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.

🧪 test(stylex): add the style-equivalence verifier and rerun all stack PRs (#22041)

Innei676875e79459
diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.md
index dec5ae7858b..7153127619f 100644
--- a/.agents/skills/react/SKILL.md
+++ b/.agents/skills/react/SKILL.md
@@ -18,13 +18,33 @@ user-invocable: false
### StyleX
- New code may not import `createStaticStyles` / `createStyles` / `css` / `keyframes` / `createGlobalStyle` / `injectGlobal` from `@lobehub/ui` (`stylex-migration/no-emotion-styles`). Files still on them are listed in `scripts/stylexMigration/legacyFiles.json`; after migrating one, run `bun run stylex:migration --prune-legacy`. Never add entries.
+- New code may not import a plain `.css` file either (`stylex-migration/no-plain-css`; CSS modules and package stylesheets are fine). Files that already do are listed in `scripts/stylexMigration/plainCssImporters.json`, which only shrinks.
- Migrate a whole file at once. StyleX longhand rules carry raised specificity (`.x:not(#\#)`) and beat emotion classes on the same element, but StyleX shorthand rules do not, so a half-migrated element resolves by property.
-- Element that also forwards a caller's `className` / `style`: `{...sx([styles.root, active && styles.active], className, style)}` from `@/styles/sx`. Spreading `stylex.props` next to `className` fails `@stylexjs/no-conflicting-props`.
+- Element that also forwards a caller's `className` / `style`: `{...sx(styles.root, active && styles.active, className, style)}` from `@/styles/sx`. Arguments are variadic like `stylex.props`: strings become class names and plain objects merge into the inline style, so pass only what you have (`sx(styles.bg, { backgroundImage })`), never an array or an `undefined` placeholder. Spreading `stylex.props` next to `className` fails `@stylexjs/no-conflicting-props`.
- Component that lets callers restyle it: take `xstyle?: StyleXStyles` and pass it last in the `sx` / `stylex.props` array. A plain `className` from outside cannot override StyleX rules. Passing a class to `@lobehub/ui` components (`className`, `classNames`) works, because lobe-ui CSS sits in `@layer lobe-ui`.
- Values follow `@stylexjs/valid-styles`: no multi-value shorthands (`margin: '0 8px'` → `marginBlock` / `marginInline`), and string `flex` (`flex: '1'`).
- `background`, `animation`, `border` and `border{Top,Right,Bottom,Left}` shorthands compile to no class at all, whatever the value (`border: 'none'` included), without an error. Write longhands: `backgroundColor` (plus `backgroundImage: 'none'` when replacing a `background` shorthand), `animationName` / `animationDuration` / …, `borderWidth` / `borderStyle` / `borderColor`.
+- Traps that compile cleanly but render differently from the emotion original (each one shipped in the migration stack):
+ - `all: 'unset'` compiles to nothing. Write the resets out (`appearance`, `margin`, `padding`, `border*`, `font: 'inherit'`, `textAlign`, …).
+ - Keep reset semantics: `outline: none` → `outline: 'none'` (not `outlineStyle`); `border: 0` → `borderWidth: 0` + `borderStyle: 'none'` + `borderColor: 'currentcolor'`; `font: inherit` → `font: 'inherit'`, not a few font longhands; reduced-motion `animation: none` → reset `animationName`, `animationDuration`, `animationTimingFunction`, `animationIterationCount` (and `animationFillMode` if set). Inside `stylex.keyframes`, `background` compiles to an empty frame: use `backgroundColor`.
+ - Longhands always beat shorthands, whatever the order: `paddingBlockStart` beats `paddingBlock`, `flexShrink` beats `flex`. Two overlapping shorthands (`borderWidth: 0` with `borderInlineWidth: '1px'`) do not layer either: write disjoint ones (`borderBlockWidth` + `borderInlineWidth`). Merged styles must write a property at the same level.
+ - Order: lobe-ui `cx(a, b)` calls `emotion.cx`, which merges classes from the same emotion cache in argument order (last wins), the same as `stylex.props(a, b)`. Only what it cannot merge (plain strings, StyleX classes, another cache) falls back to stylesheet order. Keep the original argument order unless the base actually renders otherwise.
+ - A per-property map replaces the whole map: a state style (`active`, `selected`) that sets `backgroundColor` wipes an earlier `':hover'` on it, and `{ default: null, ':hover': x }` wipes an earlier style's default. Carry both: `{ default: <state>, ':hover': <hover> }`.
+ - Dynamic StyleX functions carry their values in an inline `style`: spread `stylex.props(fn(x))` or use `sx`, never `.className` alone. StyleX objects passed into `cx()` vanish.
+ - Keep physical edges and corners when the original used them (`border-radius: 0 r r 0` → `borderTopRightRadius` …); logical properties flip in RTL.
+ - Strict media ranges: `620px < width` compiles to `width >= 620.01px`, which Chrome matches at a 620px viewport. For disjoint ranges write `620.02px <= width`.
+ - Do not add declarations the original did not have (a `transition` on an element nothing animates).
+ - `stylex.when.ancestor(...)` without a marker listens to every ancestor carrying `stylex.defaultMarker()`, including unrelated wrappers (a scroll container, a layout cell). For a hover / focus reveal give the owner a private `stylex.defineMarker()` from a `markers.stylex.ts` beside it.
+ - `stylex.when.siblingBefore(...)` compiles to the general sibling combinator `~`, not `+`, and only sees siblings that carry the marker. It reproduces `& + &` only when the matching siblings are always contiguous and marked; otherwise pass an explicit prop (`divided`, `index > 0`).
+ - Keep `!important` when the competitor is an inline style: lobe-ui writes some properties inline (ActionIcon / Avatar with a numeric `size` → `borderRadius`, `width`; Image → `maxWidth`). Without it the inline value wins; pass the value through the component's `style` instead.
+ - A caller's StyleX className passed through `className` into a component that applies its own StyleX on the same property gives one element two atomic classes for it, and the build's sort order (not argument order) picks the winner. Restyle our own components through an `xstyle` prop merged last.
- Check a migration in dev with the DevDock snapshot helper: on the migrated page run `__lobeStyleSnapshot.capture('<name>', '<root selector>')`, back up the migrated files with their relative paths into a fresh directory (`BACKUP=$(mktemp -d) && rsync -R <paths> "$BACKUP/"`), swap in the originals (`git checkout HEAD -- <paths>`), reload, run `__lobeStyleSnapshot.compare('<name>')`, then restore the migrated files (`cp -R "$BACKUP"/. ./`). Do not use `git stash`: every checkout shares one stash stack, and a `push` with nothing to save creates no entry, so the next `pop` applies an older one. Each pair reads `[captured, current]`, here `[migrated, original]`. It lists elements and `::before` / `::after` whose tracked computed styles, box (relative to the root) or text differ; an empty list means those match, not that hover, focus or closed dialogs were checked, so open each state you migrated and compare it too. Keep the window size, scroll everything under the root back to the start, and move the pointer off the compared area.
-- `bun run stylex:migration --list <A|B|C|D>` lists files by how hard they are to move: A flat, B self pseudo-classes, C descendant / ancestor coupling (use `stylex.defaultMarker()` + `stylex.when.ancestor()` or `xstyle`), D tag / third-party DOM selectors (scoped plain CSS).
+- `bun run stylex:migration --list <A|B|C|D>` lists files by how hard they are to move: A flat, B self pseudo-classes, C descendant / ancestor coupling (use `stylex.defaultMarker()` + `stylex.when.ancestor()` or `xstyle`), D tag / third-party DOM selectors (see the next rule).
+- Never move a selector into a plain `.css` file to escape StyleX. Reach the element through an API instead, in this order:
+ 1. The component's slot props. lobe-ui components take `classNames` / `styles` per part, e.g. `Tabs` → `classNames={{ list: stylex.props(styles.tabList).className, tab: stylex.props(styles.tab).className }}`.
+ 2. A pseudo-class on the slot's element: StyleX compiles keys like `':has([data-replace-all])'` and `':nth-child(2)'`, so `.tabs [role=tab]:has([data-replace-all])` becomes `classNames.tab` with `marginInlineStart: { default: null, ':has([data-replace-all])': 'auto' }`.
+ 3. Our own component: add an `xstyle?: StyleXStyles` prop (or `<part>Xstyle` for an inner part) and apply it there.
+ 4. Only DOM no prop can reach (editor content such as `.ProseMirror p`, rendered markdown, third-party widgets, lobe-ui parts without a slot) keeps its original nested rule, unchanged, in a `createStaticStyles` object in the same file, merged onto the host element with `{...sx(styles.content, fallback.content)}`. Put `// oxlint-disable-next-line stylex-migration/no-emotion-styles -- <what no prop reaches>` above the `@lobehub/ui` import. Add a missing slot to lobe-ui instead when the component is ours.
## Component Priority
diff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.ts
index 11e754c39fd..5790fa3addc 100644
--- a/apps/cli/src/commands/doc.test.ts
+++ b/apps/cli/src/commands/doc.test.ts
@@ -225,12 +225,10 @@ describe('doc command', () => {
it('should report truncation when --all reaches its page cap', async () => {
mockTrpcClient.document.queryDocuments.query.mockReset();
- mockTrpcClient.document.queryDocuments.query.mockImplementation(
- async ({ current }: any) => ({
- items: [{ id: `doc${current}`, title: 'A' }],
- total: 5000,
- }),
- );
+ mockTrpcClient.document.queryDocuments.query.mockImplementation(async ({ current }: any) => ({
+ items: [{ id: `doc${current}`, title: 'A' }],
+ total: 5000,
+ }));
const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
try {
@@ -260,12 +258,10 @@ describe('doc command', () => {
it('should not report a complete total when --all is capped in table mode', async () => {
mockTrpcClient.document.queryDocuments.query.mockReset();
- mockTrpcClient.document.queryDocuments.query.mockImplementation(
- async ({ current }: any) => ({
- items: [{ id: `doc${current}`, title: 'A' }],
- total: 1200,
- }),
- );
+ mockTrpcClient.document.queryDocuments.query.mockImplementation(async ({ current }: any) => ({
+ items: [{ id: `doc${current}`, title: 'A' }],
+ total: 1200,
+ }));
const program = createProgram();
await program.parseAsync(['node', 'test', 'doc', 'list', '-L', '1', '--all']);
diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.ts
index 9cdb9c9f76e..383fc52ab41 100644
--- a/apps/cli/src/commands/doc.ts
+++ b/apps/cli/src/commands/doc.ts
@@ -185,9 +185,7 @@ export function registerDocCommand(program: Command) {
const range = `${from}-${to}${total === undefined ? '' : ` of ${total}`}`;
const pager =
pageCount === undefined ? `page ${page + 1}` : `page ${page + 1}/${pageCount}`;
- log.info(
- `${range} · ${pager}${hasNext ? ` · next: --page ${page + 1}` : ' · last page'}`,
- );
+ log.info(`${range} · ${pager}${hasNext ? ` · next: --page ${page + 1}` : ' · last page'}`);
},
);
diff --git a/oxlint.config.mts b/oxlint.config.mts
index 812ceddb3bc..541061a18bb 100644
--- a/oxlint.config.mts
+++ b/oxlint.config.mts
@@ -811,6 +811,7 @@ export default defineConfig(
{
files: [
'packages/agent-tracing/**/*',
+ 'packages/style-equivalence/src/cli/**/*',
'apps/cli/**/*',
'packages/model-runtime/src/utils/debugStream.ts',
],
@@ -829,6 +830,29 @@ export default defineConfig(
],
rules: { '@eslint-react/no-unnecessary-use-prefix': 'off' },
},
+ restrictImports(
+ ['packages/style-equivalence/**/*'],
+ [
+ 'error',
+ {
+ ...baseRestrictedImportOptions,
+ patterns: [
+ ...baseRestrictedImportOptions.patterns,
+ {
+ message:
+ 'style-equivalence is project-agnostic; pass lobe-chat specifics through its config.',
+ regex: '^@/',
+ },
+ {
+ message:
+ 'style-equivalence is project-agnostic; pass lobe-chat specifics through its config.',
+ regex:
+ '^(?:\\.\\./)+(?:apps|scripts|src/(?:app|business|components|config|const|envs|features|helpers|hooks|layout|libs|locales|routes|server|services|spa|store|styles|types|utils))/',
+ },
+ ],
+ },
+ ],
+ ),
...(stylexMigrationOverrides as UserOverride[]),
// CommonJS files rely on `require()` by design
{
diff --git a/package.json b/package.json
index c4dc9fc1821..b9a938e8dbd 100644
--- a/package.json
+++ b/package.json
@@ -123,6 +123,8 @@
"self-hosting:docker": "docker build -t lobehub:local .",
"self-hosting:docker-cn": "docker build -t lobehub-local --build-arg USE_CN_MIRROR=true .",
"start": "next start -p 3210",
+ "style-eq": "bun packages/style-equivalence/src/cli/index.ts",
+ "style-eq:test": "cd packages/style-equivalence && vitest run --silent=passed-only",
"stylelint": "stylelint \"src/**/*.{css,less}\" --fix --allow-empty-input",
"stylex:migration": "tsx scripts/stylexMigration/index.ts",
"stylex:verify": "bun scripts/stylexMigration/verification/run.ts",
@@ -331,7 +333,7 @@
"@lobehub/editor": "7.2.1",
"@lobehub/icons": "^6.13.0",
"@lobehub/market-sdk": "0.46.0",
- "@lobehub/ui": "^6.12.0",
+ "@lobehub/ui": "^6.13.1",
"@modelcontextprotocol/client": "~2.4.0",
"@modelcontextprotocol/ext-apps": "^2.0.3",
"@neondatabase/serverless": "^1.1.0",
diff --git a/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx b/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx
index ebf9357dfbe..e1e8ed2a660 100644
--- a/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx
+++ b/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx
@@ -1,8 +1,10 @@
'use client';
import { type BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type TFunction } from 'i18next';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -32,39 +34,35 @@ const resolveLabel = (t: TFunction<'plugin'>, source: ActivateSkillSource | unde
}
};
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- max-width: 100%;
- margin-inline-start: 6px;
- padding-block: 3px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 999px;
-
- background: ${cssVar.colorBgContainer};
- `,
- skillIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- skillName: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '100%',
+ marginInlineStart: '6px',
+ paddingBlock: '3px',
+ paddingInline: '10px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ skillIcon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ skillName: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const ActivateSkillInspector = memo<
BuiltinInspectorProps<ActivateSkillParams, ActivateSkillState>
@@ -86,9 +84,9 @@ export const ActivateSkillInspector = memo<
return (
<div className={inspectorTextStyles.root}>
<span className={shinyTextStyles.shinyText}>{label}:</span>
- <span className={styles.chip}>
- <SkillsIcon className={styles.skillIcon} size={12} />
- <span className={styles.skillName}>{displayName}</span>
+ <span {...stylex.props(styles.chip)}>
+ <SkillsIcon className={stylex.props(styles.skillIcon).className} size={12} />
+ <span {...stylex.props(styles.skillName)}>{displayName}</span>
</span>
</div>
);
@@ -98,9 +96,9 @@ export const ActivateSkillInspector = memo<
<div className={inspectorTextStyles.root}>
<span className={cx(isLoading && shinyTextStyles.shinyText)}>{label}:</span>
{displayName && (
- <span className={styles.chip}>
- <SkillsIcon className={styles.skillIcon} size={12} />
- <span className={styles.skillName}>{displayName}</span>
+ <span {...stylex.props(styles.chip)}>
+ <SkillsIcon className={stylex.props(styles.skillIcon).className} size={12} />
+ <span {...stylex.props(styles.skillName)}>{displayName}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx b/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
index 4aa29b90bb4..89ee64ee49e 100644
--- a/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
+++ b/packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx
@@ -1,9 +1,9 @@
'use client';
import { type BuiltinInspectorProps } from '@lobechat/types';
-import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
-import { Avatar } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Avatar, Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AlertTriangle } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,46 +12,35 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ActivatedToolInfo, ActivateToolsParams, ActivateToolsState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- notFoundHint: css`
- flex-shrink: 0;
- max-width: 100%;
- font-size: 12px;
- color: ${cssVar.colorWarning};
- `,
- tool: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- padding-block: 2px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
- toolName: css`
- overflow: hidden;
- min-width: 0;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- tools: css`
- display: inline-flex;
- flex-wrap: wrap;
- gap: 4px;
- align-items: center;
-
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({
+ notFoundHint: { flexShrink: 0, maxWidth: '100%', fontSize: '12px', color: cssVar.colorWarning },
+ tool: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ toolName: { overflow: 'hidden', minWidth: '0', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+ tools: {
+ display: 'inline-flex',
+ flexWrap: 'wrap',
+ gap: '4px',
+ alignItems: 'center',
+ marginInlineStart: '4px',
+ },
+});
export const ActivateToolsInspector = memo<
BuiltinInspectorProps<ActivateToolsParams, ActivateToolsState>
@@ -74,10 +63,10 @@ export const ActivateToolsInspector = memo<
{t('builtins.lobe-activator.apiName.activateTools')}
</span>
{identifiers && identifiers.length > 0 && (
- <span className={styles.tools}>
+ <span {...stylex.props(styles.tools)}>
{identifiers.map((id) => (
- <span className={styles.tool} key={id}>
- <span className={styles.toolName}>{id}</span>
+ <span {...stylex.props(styles.tool)} key={id}>
+ <span {...stylex.props(styles.toolName)}>{id}</span>
</span>
))}
</span>
@@ -101,7 +90,7 @@ export const ActivateToolsInspector = memo<
<span>{t('builtins.lobe-activator.apiName.activateTools')}</span>
{hasNotFound && (
<Tooltip title={notFoundTitle}>
- <Flexbox horizontal className={styles.notFoundHint} gap={4}>
+ <Flexbox horizontal className={stylex.props(styles.notFoundHint).className} gap={4}>
<Icon color={cssVar.colorWarning} icon={AlertTriangle} />
<span>
{t('builtins.lobe-activator.inspector.activateTools.notFoundCount', {
@@ -112,11 +101,11 @@ export const ActivateToolsInspector = memo<
</Tooltip>
)}
{visibleTools.length > 0 && (
- <span className={styles.tools}>
+ <span {...stylex.props(styles.tools)}>
{visibleTools.map((tool) => (
- <span className={styles.tool} key={tool.identifier}>
+ <span {...stylex.props(styles.tool)} key={tool.identifier}>
{tool.avatar && <Avatar avatar={tool.avatar} size={14} title={tool.name} />}
- <span className={styles.toolName}>{tool.name}</span>
+ <span {...stylex.props(styles.toolName)}>{tool.name}</span>
</span>
))}
</span>
diff --git a/packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx b/packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx
index 5beb4ddddc2..d11f04a2d45 100644
--- a/packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx
+++ b/packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx
@@ -2,39 +2,34 @@
import { type BuiltinRenderProps } from '@lobechat/types';
import { Flexbox, Markdown, ScrollShadow } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { ActivateSkillParams, ActivateSkillState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-block: 8px;
- padding-inline: 16px;
- font-size: 14px;
- `,
- description: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- header: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- name: css`
- font-weight: 500;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingBlock: '8px', paddingInline: '16px', fontSize: '14px' },
+ description: { fontSize: '12px', color: cssVar.colorTextSecondary },
+ header: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ name: { fontWeight: 500 },
+});
const ActivateSkill = memo<BuiltinRenderProps<ActivateSkillParams, ActivateSkillState>>(
({ content, pluginState }) => {
@@ -44,13 +39,18 @@ const ActivateSkill = memo<BuiltinRenderProps<ActivateSkillParams, ActivateSkill
if (!displayName) return null;
return (
- <Flexbox className={styles.container}>
- <Flexbox className={styles.header} gap={4}>
- <span className={styles.name}>{displayName}</span>
- {description && <span className={styles.description}>{description}</span>}
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox className={stylex.props(styles.header).className} gap={4}>
+ <span {...stylex.props(styles.name)}>{displayName}</span>
+ {description && <span {...stylex.props(styles.description)}>{description}</span>}
</Flexbox>
{content && (
- <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>
+ <ScrollShadow
+ className={stylex.props(styles.content).className}
+ offset={12}
+ size={12}
+ style={{ maxHeight: 400 }}
+ >
<Markdown style={{ overflow: 'unset' }} variant={'chat'}>
{content}
</Markdown>
diff --git a/packages/builtin-tool-activator/vitest.config.mts b/packages/builtin-tool-activator/vitest.config.mts
index a9f5456ffd2..499e6228649 100644
--- a/packages/builtin-tool-activator/vitest.config.mts
+++ b/packages/builtin-tool-activator/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'happy-dom',
},
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx
index 3d533073b10..c5b8ae40283 100644
--- a/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { InstallPluginParams, InstallPluginState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const InstallPluginInspector = memo<
BuiltinInspectorProps<InstallPluginParams, InstallPluginState>
@@ -49,9 +46,17 @@ export const InstallPluginInspector = memo<
{!isLoading &&
hasResult &&
(isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
))}
</div>
);
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx
index 941c9a71cf6..d3deb94bab9 100644
--- a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { UpdateAgentConfigParams, UpdateConfigState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const UpdateConfigInspector = memo<
BuiltinInspectorProps<UpdateAgentConfigParams, UpdateConfigState>
@@ -82,7 +79,11 @@ export const UpdateConfigInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx
index 5fed344bfb5..ea48f46c54e 100644
--- a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,12 +12,7 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { UpdatePromptParams, UpdatePromptState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const UpdatePromptInspector = memo<
BuiltinInspectorProps<UpdatePromptParams, UpdatePromptState>
@@ -84,7 +80,11 @@ export const UpdatePromptInspector = memo<
</Text>
)}
{!isLoading && !isArgumentsStreaming && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx b/packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx
index d1f3ba4b4e0..9c9d8f2955f 100644
--- a/packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx
+++ b/packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx
@@ -1,8 +1,8 @@
'use client';
-import { CodeDiff, CopyButton, Flexbox, ScrollShadow, TooltipGroup } from '@lobehub/ui';
-import { ActionIcon } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { ActionIcon, CodeDiff, CopyButton, Flexbox, ScrollShadow, TooltipGroup } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckCircle, FileText, Maximize2, Minimize2 } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,81 +19,62 @@ const INSPECTOR_CHECK_COLUMN = 24;
const withTrailingNewline = (value: string) =>
value === '' || value.endsWith('\n') ? value : `${value}\n`;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
- width: 100%;
- min-width: 0;
- font-size: 13px;
- `,
- contentBox: css`
- overflow: hidden;
-
- width: 100%;
- min-width: 0;
- padding: 12px;
- border-inline-start: 3px solid ${cssVar.colorSuccess};
-
- background: ${cssVar.colorFillTertiary};
- `,
- diff: css`
- overflow: hidden;
- width: 100%;
- min-width: 0;
- `,
- diffPanel: css`
- border-radius: 0;
- `,
- fileIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextTertiary};
- `,
- promptContent: css`
- min-width: 0;
-
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorText};
- word-break: break-word;
- overflow-wrap: anywhere;
- white-space: pre-wrap;
- `,
- promptLabel: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- statusIcon: css`
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- width: 24px;
- height: 24px;
- `,
- statusRow: css`
- width: calc(100% - 12px);
- min-width: 0;
- margin-inline-start: 4px;
- color: ${cssVar.colorSuccess};
- `,
- statusText: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', width: '100%', minWidth: '0', fontSize: '13px' },
+ contentBox: {
+ overflow: 'hidden',
+ width: '100%',
+ minWidth: '0',
+ padding: '12px',
+ borderInlineStartWidth: '3px',
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ diff: { overflow: 'hidden', width: '100%', minWidth: '0' },
+ diffPanel: { borderRadius: '0' },
+ fileIcon: { flexShrink: 0, color: cssVar.colorTextTertiary },
+ promptContent: {
+ minWidth: '0',
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorText,
+ wordBreak: 'break-word',
+ overflowWrap: 'anywhere',
+ whiteSpace: 'pre-wrap',
+ },
+ promptLabel: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ statusIcon: {
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '24px',
+ height: '24px',
+ },
+ statusRow: {
+ width: 'calc(100% - 12px)',
+ minWidth: '0',
+ marginInlineStart: '4px',
+ color: cssVar.colorSuccess,
+ },
+ statusText: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontWeight: 500,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export interface PromptDiffViewProps {
/**
@@ -151,32 +132,32 @@ const PromptDiffView = memo<PromptDiffViewProps>(({ newPrompt = '', previousProm
);
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Flexbox
horizontal
align={'center'}
- className={styles.statusRow}
+ className={stylex.props(styles.statusRow).className}
distribution={'space-between'}
gap={8}
>
<Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>
- <span className={styles.statusIcon}>
+ <span {...stylex.props(styles.statusIcon)}>
<CheckCircle size={14} />
</span>
- <span className={styles.statusText}>{t(statusKey)}</span>
+ <span {...stylex.props(styles.statusText)}>{t(statusKey)}</span>
</Flexbox>
{actions}
</Flexbox>
{hasDiff && (
<ScrollShadow
- className={styles.diff}
+ className={stylex.props(styles.diff).className}
offset={12}
size={12}
style={{ maxHeight: contentMaxHeight }}
>
<CodeDiff
- className={styles.diffPanel}
+ className={stylex.props(styles.diffPanel).className}
language={'markdown'}
newContent={withTrailingNewline(newPrompt)}
oldContent={withTrailingNewline(previousPrompt)}
@@ -188,17 +169,17 @@ const PromptDiffView = memo<PromptDiffViewProps>(({ newPrompt = '', previousProm
)}
{showPreview && (
- <Flexbox className={styles.contentBox} gap={8}>
+ <Flexbox className={stylex.props(styles.contentBox).className} gap={8}>
<Flexbox horizontal align={'center'} gap={6}>
- <FileText className={styles.fileIcon} size={14} />
- <span className={styles.promptLabel}>
+ <FileText className={stylex.props(styles.fileIcon).className} size={14} />
+ <span {...stylex.props(styles.promptLabel)}>
{t('builtins.lobe-agent-builder.render.updatePrompt.newPrompt', {
count: newPrompt.length,
})}
</span>
</Flexbox>
<ScrollShadow
- className={styles.promptContent}
+ className={stylex.props(styles.promptContent).className}
offset={12}
size={12}
style={{ maxHeight: contentMaxHeight }}
diff --git a/packages/builtin-tool-agent-builder/vitest.config.mts b/packages/builtin-tool-agent-builder/vitest.config.mts
index 1d6d3125033..d586038d5a2 100644
--- a/packages/builtin-tool-agent-builder/vitest.config.mts
+++ b/packages/builtin-tool-agent-builder/vitest.config.mts
@@ -2,7 +2,10 @@ import path from 'node:path';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
alias: {
'@': path.resolve(__dirname, '../../src'),
diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx
index ebe4fdb80de..0f7072ce3ec 100644
--- a/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,23 +12,23 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { RemoveDocumentArgs, RemoveDocumentState } from '../../../types';
import { formatDocumentId } from '../_styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- removeChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border: 1px dashed ${cssVar.colorErrorBorder};
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorError};
- text-decoration: line-through;
-
- background: transparent;
- `,
-}));
+const styles = stylex.create({
+ removeChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorErrorBorder,
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorError,
+ textDecoration: 'line-through',
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ },
+});
export const RemoveDocumentInspector = memo<
BuiltinInspectorProps<RemoveDocumentArgs, RemoveDocumentState>
@@ -43,7 +45,7 @@ export const RemoveDocumentInspector = memo<
>
{t('builtins.lobe-agent-documents.apiName.removeDocument')}
</span>
- {id && <span className={styles.removeChip}>{formatDocumentId(id)}</span>}
+ {id && <span {...stylex.props(styles.removeChip)}>{formatDocumentId(id)}</span>}
</div>
);
});
diff --git a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx
index d4f1070e634..e050cec540b 100644
--- a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx
@@ -1,8 +1,16 @@
'use client';
-import { CopyButton, Flexbox, Markdown, ScrollShadow, TooltipGroup } from '@lobehub/ui';
-import { ActionIcon, Button } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ CopyButton,
+ Flexbox,
+ Markdown,
+ ScrollShadow,
+ TooltipGroup,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileTextIcon, Maximize2, Minimize2, PencilLine } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,48 +18,43 @@ import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- position: relative;
-
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-inline: 16px;
- font-size: 14px;
- `,
- expandButton: css`
- position: absolute;
- inset-block-end: 16px;
- inset-inline-start: 50%;
- transform: translateX(-50%);
-
- box-shadow: ${cssVar.boxShadow};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- color: ${cssVar.colorPrimary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ position: 'relative',
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingInline: '16px', fontSize: '14px' },
+ expandButton: {
+ position: 'absolute',
+ insetBlockEnd: '16px',
+ insetInlineStart: '50%',
+ transform: 'translateX(-50%)',
+ boxShadow: cssVar.boxShadow,
+ },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: { color: cssVar.colorPrimary },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
interface DocumentCardProps {
content: string;
@@ -80,11 +83,16 @@ const DocumentCard = memo<DocumentCardProps>(({ content, documentId, readonly, t
};
return (
- <Flexbox className={styles.container}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
- <FileTextIcon className={styles.icon} size={16} />
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
+ <FileTextIcon className={stylex.props(styles.icon).className} size={16} />
<Flexbox flex={1}>
- <div className={styles.title}>{title}</div>
+ <div {...stylex.props(styles.title)}>{title}</div>
</Flexbox>
<TooltipGroup>
<Flexbox horizontal gap={4}>
@@ -104,7 +112,12 @@ const DocumentCard = memo<DocumentCardProps>(({ content, documentId, readonly, t
</Flexbox>
</TooltipGroup>
</Flexbox>
- <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>
+ <ScrollShadow
+ className={stylex.props(styles.content).className}
+ offset={12}
+ size={12}
+ style={{ maxHeight: 400 }}
+ >
<Markdown style={{ overflow: 'unset', paddingBottom: 40 }} variant={'chat'}>
{content}
</Markdown>
@@ -112,7 +125,7 @@ const DocumentCard = memo<DocumentCardProps>(({ content, documentId, readonly, t
{documentId && !readonly && (
<Button
- className={styles.expandButton}
+ className={stylex.props(styles.expandButton).className}
icon={isExpanded ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
shape={'round'}
type={'default'}
diff --git a/packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx
index 1ae6318d8f6..4e025513051 100644
--- a/packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Spin } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Spin } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileTextIcon } from 'lucide-react';
import { memo } from 'react';
@@ -12,34 +12,34 @@ import StreamingMarkdown from '@/components/StreamingMarkdown';
import type { CreateDocumentArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- color: ${cssVar.colorPrimary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: { color: cssVar.colorPrimary },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
export const CreateDocumentStreaming = memo<BuiltinStreamingProps<CreateDocumentArgs>>(
({ args }) => {
@@ -48,11 +48,16 @@ export const CreateDocumentStreaming = memo<BuiltinStreamingProps<CreateDocument
if (!content && !title) return null;
return (
- <Flexbox className={styles.container}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
- <FileTextIcon className={styles.icon} size={16} />
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
+ <FileTextIcon className={stylex.props(styles.icon).className} size={16} />
<Flexbox flex={1}>
- <div className={styles.title}>{title}</div>
+ <div {...stylex.props(styles.title)}>{title}</div>
</Flexbox>
<Spin size="middle" variant="network" />
</Flexbox>
diff --git a/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx b/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx
index 44880bfaea5..aefc59f77f1 100644
--- a/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileTextIcon, FolderIcon, HomeIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -8,16 +10,10 @@ import { useTranslation } from 'react-i18next';
import { describeDocumentRef } from './describeDocumentRef';
import type { AgentDocumentLookup } from './useAgentDocumentLookup';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- icon: css`
- flex: none;
- color: ${cssVar.colorTextDescription};
- `,
- id: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- `,
-}));
+const styles = stylex.create({
+ icon: { flex: 'none', color: cssVar.colorTextDescription },
+ id: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },
+});
interface DocumentRefProps {
/** Title to show when the id no longer resolves (e.g. from a tool result). */
@@ -35,7 +31,7 @@ const DocumentRef = memo<DocumentRefProps>(({ fallbackTitle, lookup, refId, stro
if (view.kind === 'unknown') {
return (
- <Text className={styles.id} type={'secondary'}>
+ <Text className={stylex.props(styles.id).className} type={'secondary'}>
{t('builtins.lobe-agent-documents.ref.unknown', { id: view.id })}
</Text>
);
@@ -46,7 +42,7 @@ const DocumentRef = memo<DocumentRefProps>(({ fallbackTitle, lookup, refId, stro
return (
<Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>
- <Icon className={styles.icon} icon={icon} size={14} />
+ <Icon className={stylex.props(styles.icon).className} icon={icon} size={14} />
<Text ellipsis strong={strong}>
{title}
</Text>
diff --git a/packages/builtin-tool-agent-documents/vitest.config.mts b/packages/builtin-tool-agent-documents/vitest.config.mts
index 52f86e133c7..f32927c6b6b 100644
--- a/packages/builtin-tool-agent-documents/vitest.config.mts
+++ b/packages/builtin-tool-agent-documents/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
coverage: {
provider: 'v8',
diff --git a/packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx
index dc202752579..d5e57390dd1 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx
@@ -2,22 +2,21 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { CallAgentParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const CallAgentRender = memo<BuiltinRenderProps<CallAgentParams>>(({ args }) => {
const { instruction } = args || {};
@@ -25,8 +24,8 @@ export const CallAgentRender = memo<BuiltinRenderProps<CallAgentParams>>(({ args
if (!instruction) return null;
return (
- <div className={styles.container}>
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown variant={'chat'}>{instruction}</Markdown>
</div>
</div>
diff --git a/packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx
index 28c34173cc9..ff3ef54229d 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx
@@ -2,66 +2,44 @@
import { AGENT_CHAT_URL } from '@lobechat/const';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Flexbox, Markdown } from '@lobehub/ui';
-import { Avatar, Tag } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Avatar, Block, Flexbox, Markdown, Tag } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ArrowRight } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useNavigate } from 'react-router';
import type { CreateAgentParams, CreateAgentState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentCard: css`
- cursor: pointer;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-radius: 8px;
-
- background: ${cssVar.colorFillQuaternary};
-
- transition: background 0.2s;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- agentDescription: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- agentTitle: css`
- font-size: 13px;
- font-weight: 500;
- `,
- arrowIcon: css`
- color: ${cssVar.colorTextTertiary};
- `,
- container: css`
- padding-block: 4px;
- `,
- field: css`
- margin-block-end: 8px;
-
- &:last-child {
- margin-block-end: 0;
- }
- `,
- label: css`
- margin-block-end: 4px;
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ agentCard: {
+ cursor: 'pointer',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderRadius: '8px',
+ backgroundColor: { 'default': cssVar.colorFillQuaternary, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': 'none', ':hover': 'none' },
+ transition: 'background 0.2s',
+ },
+ agentDescription: {
+ overflow: 'hidden',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ agentTitle: { fontSize: '13px', fontWeight: 500 },
+ arrowIcon: { color: cssVar.colorTextTertiary },
+ container: { paddingBlock: '4px' },
+ field: { marginBlockEnd: { 'default': '8px', ':last-child': '0' } },
+ label: {
+ marginBlockEnd: '4px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ },
+ value: { fontSize: '13px' },
+});
export const CreateAgentRender = memo<BuiltinRenderProps<CreateAgentParams, CreateAgentState>>(
({ args, pluginState }) => {
@@ -81,7 +59,7 @@ export const CreateAgentRender = memo<BuiltinRenderProps<CreateAgentParams, Crea
<Flexbox
horizontal
align={'center'}
- className={styles.agentCard}
+ className={stylex.props(styles.agentCard).className}
gap={12}
onClick={handleNavigateToAgent}
>
@@ -93,10 +71,10 @@ export const CreateAgentRender = memo<BuiltinRenderProps<CreateAgentParams, Crea
title={title || undefined}
/>
<Flexbox flex={1} gap={2}>
- <span className={styles.agentTitle}>{title}</span>
- {description && <span className={styles.agentDescription}>{description}</span>}
+ <span {...stylex.props(styles.agentTitle)}>{title}</span>
+ {description && <span {...stylex.props(styles.agentDescription)}>{description}</span>}
</Flexbox>
- <ArrowRight className={styles.arrowIcon} size={16} />
+ <ArrowRight className={stylex.props(styles.arrowIcon).className} size={16} />
</Flexbox>
);
}
@@ -105,31 +83,31 @@ export const CreateAgentRender = memo<BuiltinRenderProps<CreateAgentParams, Crea
if (!title && !description && !systemRole && !plugins?.length) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{title && (
- <div className={styles.field}>
- <div className={styles.label}>Title</div>
- <div className={styles.value}>{title}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Title</div>
+ <div {...stylex.props(styles.value)}>{title}</div>
</div>
)}
{description && (
- <div className={styles.field}>
- <div className={styles.label}>Description</div>
- <div className={styles.value}>{description}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Description</div>
+ <div {...stylex.props(styles.value)}>{description}</div>
</div>
)}
{(model || provider) && (
- <div className={styles.field}>
- <div className={styles.label}>Model</div>
- <div className={styles.value}>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Model</div>
+ <div {...stylex.props(styles.value)}>
{provider && `${provider}/`}
{model}
</div>
</div>
)}
{plugins && plugins.length > 0 && (
- <div className={styles.field}>
- <div className={styles.label}>Plugins</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Plugins</div>
<Flexbox horizontal gap={4} wrap={'wrap'}>
{plugins.map((plugin) => (
<Tag key={plugin}>{plugin}</Tag>
@@ -138,8 +116,8 @@ export const CreateAgentRender = memo<BuiltinRenderProps<CreateAgentParams, Crea
</div>
)}
{systemRole && (
- <div className={styles.field}>
- <div className={styles.label}>System Prompt</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>System Prompt</div>
<Block paddingBlock={8} paddingInline={12} variant={'outlined'} width="100%">
<Markdown fontSize={13} variant={'chat'}>
{systemRole}
diff --git a/packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx
index db76acd6399..bfde7cd35f2 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx
@@ -2,27 +2,23 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { DuplicateAgentParams, DuplicateAgentState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- label: css`
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ label: { fontSize: '12px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ value: { fontSize: '13px' },
+});
export const DuplicateAgentRender = memo<
BuiltinRenderProps<DuplicateAgentParams, DuplicateAgentState>
@@ -32,19 +28,19 @@ export const DuplicateAgentRender = memo<
if (!pluginState?.success) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
<Flexbox gap={8}>
<Flexbox gap={2}>
- <span className={styles.label}>
+ <span {...stylex.props(styles.label)}>
{t('builtins.lobe-agent-management.render.duplicateAgent.sourceId')}
</span>
- <span className={styles.value}>{pluginState.sourceAgentId}</span>
+ <span {...stylex.props(styles.value)}>{pluginState.sourceAgentId}</span>
</Flexbox>
<Flexbox gap={2}>
- <span className={styles.label}>
+ <span {...stylex.props(styles.label)}>
{t('builtins.lobe-agent-management.render.duplicateAgent.newId')}
</span>
- <span className={styles.value}>{pluginState.newAgentId}</span>
+ <span {...stylex.props(styles.value)}>{pluginState.newAgentId}</span>
</Flexbox>
</Flexbox>
</div>
diff --git a/packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx
index e0ac02e5b8e..5118eb71065 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx
@@ -1,47 +1,37 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, createStaticStyles, Flexbox, Markdown, Tag, useTheme } from '@lobehub/ui';
+import { Block, Flexbox, Markdown, Tag, useTheme } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
import type { GetAgentDetailParams, GetAgentDetailState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- field: css`
- margin-block-end: 8px;
-
- &:last-child {
- margin-block-end: 0;
- }
- `,
- header: css`
- display: flex;
- gap: 12px;
- align-items: center;
-
- margin-block-end: 12px;
- padding-block-end: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- label: css`
- margin-block-end: 4px;
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- title: css`
- font-size: 14px;
- font-weight: 600;
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ field: { marginBlockEnd: { 'default': '8px', ':last-child': '0' } },
+ header: {
+ display: 'flex',
+ gap: '12px',
+ alignItems: 'center',
+ marginBlockEnd: '12px',
+ paddingBlockEnd: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ label: {
+ marginBlockEnd: '4px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ },
+ title: { fontSize: '14px', fontWeight: 600 },
+ value: { fontSize: '13px' },
+});
export const GetAgentDetailRender = memo<
BuiltinRenderProps<GetAgentDetailParams, GetAgentDetailState>
@@ -53,9 +43,9 @@ export const GetAgentDetailRender = memo<
if (!meta && !config) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{meta && (
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<AgentAvatar
agentId={pluginState?.agentId}
avatar={meta.avatar}
@@ -65,23 +55,23 @@ export const GetAgentDetailRender = memo<
title={meta.title || undefined}
/>
<Flexbox gap={2}>
- <span className={styles.title}>{meta.title || 'Untitled'}</span>
- {meta.description && <span className={styles.value}>{meta.description}</span>}
+ <span {...stylex.props(styles.title)}>{meta.title || 'Untitled'}</span>
+ {meta.description && <span {...stylex.props(styles.value)}>{meta.description}</span>}
</Flexbox>
</div>
)}
{(config?.model || config?.provider) && (
- <div className={styles.field}>
- <div className={styles.label}>Model</div>
- <div className={styles.value}>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Model</div>
+ <div {...stylex.props(styles.value)}>
{config.provider && `${config.provider}/`}
{config.model}
</div>
</div>
)}
{config?.plugins && config.plugins.length > 0 && (
- <div className={styles.field}>
- <div className={styles.label}>Plugins</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Plugins</div>
<Flexbox horizontal gap={4} wrap={'wrap'}>
{config.plugins.map((plugin) => (
<Tag key={plugin}>{plugin}</Tag>
@@ -90,8 +80,8 @@ export const GetAgentDetailRender = memo<
</div>
)}
{meta?.tags && meta.tags.length > 0 && (
- <div className={styles.field}>
- <div className={styles.label}>Tags</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Tags</div>
<Flexbox horizontal gap={4} wrap={'wrap'}>
{meta.tags.map((tag) => (
<Tag key={tag}>{tag}</Tag>
@@ -100,8 +90,8 @@ export const GetAgentDetailRender = memo<
</div>
)}
{config?.systemRole && (
- <div className={styles.field}>
- <div className={styles.label}>System Prompt</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>System Prompt</div>
<Block paddingBlock={8} paddingInline={12} variant={'outlined'} width="100%">
<Markdown fontSize={13} variant={'chat'}>
{config.systemRole}
diff --git a/packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx
index c5128f65c05..f6b538c93f5 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx
@@ -1,39 +1,25 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Tag } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Tag } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallPluginParams, InstallPluginState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- label: css`
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- statusFail: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorError};
- `,
- statusSuccess: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorSuccess};
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ label: { fontSize: '12px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ statusFail: { fontSize: '13px', fontWeight: 500, color: cssVar.colorError },
+ statusSuccess: { fontSize: '13px', fontWeight: 500, color: cssVar.colorSuccess },
+});
export const InstallPluginRender = memo<
BuiltinRenderProps<InstallPluginParams, InstallPluginState>
@@ -43,15 +29,15 @@ export const InstallPluginRender = memo<
if (!pluginState) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
<Flexbox gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
- <span className={styles.label}>
+ <span {...stylex.props(styles.label)}>
{t('builtins.lobe-agent-management.render.installPlugin.plugin')}
</span>
<Tag>{pluginState.pluginName || pluginState.pluginId}</Tag>
</Flexbox>
- <span className={pluginState.installed ? styles.statusSuccess : styles.statusFail}>
+ <span {...stylex.props(pluginState.installed ? styles.statusSuccess : styles.statusFail)}>
{pluginState.installed
? t('builtins.lobe-agent-management.render.installPlugin.success')
: t('builtins.lobe-agent-management.render.installPlugin.failed')}
diff --git a/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx
index f8ab85d2cfd..6eee6b12ba6 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx
@@ -3,7 +3,9 @@
import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import type { BuiltinRenderProps } from '@lobechat/types';
import { agentDisplayName, agentSecondaryDisplayName } from '@lobechat/types';
-import { createStaticStyles, Flexbox, useTheme } from '@lobehub/ui';
+import { Flexbox, useTheme } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,66 +13,57 @@ import AgentAvatar from '@/components/AgentAvatar';
import type { AgentSearchItem, SearchAgentParams, SearchAgentState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentItem: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: 6px;
- background: ${cssVar.colorFillQuaternary};
- `,
- agentRole: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- agentTitle: css`
- font-size: 13px;
- font-weight: 500;
- `,
- container: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
-
- padding: 12px;
- border-radius: 8px;
-
- background: ${cssVar.colorFillQuaternary};
- `,
- description: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- heteroBadge: css`
- padding-block: 2px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-size: 10px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillSecondary};
- `,
- marketBadge: css`
- padding-block: 2px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-size: 10px;
- color: ${cssVar.colorPrimary};
-
- background: ${cssVar.colorPrimaryBg};
- `,
- noResults: css`
- padding: 12px;
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
- `,
-}));
+const styles = stylex.create({
+ agentItem: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: '6px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ agentRole: { fontSize: '12px', color: cssVar.colorTextTertiary },
+ agentTitle: { fontSize: '13px', fontWeight: 500 },
+ container: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ description: {
+ overflow: 'hidden',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ heteroBadge: {
+ paddingBlock: '2px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontSize: '10px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ marketBadge: {
+ paddingBlock: '2px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontSize: '10px',
+ color: cssVar.colorPrimary,
+ backgroundColor: cssVar.colorPrimaryBg,
+ backgroundImage: 'none',
+ },
+ noResults: {
+ padding: '12px',
+ fontSize: '13px',
+ color: cssVar.colorTextSecondary,
+ textAlign: 'center',
+ },
+});
export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, SearchAgentState>>(
({ pluginState }) => {
@@ -80,14 +73,14 @@ export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, Sear
if (agents.length === 0) {
return (
- <div className={styles.noResults}>
+ <div {...stylex.props(styles.noResults)}>
{t('builtins.lobe-agent-builder.inspector.noResults')}
</div>
);
}
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{agents.map((agent: AgentSearchItem) => {
const displayName = agentDisplayName(agent, agent.id);
const role = agentSecondaryDisplayName(agent);
@@ -96,7 +89,7 @@ export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, Sear
<Flexbox
horizontal
align={'center'}
- className={styles.agentItem}
+ className={stylex.props(styles.agentItem).className}
gap={12}
key={agent.id}
>
@@ -110,17 +103,17 @@ export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, Sear
/>
<Flexbox flex={1} gap={2}>
<Flexbox horizontal align={'center'} gap={8}>
- <span className={styles.agentTitle}>{displayName}</span>
- {role && <span className={styles.agentRole}>{role}</span>}
+ <span {...stylex.props(styles.agentTitle)}>{displayName}</span>
+ {role && <span {...stylex.props(styles.agentRole)}>{role}</span>}
{agent.heteroType && (
- <span className={styles.heteroBadge}>
+ <span {...stylex.props(styles.heteroBadge)}>
{HETEROGENEOUS_TYPE_LABELS[agent.heteroType] ?? agent.heteroType}
</span>
)}
- {agent.isMarket && <span className={styles.marketBadge}>Market</span>}
+ {agent.isMarket && <span {...stylex.props(styles.marketBadge)}>Market</span>}
</Flexbox>
{agent.description && (
- <span className={styles.description}>{agent.description}</span>
+ <span {...stylex.props(styles.description)}>{agent.description}</span>
)}
</Flexbox>
</Flexbox>
diff --git a/packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx
index 710cf4c9a9b..11bf9aada72 100644
--- a/packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx
@@ -2,34 +2,28 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Block, Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { UpdateAgentParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- field: css`
- margin-block-end: 8px;
-
- &:last-child {
- margin-block-end: 0;
- }
- `,
- label: css`
- margin-block-end: 4px;
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ field: { marginBlockEnd: { 'default': '8px', ':last-child': '0' } },
+ label: {
+ marginBlockEnd: '4px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ },
+ value: { fontSize: '13px' },
+});
const safeParse = (val: unknown): Record<string, any> | undefined => {
if (!val) return undefined;
@@ -55,22 +49,22 @@ export const UpdateAgentRender = memo<BuiltinRenderProps<UpdateAgentParams>>(({
if (!hasConfig && !hasMeta) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{meta?.title && (
- <div className={styles.field}>
- <div className={styles.label}>Title</div>
- <div className={styles.value}>{meta.title}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Title</div>
+ <div {...stylex.props(styles.value)}>{meta.title}</div>
</div>
)}
{meta?.description && (
- <div className={styles.field}>
- <div className={styles.label}>Description</div>
- <div className={styles.value}>{meta.description}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Description</div>
+ <div {...stylex.props(styles.value)}>{meta.description}</div>
</div>
)}
{config?.systemRole && (
- <div className={styles.field}>
- <div className={styles.label}>System Prompt</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>System Prompt</div>
<Block paddingBlock={8} paddingInline={12} variant={'outlined'} width="100%">
<Markdown fontSize={13} variant={'chat'}>
{config.systemRole as string}
@@ -79,9 +73,9 @@ export const UpdateAgentRender = memo<BuiltinRenderProps<UpdateAgentParams>>(({
</div>
)}
{config?.model && (
- <div className={styles.field}>
- <div className={styles.label}>Model</div>
- <div className={styles.value}>{config.model as string}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Model</div>
+ <div {...stylex.props(styles.value)}>{config.model as string}</div>
</div>
)}
</div>
diff --git a/packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx
index e8aad88e7e2..f532dc3e05a 100644
--- a/packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx
+++ b/packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx
@@ -1,33 +1,19 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Block, Flexbox, Markdown } from '@lobehub/ui';
-import { Tag } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Flexbox, Markdown, Tag } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { CreateAgentParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- display: flex;
- flex-direction: column;
- gap: 12px;
- `,
- field: css`
- display: flex;
- flex-direction: column;
- gap: 4px;
- `,
- label: css`
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: { display: 'flex', flexDirection: 'column', gap: '12px' },
+ field: { display: 'flex', flexDirection: 'column', gap: '4px' },
+ label: { fontSize: '12px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ value: { fontSize: '13px' },
+});
export const CreateAgentStreaming = memo<BuiltinStreamingProps<CreateAgentParams>>(({ args }) => {
const { title, description, systemRole, plugins, model, provider } = args || {};
@@ -35,31 +21,31 @@ export const CreateAgentStreaming = memo<BuiltinStreamingProps<CreateAgentParams
if (!title && !description && !systemRole && !plugins?.length) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{title && (
- <div className={styles.field}>
- <div className={styles.label}>Title</div>
- <div className={styles.value}>{title}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Title</div>
+ <div {...stylex.props(styles.value)}>{title}</div>
</div>
)}
{description && (
- <div className={styles.field}>
- <div className={styles.label}>Description</div>
- <div className={styles.value}>{description}</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Description</div>
+ <div {...stylex.props(styles.value)}>{description}</div>
</div>
)}
{(model || provider) && (
- <div className={styles.field}>
- <div className={styles.label}>Model</div>
- <div className={styles.value}>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Model</div>
+ <div {...stylex.props(styles.value)}>
{provider && `${provider}/`}
{model}
</div>
</div>
)}
{plugins && plugins.length > 0 && (
- <div className={styles.field}>
- <div className={styles.label}>Plugins</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>Plugins</div>
<Flexbox horizontal gap={4} wrap={'wrap'}>
{plugins.map((plugin) => (
<Tag key={plugin}>{plugin}</Tag>
@@ -68,8 +54,8 @@ export const CreateAgentStreaming = memo<BuiltinStreamingProps<CreateAgentParams
</div>
)}
{systemRole && (
- <div className={styles.field}>
- <div className={styles.label}>System Prompt</div>
+ <div {...stylex.props(styles.field)}>
+ <div {...stylex.props(styles.label)}>System Prompt</div>
<Block paddingBlock={8} paddingInline={12} variant={'outlined'} width="100%">
<Markdown animated variant={'chat'}>
{systemRole}
diff --git a/packages/builtin-tool-agent-management/vitest.config.mts b/packages/builtin-tool-agent-management/vitest.config.mts
index 52f86e133c7..f32927c6b6b 100644
--- a/packages/builtin-tool-agent-management/vitest.config.mts
+++ b/packages/builtin-tool-agent-management/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
coverage: {
provider: 'v8',
diff --git a/packages/builtin-tool-browser/src/client/Inspector/Browser.tsx b/packages/builtin-tool-browser/src/client/Inspector/Browser.tsx
index 5e3e219c4ad..591e87ca970 100644
--- a/packages/builtin-tool-browser/src/client/Inspector/Browser.tsx
+++ b/packages/builtin-tool-browser/src/client/Inspector/Browser.tsx
@@ -2,7 +2,9 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { LucideIcon } from 'lucide-react';
import {
Camera,
@@ -20,38 +22,32 @@ import { useTranslation } from 'react-i18next';
import type { BrowserApiNameType } from '../../types';
import { BrowserApiName } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- icon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- value: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ icon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ value: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface BrowserArgs {
dx?: number;
@@ -131,9 +127,9 @@ export const BrowserInspector = memo<BuiltinInspectorProps<BrowserArgs>>(
{value ? `${label}:` : label}
</span>
{value && Icon && (
- <span className={styles.chip}>
- <Icon className={styles.icon} size={14} />
- <span className={styles.value}>{value}</span>
+ <span {...stylex.props(styles.chip)}>
+ <Icon className={stylex.props(styles.icon).className} size={14} />
+ <span {...stylex.props(styles.value)}>{value}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-browser/src/client/Render/PageAction.tsx b/packages/builtin-tool-browser/src/client/Render/PageAction.tsx
index 38b9ef3e73f..968b137ba28 100644
--- a/packages/builtin-tool-browser/src/client/Render/PageAction.tsx
+++ b/packages/builtin-tool-browser/src/client/Render/PageAction.tsx
@@ -1,34 +1,35 @@
import type { BuiltinRenderProps } from '@lobechat/types';
-import { createStaticStyles, Flexbox, Text } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Globe } from 'lucide-react';
import { memo } from 'react';
import type { BrowserPageState } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 6px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
- `,
- url: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ paddingBlock: '6px',
+ paddingInline: '10px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '8px',
+ },
+ url: { fontSize: '12px', color: cssVar.colorTextTertiary },
+});
/** Compact "acted on this page" row used by navigate/click/fill/press/scroll/setViewport. */
const PageAction = memo<BuiltinRenderProps<unknown, BrowserPageState, string>>(
({ content, pluginState }) => {
return (
- <Flexbox className={styles.container} gap={2}>
+ <Flexbox className={stylex.props(styles.container).className} gap={2}>
<Flexbox horizontal align={'center'} gap={6}>
<Globe size={14} />
<Text ellipsis>{content || pluginState?.title || 'Browser action'}</Text>
</Flexbox>
{pluginState?.url && (
- <Text ellipsis className={styles.url}>
+ <Text ellipsis className={stylex.props(styles.url).className}>
{pluginState.url}
</Text>
)}
diff --git a/packages/builtin-tool-browser/vitest.config.mts b/packages/builtin-tool-browser/vitest.config.mts
index e8853d408eb..d93efe05c50 100644
--- a/packages/builtin-tool-browser/vitest.config.mts
+++ b/packages/builtin-tool-browser/vitest.config.mts
@@ -2,7 +2,10 @@ import { resolve } from 'node:path';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
resolve: {
alias: { '@': resolve(__dirname, '../../src') },
},
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx
index cbe7e12b997..36116de2b6d 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx
@@ -2,7 +2,9 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspector, BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { LucideIcon } from 'lucide-react';
import {
Camera,
@@ -26,38 +28,32 @@ import {
parseBrowserMcpApi,
} from './browserMcpLabels';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- icon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- value: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ icon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ value: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface BrowserMcpArgs {
dx?: number;
@@ -154,9 +150,9 @@ const BrowserMcpInspector = memo<BuiltinInspectorProps<BrowserMcpArgs>>(
{value ? `${label}:` : label}
</span>
{value && (
- <span className={styles.chip}>
- <Icon className={styles.icon} size={14} />
- <span className={styles.value}>{value}</span>
+ <span {...stylex.props(styles.chip)}>
+ <Icon className={stylex.props(styles.icon).className} size={14} />
+ <span {...stylex.props(styles.value)}>{value}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx
index 376d726fb0c..7b27b4c2a12 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx
@@ -2,64 +2,56 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, Monitor as MonitorIcon, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type MonitorArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- command: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- description: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- monitorIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- statusIcon: css`
- margin-inline-start: 4px;
- `,
- timeout: css`
- flex-shrink: 0;
- margin-inline-start: 8px;
- font-feature-settings: 'tnum';
- color: ${cssVar.colorTextDescription};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ command: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ description: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ monitorIcon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ statusIcon: { marginInlineStart: '4px' },
+ timeout: {
+ flexShrink: 0,
+ marginInlineStart: '8px',
+ fontFeatureSettings: "'tnum'",
+ color: cssVar.colorTextDescription,
+ },
+});
const formatTimeout = (ms: number | undefined): string | undefined => {
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return undefined;
@@ -116,16 +108,26 @@ export const MonitorInspector = memo<BuiltinInspectorProps<MonitorArgs>>(
<div className={inspectorTextStyles.root}>
<span className={cx(isShiny && shinyTextStyles.shinyText)}>{label}:</span>
{chipText && (
- <span className={styles.chip}>
- <MonitorIcon className={styles.monitorIcon} size={12} />
- <span className={showAsCommand ? styles.command : styles.description}>{chipText}</span>
+ <span {...stylex.props(styles.chip)}>
+ <MonitorIcon className={stylex.props(styles.monitorIcon).className} size={12} />
+ <span {...stylex.props(showAsCommand ? styles.command : styles.description)}>
+ {chipText}
+ </span>
</span>
)}
- {timeoutLabel && <span className={styles.timeout}>· {timeoutLabel}</span>}
+ {timeoutLabel && <span {...stylex.props(styles.timeout)}>· {timeoutLabel}</span>}
{isLoading ? null : isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : isError ? (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
) : null}
</div>
);
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx
index 73ca706905c..890a6b5a08e 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx
@@ -2,38 +2,34 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type ScheduleWakeupArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- delay: css`
- flex-shrink: 0;
- margin-inline-start: 8px;
- color: ${cssVar.colorTextDescription};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ delay: { flexShrink: 0, marginInlineStart: '8px', color: cssVar.colorTextDescription },
+});
const formatDelay = (seconds: number): string => {
if (!Number.isFinite(seconds) || seconds <= 0) return `${seconds}s`;
@@ -73,8 +69,10 @@ export const ScheduleWakeupInspector = memo<BuiltinInspectorProps<ScheduleWakeup
<span className={cx(isShiny && shinyTextStyles.shinyText)}>
{reason || typeof delay === 'number' ? `${label}:` : label}
</span>
- {reason && <span className={styles.chip}>{reason}</span>}
- {typeof delay === 'number' && <span className={styles.delay}>· {formatDelay(delay)}</span>}
+ {reason && <span {...stylex.props(styles.chip)}>{reason}</span>}
+ {typeof delay === 'number' && (
+ <span {...stylex.props(styles.delay)}>· {formatDelay(delay)}</span>
+ )}
</div>
);
},
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx
index 59ec568bf16..d5557ab7ca6 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx
@@ -2,33 +2,33 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { SendMessageArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
/**
* Chip for the multi-agent `SendMessage` tool. Leads with the human-readable
@@ -53,7 +53,7 @@ export const SendMessageInspector = memo<BuiltinInspectorProps<SendMessageArgs>>
<span className={cx(isShiny && shinyTextStyles.shinyText)}>
{recap ? `${label}:` : label}
</span>
- {recap && <span className={styles.chip}>{recap}</span>}
+ {recap && <span {...stylex.props(styles.chip)}>{recap}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx
index 87b3a4790d8..993013717b0 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx
@@ -2,44 +2,40 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type SkillArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- skillIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- skillName: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ skillIcon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ skillName: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const SkillInspector = memo<BuiltinInspectorProps<SkillArgs>>(
({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
@@ -57,9 +53,9 @@ export const SkillInspector = memo<BuiltinInspectorProps<SkillArgs>>(
{label}
</span>
{skillName && (
- <span className={styles.chip}>
- <SkillsIcon className={styles.skillIcon} size={12} />
- <span className={styles.skillName}>{skillName}</span>
+ <span {...stylex.props(styles.chip)}>
+ <SkillsIcon className={stylex.props(styles.skillIcon).className} size={12} />
+ <span {...stylex.props(styles.skillName)}>{skillName}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx
index 965800b2ec0..a6f281d3794 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx
@@ -2,7 +2,9 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,50 +20,36 @@ const RING_STROKE = 2;
const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;
const RING_CIRCUM = 2 * Math.PI * RING_RADIUS;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- flex-shrink: 1;
-
- min-width: 0;
- margin-inline-start: 4px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillSecondary};
- `,
- countChip: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- ring: css`
- transform: rotate(-90deg);
- flex-shrink: 0;
- margin-inline-end: 6px;
- `,
- ringProgress: css`
- transition:
- stroke-dashoffset 240ms ease,
- stroke 240ms ease;
- `,
- ringTrack: css`
- stroke: ${cssVar.colorFillSecondary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ flexShrink: 1,
+ minWidth: '0',
+ marginInlineStart: '4px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ countChip: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ ring: { transform: 'rotate(-90deg)', flexShrink: 0, marginInlineEnd: '6px' },
+ ringProgress: { transition: 'stroke-dashoffset 240ms ease,\n stroke 240ms ease' },
+ ringTrack: { stroke: cssVar.colorFillSecondary },
+});
/**
* Items shape the CC adapter emits on `pluginState.todos` — normalized
@@ -109,9 +97,9 @@ const ProgressRing = memo<ProgressRingProps>(({ stats }) => {
const color = allDone ? cssVar.colorSuccess : cssVar.colorInfo;
return (
- <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>
+ <svg {...stylex.props(styles.ring)} height={RING_SIZE} width={RING_SIZE}>
<circle
- className={styles.ringTrack}
+ {...stylex.props(styles.ringTrack)}
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
fill="none"
@@ -119,7 +107,7 @@ const ProgressRing = memo<ProgressRingProps>(({ stats }) => {
strokeWidth={RING_STROKE}
/>
<circle
- className={styles.ringProgress}
+ {...stylex.props(styles.ringProgress)}
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
fill="none"
@@ -192,7 +180,7 @@ export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskP
<div className={inspectorTextStyles.root}>
<ProgressRing stats={stats} />
{stats.total > 0 && (
- <span className={styles.countChip}>
+ <span {...stylex.props(styles.countChip)}>
{stats.completed}/{stats.total}
</span>
)}
@@ -238,7 +226,7 @@ export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskP
<div className={inspectorTextStyles.root}>
<ProgressRing stats={stats} />
{stats.total > 0 && (
- <span className={styles.countChip}>
+ <span {...stylex.props(styles.countChip)}>
{stats.completed}/{stats.total}
</span>
)}
@@ -272,7 +260,7 @@ export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskP
<div className={inspectorTextStyles.root}>
<ProgressRing stats={stats} />
{stats.total > 0 && (
- <span className={styles.countChip}>
+ <span {...stylex.props(styles.countChip)}>
{stats.completed}/{stats.total}
</span>
)}
@@ -336,7 +324,7 @@ export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskP
{detail && (
<>
<span>:</span>
- <span className={styles.chip}>{detail}</span>
+ <span {...stylex.props(styles.chip)}>{detail}</span>
</>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx
index b48bf13284e..02cd8b07d21 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx
@@ -2,34 +2,34 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type TaskOutputArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
/**
* CC's tool for reading output from a background task. The only user-relevant
@@ -53,7 +53,7 @@ export const TaskOutputInspector = memo<BuiltinInspectorProps<TaskOutputArgs>>(
<span className={cx(isShiny && shinyTextStyles.shinyText)}>
{taskId ? `${label}:` : label}
</span>
- {taskId && <span className={styles.chip}>{taskId}</span>}
+ {taskId && <span {...stylex.props(styles.chip)}>{taskId}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx
index 19923390e5f..a8d6a45d3f6 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx
@@ -2,34 +2,34 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type TaskStopArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
/**
* CC's tool for terminating a background task. Falls back to the legacy
@@ -53,7 +53,7 @@ export const TaskStopInspector = memo<BuiltinInspectorProps<TaskStopArgs>>(
<span className={cx(isShiny && shinyTextStyles.shinyText)}>
{taskId ? `${label}:` : label}
</span>
- {taskId && <span className={styles.chip}>{taskId}</span>}
+ {taskId && <span {...stylex.props(styles.chip)}>{taskId}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx
index 417dde85a88..874576a14ab 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx
@@ -6,7 +6,9 @@ import {
shinyTextStyles,
} from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,33 +16,28 @@ import { ClaudeCodeApiName, type ToolSearchArgs } from '../../types';
const SELECT_PREFIX = 'select:';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- baseline: css`
- align-items: baseline;
- `,
- tag: css`
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
- tagsList: css`
- display: inline-flex;
- flex-shrink: 1;
- gap: 4px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
-
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ baseline: { alignItems: 'baseline' },
+ tag: {
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ tagsList: {
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '4px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ whiteSpace: 'nowrap',
+ },
+});
interface ParsedQuery {
names: string[] | null;
@@ -79,11 +76,11 @@ export const ToolSearchInspector = memo<BuiltinInspectorProps<ToolSearchArgs>>(
if (parsed?.names) {
return (
- <div className={cx(inspectorTextStyles.root, styles.baseline)}>
+ <div className={cx(stylex.props(styles.baseline).className, inspectorTextStyles.root)}>
<span className={cx(isShiny && shinyTextStyles.shinyText)}>{label}:</span>
- <span className={styles.tagsList}>
+ <span {...stylex.props(styles.tagsList)}>
{parsed.names.map((name, index) => (
- <span className={styles.tag} key={`${index}-${name}`}>
+ <span {...stylex.props(styles.tag)} key={`${index}-${name}`}>
{name}
</span>
))}
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx
index 70502af50da..441c85a35e6 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx
@@ -2,45 +2,41 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Globe } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type WebFetchArgs } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- icon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- url: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ icon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ url: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
/**
* Strip the protocol so the chip leads with the host — full URLs eat the
@@ -66,9 +62,9 @@ export const WebFetchInspector = memo<BuiltinInspectorProps<WebFetchArgs>>(
{url ? `${label}:` : label}
</span>
{url && (
- <span className={styles.chip}>
- <Globe className={styles.icon} size={14} />
- <span className={styles.url}>{stripProtocol(url)}</span>
+ <span {...stylex.props(styles.chip)}>
+ <Globe className={stylex.props(styles.icon).className} size={14} />
+ <span {...stylex.props(styles.url)}>{stripProtocol(url)}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx
index d68a88d50bb..e20b9e88bed 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx
@@ -2,7 +2,9 @@
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { GitForkIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -39,55 +41,45 @@ const REMOVE_LABEL_KEYS = {
loading: 'builtins.lobe-claude-code.worktree.remove.loading',
} as const;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- max-width: min(420px, 60vw);
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- icon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- leadingIcon: css`
- margin-inline-end: 6px;
- `,
- risk: css`
- flex-shrink: 0;
-
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
- target: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: 'min(420px, 60vw)',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ icon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ leadingIcon: { marginInlineEnd: '6px' },
+ risk: {
+ flexShrink: 0,
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorError,
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+ target: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
const resolvePhase = (
isArgumentsStreaming: boolean | undefined,
@@ -106,9 +98,9 @@ interface WorktreeTargetProps {
}
const WorktreeTarget = memo<WorktreeTargetProps>(({ target }) => (
- <span className={styles.chip} title={target}>
- <GitForkIcon className={styles.icon} size={12} />
- <span className={styles.target}>{target}</span>
+ <span {...stylex.props(styles.chip)} title={target}>
+ <GitForkIcon className={stylex.props(styles.icon).className} size={12} />
+ <span {...stylex.props(styles.target)}>{target}</span>
</span>
));
@@ -156,12 +148,15 @@ export const ExitWorktreeInspector = memo<BuiltinInspectorProps<ExitWorktreeArgs
return (
<div className={inspectorTextStyles.root}>
- <GitForkIcon className={cx(styles.icon, styles.leadingIcon)} size={12} />
+ <GitForkIcon
+ className={cx(stylex.props(styles.icon, styles.leadingIcon).className)}
+ size={12}
+ />
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{label}
</span>
{action === 'remove' && discardChanges && (
- <span className={styles.risk}>
+ <span {...stylex.props(styles.risk)}>
{t('builtins.lobe-claude-code.worktree.discardChanges')}
</span>
)}
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx
index 197215ceb25..bd4eeb0f876 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Markdown } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Button, Flexbox, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ListTree } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,36 +13,26 @@ import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
import type { AgentArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- label: css`
- padding-inline-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- labelRow: css`
- margin-block-end: 4px;
- `,
- openThread: css`
- height: 22px;
- padding-inline: 6px;
- font-size: 12px;
- `,
- promptBox: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorFillTertiary};
- `,
- resultBox: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ label: { paddingInlineStart: '4px', fontSize: '12px', color: cssVar.colorTextTertiary },
+ labelRow: { marginBlockEnd: '4px' },
+ openThread: { height: '22px', paddingInline: '6px', fontSize: '12px' },
+ promptBox: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ resultBox: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
/**
* Render for CC's `Agent` (subagent-spawn) tool.
@@ -96,13 +86,13 @@ const Agent = memo<BuiltinRenderProps<AgentArgs, unknown, string>>(
const showResultSection = !!result || !!subagentThread;
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
{prompt && (
<Flexbox>
- <Text className={styles.label} style={{ marginBlockEnd: 4 }}>
+ <Text className={stylex.props(styles.label).className} style={{ marginBlockEnd: 4 }}>
{t('builtins.lobe-claude-code.agent.instruction')}
</Text>
- <Flexbox className={styles.promptBox}>
+ <Flexbox className={stylex.props(styles.promptBox).className}>
<Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>
{prompt}
</Markdown>
@@ -115,13 +105,15 @@ const Agent = memo<BuiltinRenderProps<AgentArgs, unknown, string>>(
<Flexbox
horizontal
align={'center'}
- className={styles.labelRow}
+ className={stylex.props(styles.labelRow).className}
justify={'space-between'}
>
- <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>
+ <Text className={stylex.props(styles.label).className}>
+ {t('builtins.lobe-claude-code.agent.result')}
+ </Text>
{subagentThread && (
<Button
- className={styles.openThread}
+ className={stylex.props(styles.openThread).className}
icon={ListTree}
size={'small'}
type={'text'}
@@ -134,7 +126,7 @@ const Agent = memo<BuiltinRenderProps<AgentArgs, unknown, string>>(
)}
</Flexbox>
{result && (
- <Flexbox className={styles.resultBox}>
+ <Flexbox className={stylex.props(styles.resultBox).className}>
<Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>
{result}
</Markdown>
diff --git a/packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx b/packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx
index 85c591444cf..8d6691d6961 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx
@@ -1,15 +1,9 @@
'use client';
import type { BuiltinRender, BuiltinRenderProps } from '@lobechat/types';
-import {
- Block,
- createStaticStyles,
- Flexbox,
- Highlighter,
- Image,
- PreviewGroup,
- Text,
-} from '@lobehub/ui';
+import { Block, Flexbox, Highlighter, Image, PreviewGroup, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Globe } from 'lucide-react';
import { memo } from 'react';
@@ -21,14 +15,16 @@ import {
} from '../Inspector/browserMcpLabels';
import { type IntrinsicImageSize, reservedImageProps } from './reservedImageProps';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- row: css`
- padding-block: 6px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
- `,
-}));
+const styles = stylex.create({
+ row: {
+ paddingBlock: '6px',
+ paddingInline: '10px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '8px',
+ },
+});
/**
* A screenshot echoed back by the in-app browser. The MCP handler returns the
@@ -64,7 +60,7 @@ const PageRow = memo<{ content?: string }>(({ content }) => {
if (!content) return null;
return (
- <Flexbox horizontal align={'center'} className={styles.row} gap={6}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.row).className} gap={6}>
<Globe size={14} />
<Text ellipsis>{content}</Text>
</Flexbox>
diff --git a/packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx
index 0e65e8b7eda..052e155cdb9 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Icon, Markdown } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleCheckBig, SendHorizontal } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,27 +20,19 @@ const parseResult = (content: unknown): SendMessageResult | undefined => {
}
};
-const styles = createStaticStyles(({ css, cssVar }) => ({
- bodyBox: css`
- overflow: hidden;
-
- padding-block: 4px;
- padding-inline: 8px;
- border-radius: 8px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- container: css`
- padding-block: 4px;
- `,
- header: css`
- padding-inline: 4px;
- color: ${cssVar.colorTextSecondary};
- `,
- status: css`
- padding-inline: 4px;
- `,
-}));
+const styles = stylex.create({
+ bodyBox: {
+ overflow: 'hidden',
+ paddingBlock: '4px',
+ paddingInline: '8px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ container: { paddingBlock: '4px' },
+ header: { paddingInline: '4px', color: cssVar.colorTextSecondary },
+ status: { paddingInline: '4px' },
+});
const SendMessage = memo<BuiltinRenderProps<SendMessageArgs>>(({ args, content }) => {
const { t } = useTranslation('plugin');
@@ -55,8 +47,13 @@ const SendMessage = memo<BuiltinRenderProps<SendMessageArgs>>(({ args, content }
const delivered = result?.success === true;
return (
- <Flexbox className={styles.container} gap={8}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
<Icon icon={SendHorizontal} size={'small'} />
<Text ellipsis strong>
{summary || t('builtins.lobe-claude-code.sendMessage.title')}
@@ -64,7 +61,7 @@ const SendMessage = memo<BuiltinRenderProps<SendMessageArgs>>(({ args, content }
</Flexbox>
{body && (
- <Flexbox className={styles.bodyBox}>
+ <Flexbox className={stylex.props(styles.bodyBox).className}>
<Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>
{body}
</Markdown>
@@ -72,7 +69,12 @@ const SendMessage = memo<BuiltinRenderProps<SendMessageArgs>>(({ args, content }
)}
{delivered && (
- <Flexbox horizontal align={'center'} className={styles.status} gap={6}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.status).className}
+ gap={6}
+ >
<Icon icon={CircleCheckBig} size={'small'} style={{ color: cssVar.colorSuccess }} />
<Text style={{ color: cssVar.colorTextSecondary, fontSize: 12 }}>
{t('builtins.lobe-claude-code.sendMessage.queued')}
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx
index cf7047aefe4..7f7bcff5719 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx
@@ -1,45 +1,44 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Icon, Markdown } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Sparkles } from 'lucide-react';
import { memo } from 'react';
import type { SkillArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- header: css`
- padding-inline: 4px;
- color: ${cssVar.colorTextSecondary};
- `,
- previewBox: css`
- overflow: hidden;
-
- padding-block: 4px;
- padding-inline: 8px;
- border-radius: 8px;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ header: { paddingInline: '4px', color: cssVar.colorTextSecondary },
+ previewBox: {
+ overflow: 'hidden',
+ paddingBlock: '4px',
+ paddingInline: '8px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
const Skill = memo<BuiltinRenderProps<SkillArgs>>(({ args, content }) => {
const skillName = args?.skill;
return (
- <Flexbox className={styles.container} gap={8}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
<Icon icon={Sparkles} size={'small'} />
<Text strong>{skillName || 'Skill'}</Text>
</Flexbox>
{content && (
- <Flexbox className={styles.previewBox}>
+ <Flexbox className={stylex.props(styles.previewBox).className}>
<Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>
{content}
</Markdown>
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx
index b9d934e67a0..21c2a4113a3 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx
@@ -1,85 +1,69 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Icon } from '@lobehub/ui';
-import { Checkbox } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { Block, Checkbox, cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleArrowRight, CircleCheckBig, CircleX, ListTodo, RotateCcw } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ClaudeCodeApiName, type TaskUpdateArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- headerCount: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- headerDetail: css`
- overflow: hidden;
- min-width: 0;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- `,
- headerLabel: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- gap: 0;
- align-items: center;
-
- min-width: 0;
-
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- itemRow: css`
- width: 100%;
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- processingRow: css`
- display: flex;
- gap: 7px;
- align-items: center;
- `,
- textCompleted: css`
- color: ${cssVar.colorTextQuaternary};
- text-decoration: line-through;
- `,
- textPending: css`
- color: ${cssVar.colorTextSecondary};
- `,
- textProcessing: css`
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ header: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ headerCount: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ headerDetail: {
+ overflow: 'hidden',
+ minWidth: '0',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ },
+ headerLabel: {
+ overflow: 'hidden',
+ display: 'flex',
+ flex: '1',
+ gap: '0',
+ alignItems: 'center',
+ minWidth: '0',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ itemRow: {
+ width: '100%',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ processingRow: { display: 'flex', gap: '7px', alignItems: 'center' },
+ textCompleted: { color: cssVar.colorTextQuaternary, textDecoration: 'line-through' },
+ textPending: { color: cssVar.colorTextSecondary },
+ textProcessing: { color: cssVar.colorText },
+});
interface TaskPluginStateItem {
id?: string;
@@ -103,9 +87,9 @@ const TaskRow = memo<TaskRowProps>(({ item }) => {
if (status === 'processing') {
return (
- <div className={cx(styles.itemRow, styles.processingRow)}>
+ <div {...stylex.props(styles.itemRow, styles.processingRow)}>
<Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorInfo }} />
- <span className={styles.textProcessing}>{text}</span>
+ <span {...stylex.props(styles.textProcessing)}>{text}</span>
</div>
);
}
@@ -119,8 +103,8 @@ const TaskRow = memo<TaskRowProps>(({ item }) => {
shape={'circle'}
style={{ borderWidth: 1.5, cursor: 'default' }}
classNames={{
- text: cx(styles.textPending, isCompleted && styles.textCompleted),
- wrapper: styles.itemRow,
+ text: cx(stylex.props(styles.textPending, isCompleted && styles.textCompleted).className),
+ wrapper: stylex.props(styles.itemRow).className,
}}
textProps={{
type: isCompleted ? 'secondary' : undefined,
@@ -176,18 +160,18 @@ const TaskHeader = memo<TaskHeaderProps>(({ completed, total, inProgress, overri
const detail = override ? override.detail : inProgress?.text;
return (
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<Icon icon={icon} size={16} style={{ color, flexShrink: 0 }} />
- <div className={styles.headerLabel}>
+ <div {...stylex.props(styles.headerLabel)}>
<span>{label}</span>
{detail && (
<>
<span>: </span>
- <span className={styles.headerDetail}>{detail}</span>
+ <span {...stylex.props(styles.headerDetail)}>{detail}</span>
</>
)}
</div>
- <span className={styles.headerCount}>
+ <span {...stylex.props(styles.headerCount)}>
{completed}/{total}
</span>
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
index a016e1f7112..032d0a5ecd2 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
@@ -2,9 +2,9 @@
import { TodoPanelHeader } from '@lobechat/shared-tool-ui/components';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Icon } from '@lobehub/ui';
-import { Checkbox } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { Block, Checkbox, cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleArrowRight } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,33 +12,20 @@ import { useTranslation } from 'react-i18next';
import type { ClaudeCodeTodoItem, TodoWriteArgs } from '../../../types';
import { computeTodoSummary, TODO_SUMMARY_LABEL_KEYS } from '../../todoSummary';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- itemRow: css`
- width: 100%;
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- processingRow: css`
- display: flex;
- gap: 7px;
- align-items: center;
- `,
- textCompleted: css`
- color: ${cssVar.colorTextQuaternary};
- text-decoration: line-through;
- `,
- textPending: css`
- color: ${cssVar.colorTextSecondary};
- `,
- textProcessing: css`
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ itemRow: {
+ width: '100%',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ processingRow: { display: 'flex', gap: '7px', alignItems: 'center' },
+ textCompleted: { color: cssVar.colorTextQuaternary, textDecoration: 'line-through' },
+ textPending: { color: cssVar.colorTextSecondary },
+ textProcessing: { color: cssVar.colorText },
+});
interface TodoRowProps {
item: ClaudeCodeTodoItem;
@@ -49,9 +36,9 @@ const TodoRow = memo<TodoRowProps>(({ item }) => {
if (status === 'in_progress') {
return (
- <div className={cx(styles.itemRow, styles.processingRow)}>
+ <div {...stylex.props(styles.itemRow, styles.processingRow)}>
<Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorInfo }} />
- <span className={styles.textProcessing}>{activeForm || content}</span>
+ <span {...stylex.props(styles.textProcessing)}>{activeForm || content}</span>
</div>
);
}
@@ -65,8 +52,8 @@ const TodoRow = memo<TodoRowProps>(({ item }) => {
shape={'circle'}
style={{ borderWidth: 1.5, cursor: 'default' }}
classNames={{
- text: cx(styles.textPending, isCompleted && styles.textCompleted),
- wrapper: styles.itemRow,
+ text: cx(stylex.props(styles.textPending, isCompleted && styles.textCompleted).className),
+ wrapper: stylex.props(styles.itemRow).className,
}}
textProps={{
type: isCompleted ? 'secondary' : undefined,
diff --git a/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx
index 1cfd774b38d..027b045faef 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx
@@ -1,76 +1,56 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Highlighter } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { WebSearchArgs, WebSearchPluginState, WebSearchResult } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- hostname: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- metadata: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- queryRow: css`
- align-items: center;
- justify-content: space-between;
-
- min-width: 0;
- padding-block: 2px;
- padding-inline: 4px;
- `,
- resultItem: css`
- min-width: 0;
- padding-block: 5px;
- padding-inline: 4px;
- border-block-end: 1px solid ${cssVar.colorSplit};
-
- &:last-child {
- border-block-end: 0;
- }
- `,
- root: css`
- overflow: auto;
- min-width: 0;
- max-height: 280px;
- padding-block: 2px;
- `,
- snippet: css`
- font-size: 12px;
- line-height: 1.45;
- color: ${cssVar.colorTextSecondary};
- `,
- title: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- line-height: 1.45;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- &:hover {
- color: ${cssVar.colorLink};
- }
- `,
-}));
+const styles = stylex.create({
+ hostname: {
+ overflow: 'hidden',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ metadata: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ queryRow: {
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ minWidth: '0',
+ paddingBlock: '2px',
+ paddingInline: '4px',
+ },
+ resultItem: {
+ minWidth: '0',
+ paddingBlock: '5px',
+ paddingInline: '4px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'solid', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorSplit,
+ },
+ root: { overflow: 'auto', minWidth: '0', maxHeight: '280px', paddingBlock: '2px' },
+ snippet: { fontSize: '12px', lineHeight: 1.45, color: cssVar.colorTextSecondary },
+ title: {
+ overflow: 'hidden',
+ fontSize: '13px',
+ fontWeight: 500,
+ lineHeight: 1.45,
+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorLink },
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
const getWebSearchHostname = (link: string): string | undefined => {
try {
@@ -119,11 +99,11 @@ const WebSearch = memo<BuiltinRenderProps<WebSearchArgs, WebSearchPluginState>>(
: undefined;
return (
- <Flexbox className={styles.root} gap={0}>
+ <Flexbox className={stylex.props(styles.root).className} gap={0}>
{(query || duration) && (
- <Flexbox horizontal className={styles.queryRow} gap={8}>
- <span className={styles.metadata}>{query}</span>
- {duration && <span className={styles.metadata}>{duration}</span>}
+ <Flexbox horizontal className={stylex.props(styles.queryRow).className} gap={8}>
+ <span {...stylex.props(styles.metadata)}>{query}</span>
+ {duration && <span {...stylex.props(styles.metadata)}>{duration}</span>}
</Flexbox>
)}
{results.map((result, index) => {
@@ -131,12 +111,20 @@ const WebSearch = memo<BuiltinRenderProps<WebSearchArgs, WebSearchPluginState>>(
const title = result.title || hostname || result.link;
return (
- <Flexbox className={styles.resultItem} gap={3} key={`${result.link}-${index}`}>
+ <Flexbox
+ className={stylex.props(styles.resultItem).className}
+ gap={3}
+ key={`${result.link}-${index}`}
+ >
<a href={result.link} rel={'noreferrer'} target={'_blank'}>
- <span className={styles.title}>{title}</span>
+ <span {...stylex.props(styles.title)}>{title}</span>
</a>
- <Text className={styles.hostname}>{hostname || result.link}</Text>
- {result.snippet && <Text className={styles.snippet}>{result.snippet}</Text>}
+ <Text className={stylex.props(styles.hostname).className}>
+ {hostname || result.link}
+ </Text>
+ {result.snippet && (
+ <Text className={stylex.props(styles.snippet).className}>{result.snippet}</Text>
+ )}
</Flexbox>
);
})}
diff --git a/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx b/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx
index 6e90c77416d..0fb1dadce3f 100644
--- a/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Flexbox, Markdown } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Button, Flexbox, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ListTree } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,30 +13,19 @@ import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
import type { AgentArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- label: css`
- padding-inline-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- labelRow: css`
- margin-block-end: 4px;
- `,
- openThread: css`
- height: 22px;
- padding-inline: 6px;
- font-size: 12px;
- `,
- promptBox: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ label: { paddingInlineStart: '4px', fontSize: '12px', color: cssVar.colorTextTertiary },
+ labelRow: { marginBlockEnd: '4px' },
+ openThread: { height: '22px', paddingInline: '6px', fontSize: '12px' },
+ promptBox: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
/**
* Streaming view for CC's `Agent` tool — shown while the subagent is still
@@ -74,19 +63,21 @@ const AgentStreaming = memo<BuiltinStreamingProps<AgentArgs>>(({ args, toolCallI
if (!prompt && !subagentThread) return null;
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
{prompt && (
<Flexbox>
<Flexbox
horizontal
align={'center'}
- className={styles.labelRow}
+ className={stylex.props(styles.labelRow).className}
justify={'space-between'}
>
- <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.instruction')}</Text>
+ <Text className={stylex.props(styles.label).className}>
+ {t('builtins.lobe-claude-code.agent.instruction')}
+ </Text>
{subagentThread && (
<Button
- className={styles.openThread}
+ className={stylex.props(styles.openThread).className}
icon={ListTree}
size={'small'}
type={'text'}
@@ -98,7 +89,7 @@ const AgentStreaming = memo<BuiltinStreamingProps<AgentArgs>>(({ args, toolCallI
</Button>
)}
</Flexbox>
- <Flexbox className={styles.promptBox}>
+ <Flexbox className={stylex.props(styles.promptBox).className}>
<Markdown variant={'chat'}>{prompt}</Markdown>
</Flexbox>
</Flexbox>
diff --git a/packages/builtin-tool-claude-code/vitest.config.mts b/packages/builtin-tool-claude-code/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-claude-code/vitest.config.mts
+++ b/packages/builtin-tool-claude-code/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
index 90ba7283cee..88ae4cfd481 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { ExecuteCodeState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
interface ExecuteCodeParams {
code: string;
@@ -58,9 +55,17 @@ export const ExecuteCodeInspector = memo<
</span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
{isLoading ? null : pluginState?.success ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
)}
</span>
</div>
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx
index afd9348d27d..c20e996c1fa 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx
@@ -2,17 +2,14 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Block, Flexbox, Highlighter } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { ExecuteCodeState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
+});
interface ExecuteCodeParams {
code: string;
@@ -24,7 +21,7 @@ const ExecuteCode = memo<BuiltinRenderProps<ExecuteCodeParams, ExecuteCodeState>
const language = args.language || 'python';
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Block gap={8} padding={8} variant={'outlined'}>
<Highlighter
wrap
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx
index 94abadf40a0..b59b9df73e0 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx
@@ -1,20 +1,17 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleCheckIcon, CircleXIcon, DownloadIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import type { ExportFileState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
+});
interface ExportFileParams {
path: string;
@@ -50,7 +47,7 @@ const ExportFile = memo<BuiltinRenderProps<ExportFileParams, ExportFileState>>(
}, [pluginState?.downloadUrl, pluginState?.filename]);
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
{pluginState === undefined ? null : isSuccess ? (
<Icon color={cssVar.colorSuccess} icon={CircleCheckIcon} size={12} />
diff --git a/packages/builtin-tool-cloud-sandbox/vitest.config.mts b/packages/builtin-tool-cloud-sandbox/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-cloud-sandbox/vitest.config.mts
+++ b/packages/builtin-tool-cloud-sandbox/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
index c15f836f525..26f7a85c6f3 100644
--- a/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
+++ b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspector, BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,33 +22,33 @@ import type {
} from '../../types';
import { DashboardApiName, DashboardIdentifier } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- flex-shrink: 1;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- failed: css`
- color: ${cssVar.colorError};
- background: ${cssVar.colorErrorBg};
- `,
- succeeded: css`
- color: ${cssVar.colorSuccess};
- background: ${cssVar.colorSuccessBg};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ flexShrink: 1,
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ failed: {
+ color: cssVar.colorError,
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+ succeeded: {
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+});
type Props = BuiltinInspectorProps<Record<string, any>, any>;
@@ -80,7 +82,7 @@ const useChip = (apiName: DashboardApiNameType, props: Props): ReactNode => {
if (!state) return undefined;
return (
<span
- className={cx(
+ {...stylex.props(
styles.chip,
state.status === 'succeeded' || state.status === 'partial'
? styles.succeeded
@@ -126,7 +128,8 @@ const createInspector = (apiName: DashboardApiNameType) => {
>
{t(`builtins.${DashboardIdentifier}.apiName.${apiName}`)}
</span>
- {chip && (typeof chip === 'string' ? <span className={styles.chip}>{chip}</span> : chip)}
+ {chip &&
+ (typeof chip === 'string' ? <span {...stylex.props(styles.chip)}>{chip}</span> : chip)}
</div>
);
});
diff --git a/packages/builtin-tool-dashboard/vitest.config.mts b/packages/builtin-tool-dashboard/vitest.config.mts
index 04bfa099ade..3533670e5be 100644
--- a/packages/builtin-tool-dashboard/vitest.config.mts
+++ b/packages/builtin-tool-dashboard/vitest.config.mts
@@ -3,11 +3,14 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(packageDir, '../..');
export default defineConfig({
plugins: [
+ stylexPluginForVitest(),
{
enforce: 'pre',
name: 'stub-lobehub-ui-motion-provider',
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx
index 48e13342eb7..2d05664fc71 100644
--- a/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { UpdateGroupParams, UpdateGroupState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const UpdateGroupInspector = memo<
BuiltinInspectorProps<UpdateGroupParams, UpdateGroupState>
@@ -75,7 +72,11 @@ export const UpdateGroupInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx b/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx
index 7731793c9cb..9b5479f73d8 100644
--- a/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx
+++ b/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Avatar } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Users } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,44 +12,39 @@ import ToolTag from '@/features/ToolTag';
import type { BatchCreateAgentsParams, BatchCreateAgentsState } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- padding-inline: 16px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- description: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextDescription};
- text-overflow: ellipsis;
- `,
- empty: css`
- padding: 16px;
- color: ${cssVar.colorTextTertiary};
- `,
- item: css`
- padding-block: 12px;
-
- &:not(:last-child) {
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- }
- `,
- title: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ paddingBlock: '4px',
+ paddingInline: '16px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ description: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextDescription,
+ textOverflow: 'ellipsis',
+ },
+ empty: { padding: '16px', color: cssVar.colorTextTertiary },
+ item: {
+ paddingBlock: '12px',
+ borderBlockEndWidth: { 'default': null, ':not(:last-child)': '1px' },
+ borderBlockEndStyle: { 'default': null, ':not(:last-child)': 'solid' },
+ borderBlockEndColor: { 'default': null, ':not(:last-child)': cssVar.colorBorderSecondary },
+ },
+ title: {
+ overflow: 'hidden',
+ fontSize: '13px',
+ fontWeight: 500,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface AgentItemProps {
agent: {
@@ -71,7 +66,7 @@ const AgentItem = memo<AgentItemProps>(({ agent, definition }) => {
const tools = definition?.tools;
return (
- <Flexbox horizontal align="flex-start" className={styles.item} gap={12}>
+ <Flexbox horizontal align="flex-start" className={stylex.props(styles.item).className} gap={12}>
<Avatar
avatar={avatar}
size={24}
@@ -79,8 +74,8 @@ const AgentItem = memo<AgentItemProps>(({ agent, definition }) => {
title={agent.title}
/>
<Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>
- <span className={styles.title}>{agent.title}</span>
- {description && <span className={styles.description}>{description}</span>}
+ <span {...stylex.props(styles.title)}>{agent.title}</span>
+ {description && <span {...stylex.props(styles.description)}>{description}</span>}
{tools && tools.length > 0 && (
<Flexbox horizontal gap={4} style={{ marginTop: 8 }} wrap={'wrap'}>
{tools.map((tool) => (
@@ -102,7 +97,7 @@ const BatchCreateAgentsRender = memo<
if (!resultAgents || resultAgents.length === 0) {
return (
- <Flexbox align="center" className={styles.empty} gap={8}>
+ <Flexbox align="center" className={stylex.props(styles.empty).className} gap={8}>
<Users size={24} />
<span>{t('builtins.lobe-group-agent-builder.inspector.noResults')}</span>
</Flexbox>
@@ -110,7 +105,7 @@ const BatchCreateAgentsRender = memo<
}
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
{resultAgents.map((agent, index) => (
<AgentItem agent={agent} definition={definitions[index]} key={agent.agentId || index} />
))}
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx
index c9b5ba013d1..d2ab86dc0f6 100644
--- a/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx
+++ b/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx
@@ -1,59 +1,51 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Block, Flexbox, Markdown } from '@lobehub/ui';
-import { Avatar, Divider } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Avatar, Block, Divider, Flexbox, Markdown } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import ToolTag from '@/features/ToolTag';
import type { BatchCreateAgentsParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- description: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- line-height: 1.5;
- color: ${cssVar.colorTextDescription};
- text-overflow: ellipsis;
- `,
- index: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- `,
- item: css`
- padding-block: 10px;
- padding-inline: 12px;
-
- &:not(:last-child) {
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
- }
- `,
- systemRole: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 3;
-
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- `,
- title: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ description: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ lineHeight: 1.5,
+ color: cssVar.colorTextDescription,
+ textOverflow: 'ellipsis',
+ },
+ index: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextQuaternary },
+ item: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: { 'default': null, ':not(:last-child)': '1px' },
+ borderBlockEndStyle: { 'default': null, ':not(:last-child)': 'dashed' },
+ borderBlockEndColor: { 'default': null, ':not(:last-child)': cssVar.colorBorderSecondary },
+ },
+ systemRole: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '3',
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ },
+ title: {
+ overflow: 'hidden',
+ fontSize: '13px',
+ fontWeight: 500,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const BatchCreateAgentsStreaming = memo<BuiltinStreamingProps<BatchCreateAgentsParams>>(
({ args }) => {
@@ -64,8 +56,14 @@ export const BatchCreateAgentsStreaming = memo<BuiltinStreamingProps<BatchCreate
return (
<Block variant={'outlined'} width="100%">
{agents.map((agent, index) => (
- <Flexbox horizontal align={'flex-start'} className={styles.item} gap={8} key={index}>
- <div className={styles.index}>{index + 1}.</div>
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={stylex.props(styles.item).className}
+ gap={8}
+ key={index}
+ >
+ <div {...stylex.props(styles.index)}>{index + 1}.</div>
<Avatar
avatar={agent.avatar}
size={24}
@@ -73,8 +71,10 @@ export const BatchCreateAgentsStreaming = memo<BuiltinStreamingProps<BatchCreate
title={agent.title}
/>
<Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>
- <span className={styles.title}>{agent.title}</span>
- {agent.description && <span className={styles.description}>{agent.description}</span>}
+ <span {...stylex.props(styles.title)}>{agent.title}</span>
+ {agent.description && (
+ <span {...stylex.props(styles.description)}>{agent.description}</span>
+ )}
{agent.tools && agent.tools.length > 0 && (
<Flexbox horizontal gap={4} style={{ marginTop: 8 }} wrap={'wrap'}>
{agent.tools.map((tool) => (
@@ -84,7 +84,7 @@ export const BatchCreateAgentsStreaming = memo<BuiltinStreamingProps<BatchCreate
)}
<Divider style={{ marginBlock: 24 }} />
{agent.systemRole && (
- <div className={styles.systemRole}>
+ <div {...stylex.props(styles.systemRole)}>
<Markdown animated variant={'chat'}>
{agent.systemRole}
</Markdown>
diff --git a/packages/builtin-tool-group-agent-builder/vitest.config.mts b/packages/builtin-tool-group-agent-builder/vitest.config.mts
index 1d6d3125033..d586038d5a2 100644
--- a/packages/builtin-tool-group-agent-builder/vitest.config.mts
+++ b/packages/builtin-tool-group-agent-builder/vitest.config.mts
@@ -2,7 +2,10 @@ import path from 'node:path';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
alias: {
'@': path.resolve(__dirname, '../../src'),
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx
index 7dd7fd37e5f..607ebcf0144 100644
--- a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx
+++ b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { Flexbox, Tooltip } from '@lobehub/ui';
-import { Avatar, InputNumber, TextArea } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Avatar, Flexbox, InputNumber, TextArea, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { Clock } from 'lucide-react';
import type { ChangeEvent } from 'react';
@@ -15,52 +15,11 @@ import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import type { ExecuteTaskParams } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentCard: css`
- padding: 4px;
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorFillTertiary};
- `,
- agentDescription: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- font-size: 12px;
- line-height: 1.4;
- color: ${cssVar.colorTextSecondary};
- `,
- agentTitle: css`
- font-size: 14px;
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
- container: css`
- padding-block: 12px;
- border-radius: ${cssVar.borderRadius};
- `,
- header: css`
- font-size: 14px;
- font-weight: 600;
- `,
- icon: css`
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: 32px;
- height: 32px;
- border-radius: ${cssVar.borderRadius};
-
- color: ${cssVar.colorPrimary};
-
- background: ${cssVar.colorPrimaryBg};
- `,
- timeoutInput: css`
- width: 100px;
- `,
-}));
+const styles = stylex.create({
+ agentTitle: { fontSize: '14px', fontWeight: 600, color: cssVar.colorText },
+ container: { paddingBlock: '12px', borderRadius: cssVar.borderRadius },
+ timeoutInput: { width: '100px' },
+});
const DEFAULT_TIMEOUT = 1_800_000; // 30 minutes
@@ -122,7 +81,7 @@ const ExecuteTaskIntervention = memo<BuiltinInterventionProps<ExecuteTaskParams>
}, [registerBeforeApprove, hasChanges, instruction, timeout, args, onArgsChange]);
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
{/* Header: Agent info + Timeout */}
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
<Flexbox horizontal align={'center'} flex={1} gap={12} style={{ minWidth: 0 }}>
@@ -133,7 +92,7 @@ const ExecuteTaskIntervention = memo<BuiltinInterventionProps<ExecuteTaskParams>
style={{ borderRadius: 8, flexShrink: 0 }}
/>
<Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
- <span className={styles.agentTitle}>
+ <span {...stylex.props(styles.agentTitle)}>
{agent?.title || t('agentGroupManagement.executeTask.intervention.unknownAgent')}
</span>
</Flexbox>
@@ -143,7 +102,7 @@ const ExecuteTaskIntervention = memo<BuiltinInterventionProps<ExecuteTaskParams>
<Clock size={14} />
</Tooltip>
<InputNumber
- className={styles.timeoutInput}
+ className={stylex.props(styles.timeoutInput).className}
max={120}
min={1}
size={'small'}
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx
index 783d0b84548..6011152961e 100644
--- a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx
+++ b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx
@@ -7,7 +7,6 @@ import {
AccordionPanel,
AccordionRoot,
AccordionTrigger,
- createStaticStyles,
Flexbox,
Icon,
Input,
@@ -17,6 +16,8 @@ import {
Tooltip,
useTheme,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { Clock, Trash2 } from 'lucide-react';
import type { ChangeEvent } from 'react';
@@ -29,46 +30,23 @@ import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import type { ExecuteTasksParams, TaskItem } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- assignee: css`
- display: flex;
- flex-shrink: 0;
- gap: 6px;
- align-items: center;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- container: css`
- padding-block: 12px;
- border-radius: ${cssVar.borderRadius};
- `,
- deleteButton: css`
- cursor: pointer;
- color: ${cssVar.colorTextTertiary};
- transition: color 0.2s;
-
- &:hover {
- color: ${cssVar.colorError};
- }
- `,
- index: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- `,
- taskTitle: css`
- overflow: hidden;
-
- font-size: 14px;
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- timeoutInput: css`
- width: 100px;
- `,
-}));
+const styles = stylex.create({
+ assignee: {
+ display: 'flex',
+ flexShrink: 0,
+ gap: '6px',
+ alignItems: 'center',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ },
+ container: { paddingBlock: '12px', borderRadius: cssVar.borderRadius },
+ deleteButton: {
+ cursor: 'pointer',
+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorError },
+ transition: 'color 0.2s',
+ },
+ timeoutInput: { width: '100px' },
+});
const DEFAULT_TIMEOUT = 1_800_000; // 30 minutes
@@ -124,7 +102,7 @@ const TaskEditor = memo<TaskEditorProps>(({ task, index, onChange, onDelete }) =
<AccordionHeader style={{ paddingBlock: 4, paddingInline: 2 }}>
<AccordionTrigger>
<Flexbox horizontal align={'center'} gap={8}>
- <div className={styles.assignee}>
+ <div {...stylex.props(styles.assignee)}>
<AgentAvatar
agentId={task.agentId}
avatar={agent?.avatar}
@@ -153,7 +131,7 @@ const TaskEditor = memo<TaskEditorProps>(({ task, index, onChange, onDelete }) =
<Clock size={14} />
</Tooltip>
<InputNumber
- className={styles.timeoutInput}
+ className={stylex.props(styles.timeoutInput).className}
max={120}
min={1}
size={'small'}
@@ -163,7 +141,7 @@ const TaskEditor = memo<TaskEditorProps>(({ task, index, onChange, onDelete }) =
onChange={handleTimeoutChange}
/>
<Icon
- className={styles.deleteButton}
+ className={stylex.props(styles.deleteButton).className}
icon={Trash2}
size={{ size: 16 }}
onClick={handleDelete}
@@ -234,7 +212,7 @@ const ExecuteTasksIntervention = memo<BuiltinInterventionProps<ExecuteTasksParam
}, [registerBeforeApprove, hasChanges, tasks, args, onArgsChange]);
return (
- <Flexbox className={styles.container} gap={0}>
+ <Flexbox className={stylex.props(styles.container).className} gap={0}>
{tasks.map((task, index) => (
<TaskEditor
index={index}
diff --git a/packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx b/packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx
index e8fe38f49a8..a5885ca7a4e 100644
--- a/packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx
@@ -2,22 +2,21 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { BroadcastParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const BroadcastRender = memo<BuiltinRenderProps<BroadcastParams>>(({ args }) => {
const { instruction } = args || {};
@@ -25,8 +24,8 @@ export const BroadcastRender = memo<BuiltinRenderProps<BroadcastParams>>(({ args
if (!instruction) return null;
return (
- <div className={styles.container}>
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown variant={'chat'}>{instruction}</Markdown>
</div>
</div>
diff --git a/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx b/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx
index ca5e4506a18..459bb5e9958 100644
--- a/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx
@@ -1,34 +1,27 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Clock } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { ExecuteTaskParams, ExecuteTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentTitle: css`
- color: ${cssVar.colorTextSecondary};
- `,
- container: css`
- padding-block: 12px;
- border-radius: ${cssVar.borderRadius};
- `,
- taskContent: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorFillTertiary};
- `,
- timeout: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+const styles = stylex.create({
+ agentTitle: { color: cssVar.colorTextSecondary },
+ container: { paddingBlock: '12px', borderRadius: cssVar.borderRadius },
+ taskContent: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ timeout: { fontSize: '12px', color: cssVar.colorTextTertiary },
+});
/**
* ExecuteTask Render component for Group Management tool
@@ -41,13 +34,18 @@ const ExecuteTaskRender = memo<BuiltinRenderProps<ExecuteTaskParams, ExecuteTask
const timeoutMinutes = args?.timeout ? Math.round(args.timeout / 60_000) : 30;
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
{/* Header: Agent info + Timeout */}
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
<Flexbox horizontal align={'center'} flex={1} gap={12} style={{ minWidth: 0 }}>
- <span className={styles.agentTitle}>{args?.title}</span>
+ <span {...stylex.props(styles.agentTitle)}>{args?.title}</span>
</Flexbox>
- <Flexbox horizontal align="center" className={styles.timeout} gap={4}>
+ <Flexbox
+ horizontal
+ align="center"
+ className={stylex.props(styles.timeout).className}
+ gap={4}
+ >
<Clock size={14} />
<span>
{timeoutMinutes} {t('agentGroupManagement.executeTask.intervention.timeoutUnit')}
@@ -57,7 +55,7 @@ const ExecuteTaskRender = memo<BuiltinRenderProps<ExecuteTaskParams, ExecuteTask
{/* Instruction content (read-only) */}
{args?.instruction && (
- <Text className={styles.taskContent} style={{ margin: 0 }}>
+ <Text className={stylex.props(styles.taskContent).className} style={{ margin: 0 }}>
{args.instruction}
</Text>
)}
diff --git a/packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx b/packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx
index ce0573404a5..4c904e1b4ca 100644
--- a/packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx
@@ -2,22 +2,21 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { SpeakParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const SpeakRender = memo<BuiltinRenderProps<SpeakParams>>(({ args }) => {
const { instruction } = args || {};
@@ -25,8 +24,8 @@ export const SpeakRender = memo<BuiltinRenderProps<SpeakParams>>(({ args }) => {
if (!instruction) return null;
return (
- <div className={styles.container}>
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown variant={'chat'}>{instruction}</Markdown>
</div>
</div>
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx
index 5597cbb635e..6ba2f3f377e 100644
--- a/packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx
@@ -2,22 +2,21 @@
import type { BuiltinStreamingProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { BroadcastParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const BroadcastStreaming = memo<BuiltinStreamingProps<BroadcastParams>>(({ args }) => {
const { instruction } = args || {};
@@ -25,8 +24,8 @@ export const BroadcastStreaming = memo<BuiltinStreamingProps<BroadcastParams>>((
if (!instruction) return null;
return (
- <div className={styles.container}>
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown animated variant={'chat'}>
{instruction}
</Markdown>
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx
index 1ab883051d9..4e79f0f3728 100644
--- a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { createStaticStyles, Flexbox, Markdown, useTheme } from '@lobehub/ui';
+import { Flexbox, Markdown, useTheme } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
@@ -10,22 +12,16 @@ import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import type { ExecuteTaskParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentTitle: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- task: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ agentTitle: { fontSize: '14px', fontWeight: 500, color: cssVar.colorText },
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ task: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const ExecuteTaskStreaming = memo<BuiltinStreamingProps<ExecuteTaskParams>>(({ args }) => {
const { agentId, instruction } = args || {};
@@ -42,7 +38,7 @@ export const ExecuteTaskStreaming = memo<BuiltinStreamingProps<ExecuteTaskParams
if (!instruction) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
<Flexbox gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
<AgentAvatar
@@ -53,9 +49,9 @@ export const ExecuteTaskStreaming = memo<BuiltinStreamingProps<ExecuteTaskParams
shape={'square'}
size={24}
/>
- <span className={styles.agentTitle}>{agent?.title || 'Agent'}</span>
+ <span {...stylex.props(styles.agentTitle)}>{agent?.title || 'Agent'}</span>
</Flexbox>
- <div className={styles.task}>
+ <div {...stylex.props(styles.task)}>
<Markdown animated variant={'chat'}>
{instruction}
</Markdown>
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx
index ca8eaa57b98..4bf9d4780d8 100644
--- a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { AgentGroupMember, BuiltinStreamingProps } from '@lobechat/types';
-import { createStaticStyles, Flexbox, Markdown, useTheme } from '@lobehub/ui';
+import { Flexbox, Markdown, useTheme } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useMemo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
@@ -11,27 +13,17 @@ import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import type { ExecuteTasksParams } from '../../../types';
import { MemberTaskTitle, useMemberAnchors } from '../../MemberProgress';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- display: flex;
- flex-direction: column;
- gap: 12px;
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
- taskCard: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- taskTitle: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: { display: 'flex', flexDirection: 'column', gap: '12px' },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+ taskCard: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ taskTitle: { fontSize: '13px', fontWeight: 500, color: cssVar.colorText },
+});
export const ExecuteTasksStreaming = memo<BuiltinStreamingProps<ExecuteTasksParams>>(
({ args, toolCallId }) => {
@@ -59,9 +51,9 @@ export const ExecuteTasksStreaming = memo<BuiltinStreamingProps<ExecuteTasksPara
if (!tasksWithAgents.length) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{tasksWithAgents.map((task, index) => (
- <div className={styles.taskCard} key={task.agentId || index}>
+ <div {...stylex.props(styles.taskCard)} key={task.agentId || index}>
<Flexbox gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
<AgentAvatar
@@ -73,13 +65,13 @@ export const ExecuteTasksStreaming = memo<BuiltinStreamingProps<ExecuteTasksPara
size={20}
/>
<MemberTaskTitle anchor={anchors[index]}>
- <span className={styles.taskTitle}>
+ <span {...stylex.props(styles.taskTitle)}>
{task.title || task.agent?.title || 'Task'}
</span>
</MemberTaskTitle>
</Flexbox>
{task.instruction && (
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown animated variant={'chat'}>
{task.instruction}
</Markdown>
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx
index 7e362af2b58..c8dd2b3f67b 100644
--- a/packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx
@@ -2,22 +2,21 @@
import type { BuiltinStreamingProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { SpeakParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const SpeakStreaming = memo<BuiltinStreamingProps<SpeakParams>>(({ args }) => {
const { instruction } = args || {};
@@ -25,8 +24,8 @@ export const SpeakStreaming = memo<BuiltinStreamingProps<SpeakParams>>(({ args }
if (!instruction) return null;
return (
- <div className={styles.container}>
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown animated variant={'chat'}>
{instruction}
</Markdown>
diff --git a/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx b/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
index 10c01461f14..d28ffba101a 100644
--- a/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
+++ b/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { PreviewGroup } from '@lobehub/ui';
-import { Alert, Button, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Alert, Button, PreviewGroup, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,22 +24,17 @@ import {
useGenerationStatus,
} from '../components/useGenerationStatus';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- caption: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- root: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
- `,
-}));
+const styles = stylex.create({
+ caption: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextQuaternary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ root: { display: 'flex', flexDirection: 'column', gap: '8px' },
+});
const GenerationTile = memo<{
index: number;
@@ -130,7 +125,7 @@ export const GenerateImageRender = memo<
const isGrid = generations.length > 1;
return (
- <div className={styles.root}>
+ <div {...stylex.props(styles.root)}>
<PreviewGroup preview={{ onDownload: downloadPreviewImage }}>
<ImageCanvasGrid count={generations.length} ratio={gridRatio}>
{generations.map((task, index) => (
@@ -145,7 +140,9 @@ export const GenerateImageRender = memo<
))}
</ImageCanvasGrid>
</PreviewGroup>
- {model && <div className={styles.caption}>{[provider, model].filter(Boolean).join('/')}</div>}
+ {model && (
+ <div {...stylex.props(styles.caption)}>{[provider, model].filter(Boolean).join('/')}</div>
+ )}
</div>
);
});
diff --git a/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx b/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
index 73a9310fd54..8afc74c0579 100644
--- a/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
+++ b/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
@@ -2,7 +2,8 @@
import type { BuiltinRenderProps } from '@lobechat/types';
import { Alert, Button, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,13 +21,7 @@ import {
useGenerationStatus,
} from '../components/useGenerationStatus';
-const styles = createStaticStyles(({ css }) => ({
- root: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
- `,
-}));
+const styles = stylex.create({ root: { display: 'flex', flexDirection: 'column', gap: '8px' } });
const getAsset = (state?: GetImageGenerationStatusState) => state?.generation?.asset;
@@ -66,7 +61,7 @@ export const GetImageGenerationStatusRender = memo<
const canRetry = Boolean(error) && normalizeAsyncError(error).retryable;
return (
- <div className={styles.root}>
+ <div {...stylex.props(styles.root)}>
{/* Same canvas the generateImage card uses, so a follow-up status check
reads as the same image continuing rather than a second card. */}
<ImageCanvasGrid count={1} ratio={ratio}>
diff --git a/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx b/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx
index 138cb01d266..ba7bb269942 100644
--- a/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx
+++ b/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx
@@ -1,16 +1,10 @@
'use client';
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import type { ReactNode } from 'react';
import { memo } from 'react';
-const styles = createStaticStyles(({ css }) => ({
- grid: css`
- display: grid;
- gap: 8px;
- width: 100%;
- `,
-}));
+const styles = stylex.create({ grid: { display: 'grid', gap: '8px', width: '100%' } });
// A lone image is the hero of the message; several share the same footprint.
const SINGLE_MAX_HEIGHT = 420;
@@ -36,7 +30,7 @@ export const ImageCanvasGrid = memo<ImageCanvasGridProps>(({ children, count, ra
return (
<div
- className={styles.grid}
+ className={stylex.props(styles.grid).className}
style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`, maxWidth }}
>
{children}
diff --git a/packages/builtin-tool-image-generation/vitest.config.mts b/packages/builtin-tool-image-generation/vitest.config.mts
index cb722729b0a..11cebea84ab 100644
--- a/packages/builtin-tool-image-generation/vitest.config.mts
+++ b/packages/builtin-tool-image-generation/vitest.config.mts
@@ -3,10 +3,13 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(packageDir, '../..');
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
resolve: {
alias: {
'@': resolve(repoRoot, 'src'),
diff --git a/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
index bb733495bee..c8b15c52a2a 100644
--- a/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
+++ b/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,12 +11,9 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { ReadKnowledgeArgs, ReadKnowledgeState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- moreFiles: css`
- margin-inline-start: 4px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+const styles = stylex.create({
+ moreFiles: { marginInlineStart: '4px', color: cssVar.colorTextTertiary },
+});
export const ReadKnowledgeInspector = memo<
BuiltinInspectorProps<ReadKnowledgeArgs, ReadKnowledgeState>
@@ -58,7 +57,7 @@ export const ReadKnowledgeInspector = memo<
<>
<span className={highlightTextStyles.gold}>{firstFilename}</span>
{remainingCount > 0 && (
- <span className={styles.moreFiles}>
+ <span {...stylex.props(styles.moreFiles)}>
{t('builtins.lobe-knowledge-base.inspector.andMoreFiles', { count: remainingCount })}
</span>
)}
diff --git a/packages/builtin-tool-knowledge-base/vitest.config.mts b/packages/builtin-tool-knowledge-base/vitest.config.mts
index 52f86e133c7..f32927c6b6b 100644
--- a/packages/builtin-tool-knowledge-base/vitest.config.mts
+++ b/packages/builtin-tool-knowledge-base/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
coverage: {
provider: 'v8',
diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx
index 021db7844ba..88d403a9dab 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -9,13 +11,14 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ClearTodosParams, ClearTodosState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- mode: css`
- padding-block-end: 1px;
- color: ${cssVar.colorText};
- background: linear-gradient(to top, ${cssVar.colorWarningBg} 40%, transparent 40%);
- `,
-}));
+const styles = stylex.create({
+ mode: {
+ paddingBlockEnd: '1px',
+ color: cssVar.colorText,
+ backgroundImage: `linear-gradient(to top, ${cssVar.colorWarningBg} 40%, transparent 40%)`,
+ backgroundColor: 'transparent',
+ },
+});
export const ClearTodosInspector = memo<BuiltinInspectorProps<ClearTodosParams, ClearTodosState>>(
({ args, partialArgs, isArgumentsStreaming }) => {
@@ -43,7 +46,7 @@ export const ClearTodosInspector = memo<BuiltinInspectorProps<ClearTodosParams,
className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
>
<Trans
- components={{ mode: <span className={styles.mode} /> }}
+ components={{ mode: <span {...stylex.props(styles.mode)} /> }}
i18nKey="builtins.lobe-agent.apiName.clearTodos.result"
ns="plugin"
values={{ mode: modeLabel }}
diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx
index f01c3061232..941a79b79a0 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckCircle2, CircleAlert } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -23,30 +24,18 @@ const CATEGORY_LABEL_KEYS = {
const getTitleKey = (category?: VentCategory) =>
category ? CATEGORY_LABEL_KEYS[category] : ('builtins.lobe-agent.apiName.vent' as const);
-const styles = createStaticStyles(({ css, cssVar }) => ({
- iconRecorded: css`
- flex-shrink: 0;
- color: ${cssVar.colorSuccess};
- `,
- iconRejected: css`
- flex-shrink: 0;
- color: ${cssVar.colorWarning};
- `,
- meta: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- summary: css`
- overflow: hidden;
-
- min-width: 0;
- max-width: 320px;
-
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ iconRecorded: { flexShrink: 0, color: cssVar.colorSuccess },
+ iconRejected: { flexShrink: 0, color: cssVar.colorWarning },
+ meta: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextTertiary },
+ summary: {
+ overflow: 'hidden',
+ minWidth: '0',
+ maxWidth: '320px',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const VentInspector = memo<BuiltinInspectorProps<VentParams, VentState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -73,16 +62,28 @@ export const VentInspector = memo<BuiltinInspectorProps<VentParams, VentState>>(
{title}
</span>
{summary && (
- <span className={cx(highlightTextStyles.primary, styles.summary)}>{summary}</span>
+ <span className={cx(stylex.props(styles.summary).className, highlightTextStyles.primary)}>
+ {summary}
+ </span>
)}
{isSettled &&
pluginState &&
(pluginState.recorded ? (
- <Icon className={styles.iconRecorded} icon={CheckCircle2} size={14} />
+ <Icon
+ className={stylex.props(styles.iconRecorded).className}
+ icon={CheckCircle2}
+ size={14}
+ />
) : (
<>
- <Icon className={styles.iconRejected} icon={CircleAlert} size={14} />
- <span className={styles.meta}>{t('builtins.lobe-agent.apiName.vent.rejected')}</span>
+ <Icon
+ className={stylex.props(styles.iconRejected).className}
+ icon={CircleAlert}
+ size={14}
+ />
+ <span {...stylex.props(styles.meta)}>
+ {t('builtins.lobe-agent.apiName.vent.rejected')}
+ </span>
</>
))}
</div>
diff --git a/packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx b/packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx
index b2933d6b4ca..9a9bcf27421 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx
@@ -1,36 +1,27 @@
'use client';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { RadioGroup } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, RadioGroup } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Trash2 } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { ClearTodosParams } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorFillTertiary};
- `,
- dangerText: css`
- font-size: 13px;
- color: ${cssVar.colorError};
- `,
- header: css`
- color: ${cssVar.colorWarning};
- `,
- label: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
- normalText: css`
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ dangerText: { fontSize: '13px', color: cssVar.colorError },
+ header: { color: cssVar.colorWarning },
+ label: { fontSize: '13px', color: cssVar.colorTextSecondary },
+ normalText: { fontSize: '13px' },
+});
/**
* ClearTodos Intervention component
@@ -52,13 +43,18 @@ const ClearTodosIntervention = memo<BuiltinInterventionProps<ClearTodosParams>>(
return (
<Flexbox gap={12}>
- <Flexbox horizontal align="center" className={styles.header} gap={8}>
+ <Flexbox
+ horizontal
+ align="center"
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
<Trash2 size={16} />
<span style={{ fontSize: 14, fontWeight: 500 }}>{t('lobe-agent.clearTodos.header')}</span>
</Flexbox>
- <Flexbox className={styles.container} gap={8}>
- <span className={styles.label}>{t('lobe-agent.clearTodos.label')}</span>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
+ <span {...stylex.props(styles.label)}>{t('lobe-agent.clearTodos.label')}</span>
<RadioGroup
gap={8}
horizontal={false}
@@ -66,7 +62,7 @@ const ClearTodosIntervention = memo<BuiltinInterventionProps<ClearTodosParams>>(
options={[
{
label: (
- <span className={styles.normalText}>
+ <span {...stylex.props(styles.normalText)}>
{t('lobe-agent.clearTodos.option.completed')}
</span>
),
@@ -74,7 +70,9 @@ const ClearTodosIntervention = memo<BuiltinInterventionProps<ClearTodosParams>>(
},
{
label: (
- <span className={styles.dangerText}>{t('lobe-agent.clearTodos.option.all')}</span>
+ <span {...stylex.props(styles.dangerText)}>
+ {t('lobe-agent.clearTodos.option.all')}
+ </span>
),
value: 'all',
},
diff --git a/packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx b/packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx
index 5dd9ef66ab3..598bdcd4679 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx
@@ -11,25 +11,19 @@ import {
ReactTablePlugin,
} from '@lobehub/editor';
import { Editor, useEditor } from '@lobehub/editor/react';
-import { Flexbox } from '@lobehub/ui';
-import { TextArea } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, TextArea } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { CreatePlanParams } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- description: css`
- font-size: 14px;
- color: ${cssVar.colorTextSecondary};
- `,
- title: css`
- font-size: 28px;
- font-weight: 600;
- `,
-}));
+const styles = stylex.create({
+ description: { fontSize: '14px', color: cssVar.colorTextSecondary },
+ title: { fontSize: '28px', fontWeight: 600 },
+});
const CreatePlanIntervention = memo<BuiltinInterventionProps<CreatePlanParams>>(
({ args, onArgsChange, registerBeforeApprove }) => {
@@ -143,7 +137,7 @@ const CreatePlanIntervention = memo<BuiltinInterventionProps<CreatePlanParams>>(
{/* Goal - Main Title */}
<TextArea
autoSize={{ minRows: 1 }}
- className={styles.title}
+ className={stylex.props(styles.title).className}
placeholder={t('lobe-agent.createPlan.goal.placeholder')}
style={{ padding: 0, resize: 'none' }}
value={goal}
@@ -155,7 +149,7 @@ const CreatePlanIntervention = memo<BuiltinInterventionProps<CreatePlanParams>>(
{/* Description - Subtitle */}
<TextArea
autoSize={{ minRows: 1 }}
- className={styles.description}
+ className={stylex.props(styles.description).className}
data-testid="plan-description"
placeholder={t('lobe-agent.createPlan.description.placeholder')}
style={{ padding: 0, resize: 'none' }}
diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
index 3e0dfb87c5b..f74659f3b0e 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Button, createStaticStyles, cssVar, cx, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { Button, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AlertTriangle, ListTree } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,44 +14,34 @@ import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
import { stripSubAgentReference } from '../../../subAgentReference';
import type { CallSubAgentParams, CallSubAgentState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- label: css`
- padding-inline-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- labelRow: css`
- margin-block-end: 4px;
- `,
- openThread: css`
- height: 22px;
- padding-inline: 6px;
- font-size: 12px;
- `,
- promptBox: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorFillTertiary};
- `,
- resultBox: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
- stoppedLabel: css`
- font-size: 12px;
- color: ${cssVar.colorWarning};
- `,
- stoppedResultBox: css`
- border: 1px solid ${cssVar.colorWarningBorder};
- background: ${cssVar.colorWarningBg};
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ label: { paddingInlineStart: '4px', fontSize: '12px', color: cssVar.colorTextTertiary },
+ labelRow: { marginBlockEnd: '4px' },
+ openThread: { height: '22px', paddingInline: '6px', fontSize: '12px' },
+ promptBox: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ resultBox: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ stoppedLabel: { fontSize: '12px', color: cssVar.colorWarning },
+ stoppedResultBox: {
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorWarningBorder,
+ backgroundColor: cssVar.colorWarningBg,
+ backgroundImage: 'none',
+ },
+});
/**
* Render for lobe-agent's `callSubAgent` tool.
@@ -107,13 +99,13 @@ export const CallSubAgentRender = memo<
const showResultSection = !!result || !!subagentThread || runningInBackground;
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
{prompt && (
<Flexbox>
- <Text className={styles.label} style={{ marginBlockEnd: 4 }}>
+ <Text className={stylex.props(styles.label).className} style={{ marginBlockEnd: 4 }}>
{t('builtins.lobe-claude-code.agent.instruction')}
</Text>
- <Flexbox className={styles.promptBox}>
+ <Flexbox className={stylex.props(styles.promptBox).className}>
<Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>
{prompt}
</Markdown>
@@ -126,26 +118,28 @@ export const CallSubAgentRender = memo<
<Flexbox
horizontal
align={'center'}
- className={styles.labelRow}
+ className={stylex.props(styles.labelRow).className}
justify={'space-between'}
>
{stopped ? (
<Flexbox horizontal align={'center'} gap={4}>
<Icon color={cssVar.colorWarning} icon={AlertTriangle} size={14} />
- <Text className={styles.stoppedLabel}>
+ <Text className={stylex.props(styles.stoppedLabel).className}>
{t('builtins.lobe-agent.subAgent.stopped')}
</Text>
</Flexbox>
) : runningInBackground ? (
- <Text className={styles.label}>
+ <Text className={stylex.props(styles.label).className}>
{t('builtins.lobe-agent.subAgent.backgroundRunning')}
</Text>
) : (
- <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>
+ <Text className={stylex.props(styles.label).className}>
+ {t('builtins.lobe-claude-code.agent.result')}
+ </Text>
)}
{subagentThread && (
<Button
- className={styles.openThread}
+ className={stylex.props(styles.openThread).className}
icon={ListTree}
size={'small'}
type={'text'}
@@ -158,10 +152,16 @@ export const CallSubAgentRender = memo<
)}
</Flexbox>
{runningInBackground && (
- <Text className={styles.label}>{t('builtins.lobe-agent.subAgent.backgroundHint')}</Text>
+ <Text className={stylex.props(styles.label).className}>
+ {t('builtins.lobe-agent.subAgent.backgroundHint')}
+ </Text>
)}
{result && (
- <Flexbox className={cx(styles.resultBox, stopped && styles.stoppedResultBox)}>
+ <Flexbox
+ className={
+ stylex.props(styles.resultBox, stopped && styles.stoppedResultBox).className
+ }
+ >
<Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>
{result}
</Markdown>
diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx
index 75dd40dbc9b..4895a490938 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Block, Flexbox, Icon, Markdown } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ListChecksIcon } from 'lucide-react';
import { memo } from 'react';
@@ -12,27 +12,24 @@ import type { Plan } from '../../../types';
const MAX_CONTENT_HEIGHT = 100;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- content: css`
- overflow: hidden auto;
-
- max-height: ${MAX_CONTENT_HEIGHT}px;
- padding: 12px;
- border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- header: css`
- cursor: pointer;
- padding-block: 4px;
- padding-inline: 0;
- transition: opacity 0.2s;
-
- &:hover {
- opacity: 0.8;
- }
- `,
-}));
+const styles = stylex.create({
+ content: {
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ maxHeight: `${MAX_CONTENT_HEIGHT}px`,
+ padding: '12px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ header: {
+ cursor: 'pointer',
+ paddingBlock: '4px',
+ paddingInline: '0',
+ transition: 'opacity 0.2s',
+ opacity: { 'default': null, ':hover': 0.8 },
+ },
+});
interface PlanCardProps {
plan: Plan;
@@ -53,7 +50,7 @@ const PlanCard = memo<PlanCardProps>(({ plan }) => {
<Flexbox
horizontal
align={'center'}
- className={styles.header}
+ className={stylex.props(styles.header).className}
gap={8}
style={{ overflow: 'hidden' }}
onClick={handleHeaderClick}
@@ -73,7 +70,7 @@ const PlanCard = memo<PlanCardProps>(({ plan }) => {
{/* Context content */}
{hasContext && (
- <div className={styles.content}>
+ <div {...stylex.props(styles.content)}>
<Markdown fontSize={13} variant={'chat'}>
{plan.context!}
</Markdown>
diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx
index 29f9ed47f99..f377e2bd303 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx
@@ -2,9 +2,9 @@
import { TodoPanelHeader } from '@lobechat/shared-tool-ui/components';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Icon } from '@lobehub/ui';
-import { Checkbox } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { Block, Checkbox, cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleArrowRight } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,33 +21,20 @@ export interface TodoListRenderState {
}
// Styles matching TodoItemRow in SortableTodoList
-const styles = createStaticStyles(({ css, cssVar }) => ({
- itemRow: css`
- width: 100%;
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- processingRow: css`
- display: flex;
- gap: 7px;
- align-items: center;
- `,
- textCompleted: css`
- color: ${cssVar.colorTextQuaternary};
- text-decoration: line-through;
- `,
- textProcessing: css`
- color: ${cssVar.colorText};
- `,
- textTodo: css`
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ itemRow: {
+ width: '100%',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ processingRow: { display: 'flex', gap: '7px', alignItems: 'center' },
+ textCompleted: { color: cssVar.colorTextQuaternary, textDecoration: 'line-through' },
+ textProcessing: { color: cssVar.colorText },
+ textTodo: { color: cssVar.colorTextSecondary },
+});
interface ReadOnlyTodoItemProps {
status: TodoStatus;
@@ -64,9 +51,9 @@ const ReadOnlyTodoItem = memo<ReadOnlyTodoItemProps>(({ text, status }) => {
// Processing state uses CircleArrowRight icon
if (isProcessing) {
return (
- <div className={cx(styles.itemRow, styles.processingRow)}>
+ <div {...stylex.props(styles.itemRow, styles.processingRow)}>
<Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorInfo }} />
- <span className={styles.textProcessing}>{text}</span>
+ <span {...stylex.props(styles.textProcessing)}>{text}</span>
</div>
);
}
@@ -79,8 +66,8 @@ const ReadOnlyTodoItem = memo<ReadOnlyTodoItemProps>(({ text, status }) => {
shape={'circle'}
style={{ borderWidth: 1.5, cursor: 'default' }}
classNames={{
- text: cx(styles.textTodo, isCompleted && styles.textCompleted),
- wrapper: styles.itemRow,
+ text: cx(stylex.props(styles.textTodo, isCompleted && styles.textCompleted).className),
+ wrapper: stylex.props(styles.itemRow).className,
}}
textProps={{
type: isCompleted ? 'secondary' : undefined,
diff --git a/packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx
index 09eb6620373..cc89a9e6424 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx
@@ -2,27 +2,21 @@
import type { BuiltinStreamingProps } from '@lobechat/types';
import { Markdown } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { CallSubAgentParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 12px;
- border-radius: 8px;
- background: ${cssVar.colorFillQuaternary};
- `,
- description: css`
- margin-block-end: 8px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
- instruction: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ instruction: { fontSize: '13px', color: cssVar.colorTextSecondary },
+});
export const CallSubAgentStreaming = memo<BuiltinStreamingProps<CallSubAgentParams>>(({ args }) => {
const { instruction } = args || {};
@@ -30,9 +24,9 @@ export const CallSubAgentStreaming = memo<BuiltinStreamingProps<CallSubAgentPara
if (!instruction) return null;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{instruction && (
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown animated variant={'chat'}>
{instruction}
</Markdown>
diff --git a/packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx
index 1a3d2d1869a..0dbde771919 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ListChecksIcon } from 'lucide-react';
import { memo } from 'react';
@@ -11,33 +11,26 @@ import StreamingMarkdown from '@/components/StreamingMarkdown';
import type { CreatePlanParams } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
- padding: 12px;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: 8px;
- `,
- description: css`
- font-size: 14px;
- color: ${cssVar.colorTextSecondary};
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
- padding-block: 4px;
- `,
- title: css`
- overflow: hidden;
-
- font-size: 16px;
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: '8px',
+ },
+ description: { fontSize: '14px', color: cssVar.colorTextSecondary },
+ header: { display: 'flex', gap: '8px', alignItems: 'center', paddingBlock: '4px' },
+ title: {
+ overflow: 'hidden',
+ fontSize: '16px',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const CreatePlanStreaming = memo<BuiltinStreamingProps<CreatePlanParams>>(({ args }) => {
const { goal, description, context } = args || {};
@@ -45,18 +38,18 @@ export const CreatePlanStreaming = memo<BuiltinStreamingProps<CreatePlanParams>>
if (!goal) return null;
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
{/* Header */}
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<Icon icon={ListChecksIcon} size={18} />
- <Text ellipsis className={styles.title}>
+ <Text ellipsis className={stylex.props(styles.title).className}>
{goal}
</Text>
</div>
{/* Description */}
{description && (
- <Text className={styles.description} ellipsis={{ rows: 2 }}>
+ <Text className={stylex.props(styles.description).className} ellipsis={{ rows: 2 }}>
{description}
</Text>
)}
diff --git a/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx
index 2d0d5b365de..1b9407de361 100644
--- a/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx
@@ -1,22 +1,22 @@
'use client';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { SubAgentRunStats } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- flex-shrink: 0;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ root: {
+ overflow: 'hidden',
+ flexShrink: 0,
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
const formatTokens = (n: number): string => {
if (n < 1000) return String(n);
@@ -44,7 +44,7 @@ export const SubAgentStats = memo<SubAgentRunStats>(({ model, totalToolCalls, to
if (items.length === 0) return null;
- return <span className={styles.root}>{items.join(' · ')}</span>;
+ return <span {...stylex.props(styles.root)}>{items.join(' · ')}</span>;
});
SubAgentStats.displayName = 'SubAgentStats';
diff --git a/packages/builtin-tool-lobe-agent/vitest.config.mts b/packages/builtin-tool-lobe-agent/vitest.config.mts
index 52f86e133c7..f32927c6b6b 100644
--- a/packages/builtin-tool-lobe-agent/vitest.config.mts
+++ b/packages/builtin-tool-lobe-agent/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
coverage: {
provider: 'v8',
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
index 5279afedc9e..9240b4536de 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
@@ -2,8 +2,8 @@
import type { RenameLocalFileParams } from '@lobechat/electron-client-ipc';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { MaterialFileTypeIcon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, MaterialFileTypeIcon } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import path from 'path-browserify-esm';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { LocalRenameFileState } from '../../..';
-const styles = createStaticStyles(({ css }) => ({
- icon: css`
- flex-shrink: 0;
- margin-inline-end: 4px;
- `,
-}));
+const styles = stylex.create({ icon: { flexShrink: 0, marginInlineEnd: '4px' } });
export const RenameLocalFileInspector = memo<
BuiltinInspectorProps<RenameLocalFileParams, LocalRenameFileState>
@@ -38,7 +33,7 @@ export const RenameLocalFileInspector = memo<
<>
{t('builtins.lobe-local-system.apiName.renameLocalFile')} {oldName} →{' '}
<MaterialFileTypeIcon
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
filename={newName}
size={16}
type={'file'}
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx b/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx
index da82ce3bdfc..a9a3bea8c5b 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx
@@ -1,32 +1,24 @@
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ArrowRight } from 'lucide-react';
import { memo } from 'react';
import { useElectronStore } from '@/store/electron';
import { desktopStateSelectors } from '@/store/electron/selectors';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- icon: css`
- color: ${cssVar.colorTextQuaternary};
- `,
- item: css`
- padding-block: 4px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
- transition: all 0.2s ease;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
- `,
- path: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- word-break: break-all;
- `,
-}));
+const styles = stylex.create({
+ icon: { color: cssVar.colorTextQuaternary },
+ item: {
+ paddingBlock: '4px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'all 0.2s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ path: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px', wordBreak: 'break-all' },
+});
interface MoveFileItemProps {
newPath: string;
@@ -38,15 +30,21 @@ const MoveFileItem = memo<MoveFileItemProps>(({ oldPath, newPath }) => {
const displayNewPath = useElectronStore(desktopStateSelectors.displayRelativePath(newPath));
return (
- <Flexbox horizontal align="center" className={styles.item} gap={8} width="100%">
+ <Flexbox
+ horizontal
+ align="center"
+ className={stylex.props(styles.item).className}
+ gap={8}
+ width="100%"
+ >
<Flexbox flex={1}>
- <Text className={styles.path} type="secondary">
+ <Text className={stylex.props(styles.path).className} type="secondary">
{displayOldPath}
</Text>
</Flexbox>
- <Icon className={styles.icon} icon={ArrowRight} />
+ <Icon className={stylex.props(styles.icon).className} icon={ArrowRight} />
<Flexbox flex={2}>
- <Text className={styles.path}>{displayNewPath}</Text>
+ <Text className={stylex.props(styles.path).className}>{displayNewPath}</Text>
</Flexbox>
</Flexbox>
);
diff --git a/packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx b/packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx
index 5b26e30b8dc..b3a0dae0457 100644
--- a/packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx
+++ b/packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx
@@ -1,31 +1,33 @@
import type { LocalSearchFilesParams } from '@lobechat/electron-client-ipc';
import type { BuiltinPlaceholderProps } from '@lobechat/types';
-import { Center, Flexbox, Icon } from '@lobehub/ui';
-import { Skeleton } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Center, Flexbox, Icon, Skeleton } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { SearchIcon } from 'lucide-react';
import React, { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- query: css`
- padding-block: 4px;
- padding-inline: 8px;
- border-radius: 8px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = stylex.create({
+ query: {
+ paddingBlock: '4px',
+ paddingInline: '8px',
+ borderRadius: '8px',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
const SearchFiles = memo<BuiltinPlaceholderProps<LocalSearchFilesParams>>(({ args = {} }) => {
return (
<Flexbox gap={4}>
<Flexbox horizontal align={'center'} distribution={'space-between'} gap={40} height={26}>
- <Flexbox horizontal align={'center'} className={styles.query} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.query).className}
+ gap={8}
+ >
<Icon icon={SearchIcon} />
{args.keywords ? args.keywords : <Skeleton height={20} width={40} />}
</Flexbox>
diff --git a/packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx b/packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx
index eb089c5e52d..d89911499d8 100644
--- a/packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx
@@ -1,30 +1,22 @@
import { useToolRenderCapabilities } from '@lobechat/shared-tool-ui';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ArrowRight } from 'lucide-react';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- icon: css`
- color: ${cssVar.colorTextQuaternary};
- `,
- item: css`
- padding-block: 4px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
- transition: all 0.2s ease;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
- `,
- path: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- word-break: break-all;
- `,
-}));
+const styles = stylex.create({
+ icon: { color: cssVar.colorTextQuaternary },
+ item: {
+ paddingBlock: '4px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'all 0.2s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ path: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px', wordBreak: 'break-all' },
+});
interface MoveFileItemProps {
newPath: string;
@@ -37,15 +29,21 @@ const MoveFileItem = memo<MoveFileItemProps>(({ oldPath, newPath }) => {
const displayNewPath = displayRelativePath ? displayRelativePath(newPath) : newPath;
return (
- <Flexbox horizontal align="center" className={styles.item} gap={8} width="100%">
+ <Flexbox
+ horizontal
+ align="center"
+ className={stylex.props(styles.item).className}
+ gap={8}
+ width="100%"
+ >
<Flexbox flex={1}>
- <Text className={styles.path} type="secondary">
+ <Text className={stylex.props(styles.path).className} type="secondary">
{displayOldPath}
</Text>
</Flexbox>
- <Icon className={styles.icon} icon={ArrowRight} />
+ <Icon className={stylex.props(styles.icon).className} icon={ArrowRight} />
<Flexbox flex={2}>
- <Text className={styles.path}>{displayNewPath}</Text>
+ <Text className={stylex.props(styles.path).className}>{displayNewPath}</Text>
</Flexbox>
</Flexbox>
);
diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx
index 1364a678745..e361b06a272 100644
--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx
@@ -1,30 +1,29 @@
-import { Flexbox } from '@lobehub/ui';
-import { Skeleton } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import React, { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding: 8px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- `,
-
- meta: css`
- font-size: 12px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ padding: '8px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ },
+ meta: { fontSize: '12px' },
+});
const ReadFileSkeleton = memo(() => {
return (
- <Flexbox className={styles.container} gap={2}>
+ <Flexbox className={stylex.props(styles.container).className} gap={2}>
<Flexbox horizontal align={'center'} gap={24} justify={'space-between'}>
<Flexbox horizontal align={'center'} flex={1} gap={8} style={{ overflow: 'hidden' }}>
<Skeleton height={16} style={{ flex: 1 }} width={20} />
<Skeleton height={16} style={{ flex: 1, minWidth: 100 }} />
</Flexbox>
- <Flexbox align={'center'} className={styles.meta} gap={16}>
+ <Flexbox align={'center'} className={stylex.props(styles.meta).className} gap={16}>
<Skeleton height={16} style={{ maxWidth: 40 }} />
</Flexbox>
</Flexbox>
diff --git a/packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx b/packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx
index 83fce878ff8..47c4a213a90 100644
--- a/packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx
@@ -1,25 +1,22 @@
-import { Flexbox, Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Flexbox, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { SearchIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { shinyTextStyles } from '@/styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- font: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- query: css`
- padding-block: 4px;
- padding-inline: 8px;
- border-radius: 8px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ font: { fontSize: '12px', color: cssVar.colorTextTertiary },
+ query: {
+ paddingBlock: '4px',
+ paddingInline: '8px',
+ borderRadius: '8px',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ },
+});
interface SearchBarProps {
defaultQuery: string;
@@ -31,12 +28,12 @@ const SearchBar = memo<SearchBarProps>(({ defaultQuery, resultsNumber, searching
const { t } = useTranslation('tool');
return (
<Flexbox horizontal align={'center'} distribution={'space-between'} gap={40} height={26}>
- <Flexbox horizontal align={'center'} className={styles.query} gap={8}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.query).className} gap={8}>
<Icon icon={SearchIcon} />
<span className={cx(searching && shinyTextStyles.shinyText)}>{defaultQuery}</span>
</Flexbox>
- <Flexbox horizontal align={'center'} className={styles.font}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.font).className}>
<div>{t('search.searchResult')}</div>
{resultsNumber}
</Flexbox>
diff --git a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
index 9fede958801..9e2b9b8ae41 100644
--- a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
@@ -1,8 +1,8 @@
import type { WriteLocalFileParams } from '@lobechat/electron-client-ipc';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Icon, Markdown, PatchDiff } from '@lobehub/ui';
-import { Skeleton } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Icon, Markdown, PatchDiff, Skeleton } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ChevronRight } from 'lucide-react';
import path from 'path-browserify-esm';
import { memo } from 'react';
@@ -10,16 +10,15 @@ import { memo } from 'react';
import { InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';
import { LocalFile, LocalFolder } from '@/features/LocalFile';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 4px;
- `,
- previewBox: css`
- overflow: hidden;
- border-radius: 8px;
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ container: { paddingBlock: '4px' },
+ previewBox: {
+ overflow: 'hidden',
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
const buildNewFilePatch = (filePath: string, content: string) => {
const hasTrailingNewline = content.endsWith('\n');
@@ -64,7 +63,7 @@ const WriteFile = memo<BuiltinRenderProps<WriteFileArgs>>(({ args }) => {
}
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
<Flexbox horizontal align={'center'}>
<LocalFolder path={dir} />
<Icon icon={ChevronRight} />
@@ -72,7 +71,10 @@ const WriteFile = memo<BuiltinRenderProps<WriteFileArgs>>(({ args }) => {
</Flexbox>
{args.content && (
- <Flexbox className={styles.previewBox} style={{ height: isHtml ? 260 : undefined }}>
+ <Flexbox
+ className={stylex.props(styles.previewBox).className}
+ style={{ height: isHtml ? 260 : undefined }}
+ >
{isHtml ? (
<InlineHtmlPreview content={args.content} />
) : (
diff --git a/packages/builtin-tool-local-system/vitest.config.mts b/packages/builtin-tool-local-system/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-local-system/vitest.config.mts
+++ b/packages/builtin-tool-local-system/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx
index 48b7de0c415..b62a2533a5b 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { AddActivityMemoryParams, AddActivityMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const AddActivityMemoryInspector = memo<
BuiltinInspectorProps<AddActivityMemoryParams, AddActivityMemoryState>
@@ -48,7 +45,11 @@ export const AddActivityMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx
index a5b396ca325..f0b6d6d1a42 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { AddContextMemoryParams, AddContextMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const AddContextMemoryInspector = memo<
BuiltinInspectorProps<AddContextMemoryParams, AddContextMemoryState>
@@ -48,7 +45,11 @@ export const AddContextMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx
index efa3cd863bc..002fbbf0f54 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { AddExperienceMemoryParams, AddExperienceMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const AddExperienceMemoryInspector = memo<
BuiltinInspectorProps<AddExperienceMemoryParams, AddExperienceMemoryState>
@@ -48,7 +45,11 @@ export const AddExperienceMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx
index 38a0789ebff..519fdbd4c95 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { AddIdentityMemoryParams, AddIdentityMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const AddIdentityMemoryInspector = memo<
BuiltinInspectorProps<AddIdentityMemoryParams, AddIdentityMemoryState>
@@ -48,7 +45,11 @@ export const AddIdentityMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx
index e2b5c8cbc4a..1397a3d68e6 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { AddPreferenceMemoryParams, AddPreferenceMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const AddPreferenceMemoryInspector = memo<
BuiltinInspectorProps<AddPreferenceMemoryParams, AddPreferenceMemoryState>
@@ -48,7 +45,11 @@ export const AddPreferenceMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx
index 53825dc00b1..1cf1dacecef 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { RemoveIdentityMemoryParams, RemoveIdentityMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const RemoveIdentityMemoryInspector = memo<
BuiltinInspectorProps<RemoveIdentityMemoryParams, RemoveIdentityMemoryState>
@@ -48,7 +45,11 @@ export const RemoveIdentityMemoryInspector = memo<
</>
)}
{!isLoading && isSuccess && (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
)}
</div>
);
diff --git a/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx
index 1d6f6a67c69..1b0ff7fb3ff 100644
--- a/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx
@@ -1,56 +1,38 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Accordion, Tag, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Accordion, Flexbox, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { SearchMemoryParams, SearchUserMemoryState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- `,
- empty: css`
- padding: 24px;
- color: ${cssVar.colorTextTertiary};
- text-align: center;
- `,
- item: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- itemContent: css`
- font-size: 13px;
- line-height: 1.5;
- color: ${cssVar.colorTextSecondary};
- `,
- itemTitle: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
- sectionHeader: css`
- font-size: 12px;
- font-weight: 500;
- `,
- tags: css`
- padding-block-start: 6px;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ empty: { padding: '24px', color: cssVar.colorTextTertiary, textAlign: 'center' },
+ item: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ itemContent: { fontSize: '13px', lineHeight: 1.5, color: cssVar.colorTextSecondary },
+ itemTitle: { fontSize: '14px', fontWeight: 500, color: cssVar.colorText },
+ sectionHeader: { fontSize: '12px', fontWeight: 500 },
+ tags: { paddingBlockStart: '6px' },
+});
interface MemoryItemProps {
content?: string | null;
@@ -63,16 +45,20 @@ const MemoryItem = memo<MemoryItemProps>(({ title, content, subContent, tags })
// Guard against non-array `tags` (dirty data) so a bad row can't crash the list.
const safeTags = Array.isArray(tags) ? tags : [];
return (
- <Flexbox className={styles.item} gap={4}>
- {title && <div className={styles.itemTitle}>{title}</div>}
- {content && <div className={styles.itemContent}>{content}</div>}
+ <Flexbox className={stylex.props(styles.item).className} gap={4}>
+ {title && <div {...stylex.props(styles.itemTitle)}>{title}</div>}
+ {content && <div {...stylex.props(styles.itemContent)}>{content}</div>}
{subContent && (
- <Text className={styles.itemContent} style={{ fontStyle: 'italic' }} type={'secondary'}>
+ <Text
+ className={stylex.props(styles.itemContent).className}
+ style={{ fontStyle: 'italic' }}
+ type={'secondary'}
+ >
{subContent}
</Text>
)}
{safeTags.length > 0 && (
- <Flexbox horizontal className={styles.tags} gap={4} wrap={'wrap'}>
+ <Flexbox horizontal className={stylex.props(styles.tags).className} gap={4} wrap={'wrap'}>
{safeTags.map((tag, index) => (
<Tag key={index} size={'small'}>
{tag}
@@ -105,8 +91,10 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
if (totalCount === 0) {
return (
- <div className={styles.container}>
- <div className={styles.empty}>{t('builtins.lobe-user-memory.inspector.noResults')}</div>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.empty)}>
+ {t('builtins.lobe-user-memory.inspector.noResults')}
+ </div>
</div>
);
}
@@ -136,7 +124,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
),
key: 'activities',
title: (
- <Text className={styles.sectionHeader}>
+ <Text className={stylex.props(styles.sectionHeader).className}>
<span>Activities</span>
<Text as={'span'} type={'secondary'}>
{' '}
@@ -161,7 +149,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
),
key: 'contexts',
title: (
- <Text className={styles.sectionHeader}>
+ <Text className={stylex.props(styles.sectionHeader).className}>
<span>{t('builtins.lobe-user-memory.render.contexts')}</span>
<Text as={'span'} type={'secondary'}>
{' '}
@@ -186,7 +174,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
),
key: 'experiences',
title: (
- <Text className={styles.sectionHeader}>
+ <Text className={stylex.props(styles.sectionHeader).className}>
<span>{t('builtins.lobe-user-memory.render.experiences')}</span>
<Text as={'span'} type={'secondary'}>
{' '}
@@ -211,7 +199,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
),
key: 'identities',
title: (
- <Text className={styles.sectionHeader}>
+ <Text className={stylex.props(styles.sectionHeader).className}>
<span>Identities</span>
<Text as={'span'} type={'secondary'}>
{' '}
@@ -235,7 +223,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
),
key: 'preferences',
title: (
- <Text className={styles.sectionHeader}>
+ <Text className={stylex.props(styles.sectionHeader).className}>
<span>{t('builtins.lobe-user-memory.render.preferences')}</span>
<Text as={'span'} type={'secondary'}>
{' '}
@@ -247,7 +235,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, Searc
].filter(Boolean) as { children: ReactNode; key: string; title: ReactNode }[];
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
<Accordion
defaultValue={defaultActiveKeys}
gap={0}
diff --git a/packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx
index c0a2b98061f..148b0255745 100644
--- a/packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx
+++ b/packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Accordion, Avatar, Spin, Steps, Tag, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Accordion, Avatar, Flexbox, Spin, Steps, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
@@ -11,64 +11,55 @@ import { highlightTextStyles } from '@/styles';
import type { AddExperienceMemoryParams } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-block: 12px;
- padding-inline: 16px;
- `,
- detail: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- keyLearning: css`
- font-size: 14px;
- line-height: 1.6;
- color: ${cssVar.colorText};
- `,
- section: css`
- padding: 4px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- stepContent: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- white-space: pre-wrap;
- `,
- summary: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- tags: css`
- padding-block-start: 8px;
- border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingBlock: '12px', paddingInline: '16px' },
+ detail: { fontSize: '13px', lineHeight: 1.6, color: cssVar.colorTextSecondary },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ keyLearning: { fontSize: '14px', lineHeight: 1.6, color: cssVar.colorText },
+ section: {
+ padding: '4px',
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ stepContent: {
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorTextSecondary,
+ whiteSpace: 'pre-wrap',
+ },
+ summary: { fontSize: '14px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ tags: {
+ paddingBlockStart: '8px',
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'dashed',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
export interface ExperienceMemoryCardProps {
data?: AddExperienceMemoryParams;
@@ -97,11 +88,16 @@ export const ExperienceMemoryCard = memo<ExperienceMemoryCardProps>(({ data, loa
].filter((item) => item.content);
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
{/* Header */}
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
<Flexbox flex={1}>
- <div className={styles.title}>{title || 'Experience Memory'}</div>
+ <div {...stylex.props(styles.title)}>{title || 'Experience Memory'}</div>
</Flexbox>
{loading && <Spin size="middle" variant="network" />}
</Flexbox>
@@ -117,10 +113,15 @@ export const ExperienceMemoryCard = memo<ExperienceMemoryCardProps>(({ data, loa
{
children: (
<Flexbox gap={8} paddingBlock={'8px 12px'} paddingInline={8}>
- {summary && <div className={styles.summary}>{summary}</div>}
- {details && <div className={styles.detail}>{details}</div>}
+ {summary && <div {...stylex.props(styles.summary)}>{summary}</div>}
+ {details && <div {...stylex.props(styles.detail)}>{details}</div>}
{safeTags.length > 0 && (
- <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>
+ <Flexbox
+ horizontal
+ className={stylex.props(styles.tags).className}
+ gap={8}
+ wrap={'wrap'}
+ >
{safeTags.map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
@@ -144,7 +145,7 @@ export const ExperienceMemoryCard = memo<ExperienceMemoryCardProps>(({ data, loa
{/* STAR Steps */}
<Accordion
- className={styles.section}
+ className={stylex.props(styles.section).className}
defaultValue={['star']}
gap={0}
items={[
@@ -154,7 +155,9 @@ export const ExperienceMemoryCard = memo<ExperienceMemoryCardProps>(({ data, loa
<Steps
orientation="vertical"
items={starItems.map((item) => ({
- description: <div className={styles.stepContent}>{item.content}</div>,
+ description: (
+ <div {...stylex.props(styles.stepContent)}>{item.content}</div>
+ ),
icon: (
<Avatar
shadow
@@ -189,28 +192,33 @@ export const ExperienceMemoryCard = memo<ExperienceMemoryCardProps>(({ data, loa
{/* Key Learning */}
{keyLearning && (
<Flexbox
- className={styles.section}
+ className={stylex.props(styles.section).className}
gap={8}
style={{ paddingBlock: 16, paddingInline: 12 }}
>
<Text fontSize={12} weight={500}>
<span className={highlightTextStyles.gold}>Key Learning</span>
</Text>
- <div className={styles.keyLearning}>{keyLearning}</div>
+ <div {...stylex.props(styles.keyLearning)}>{keyLearning}</div>
</Flexbox>
)}
</>
) : (
/* When no STAR content: show summary and details */
- <Flexbox className={styles.content} gap={8}>
+ <Flexbox className={stylex.props(styles.content).className} gap={8}>
{!summary && loading ? (
<BubblesLoading />
) : (
<>
- {summary && <div className={styles.summary}>{summary}</div>}
+ {summary && <div {...stylex.props(styles.summary)}>{summary}</div>}
{details && <StreamingMarkdown>{details}</StreamingMarkdown>}
{safeTags.length > 0 && (
- <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>
+ <Flexbox
+ horizontal
+ className={stylex.props(styles.tags).className}
+ gap={8}
+ wrap={'wrap'}
+ >
{safeTags.map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
diff --git a/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx
index 72027eed9a5..1ff5be67e09 100644
--- a/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx
+++ b/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Progress, Spin, Tag, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Progress, Spin, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
@@ -11,18 +11,19 @@ import StreamingMarkdown from '@/components/StreamingMarkdown';
import type { IdentityMemoryViewModel } from './identityMemoryViewModel';
import { memoryCardStyles as styles, MemorySection, SummaryAccordion } from './MemoryCardParts';
-const localStyles = createStaticStyles(({ css, cssVar }) => ({
- evidence: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-inline-start: 2px solid ${cssVar.colorBorder};
-
- font-size: 13px;
- font-style: italic;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const localStyles = stylex.create({
+ evidence: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderInlineStartWidth: '2px',
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: cssVar.colorBorder,
+ fontSize: '13px',
+ fontStyle: 'italic',
+ lineHeight: 1.6,
+ color: cssVar.colorTextSecondary,
+ },
+});
export interface IdentityMemoryCardProps {
data: IdentityMemoryViewModel;
@@ -125,7 +126,7 @@ export const IdentityMemoryCard = memo<IdentityMemoryCardProps>(
{sourceEvidence && (
<MemorySection title={'Evidence'} tone={'gold'}>
- <div className={localStyles.evidence}>{sourceEvidence}</div>
+ <div {...stylex.props(localStyles.evidence)}>{sourceEvidence}</div>
</MemorySection>
)}
diff --git a/packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx
index 26b4e66e23e..6adae951386 100644
--- a/packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx
+++ b/packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Accordion, Avatar, Spin, Steps, Tag, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Accordion, Avatar, Flexbox, Spin, Steps, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
@@ -11,75 +11,65 @@ import { highlightTextStyles } from '@/styles';
import type { AddPreferenceMemoryParams } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-block: 12px;
- padding-inline: 16px;
- `,
- detail: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
- directive: css`
- font-size: 14px;
- line-height: 1.6;
- color: ${cssVar.colorText};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- section: css`
- padding: 4px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- stepContent: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- white-space: pre-wrap;
- `,
- suggestion: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: 8px;
-
- font-size: 13px;
- line-height: 1.5;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- summary: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- tags: css`
- padding-block-start: 8px;
- border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingBlock: '12px', paddingInline: '16px' },
+ detail: { fontSize: '13px', lineHeight: 1.6, color: cssVar.colorTextSecondary },
+ directive: { fontSize: '14px', lineHeight: 1.6, color: cssVar.colorText },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ section: {
+ padding: '4px',
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ stepContent: {
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorTextSecondary,
+ whiteSpace: 'pre-wrap',
+ },
+ suggestion: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: '8px',
+ fontSize: '13px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ summary: { fontSize: '14px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ tags: {
+ paddingBlockStart: '8px',
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'dashed',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
export interface PreferenceMemoryCardProps {
data?: AddPreferenceMemoryParams;
@@ -134,11 +124,16 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
].filter((item) => item.content);
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
{/* Header */}
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
<Flexbox flex={1}>
- <div className={styles.title}>{title || 'Preference Memory'}</div>
+ <div {...stylex.props(styles.title)}>{title || 'Preference Memory'}</div>
</Flexbox>
{type && <Tag>{type}</Tag>}
{loading && <Spin size="middle" variant="network" />}
@@ -155,10 +150,15 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
{
children: (
<Flexbox gap={8} paddingBlock={'8px 12px'} paddingInline={8}>
- {summary && <div className={styles.summary}>{summary}</div>}
- {details && <div className={styles.detail}>{details}</div>}
+ {summary && <div {...stylex.props(styles.summary)}>{summary}</div>}
+ {details && <div {...stylex.props(styles.detail)}>{details}</div>}
{safeTags.length > 0 && (
- <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>
+ <Flexbox
+ horizontal
+ className={stylex.props(styles.tags).className}
+ gap={8}
+ wrap={'wrap'}
+ >
{safeTags.map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
@@ -183,7 +183,7 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
{/* Origin Context Steps */}
{hasContextContent && (
<Accordion
- className={styles.section}
+ className={stylex.props(styles.section).className}
defaultValue={['context']}
gap={0}
items={[
@@ -193,7 +193,9 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
<Steps
orientation="vertical"
items={contextItems.map((item) => ({
- description: <div className={styles.stepContent}>{item.content}</div>,
+ description: (
+ <div {...stylex.props(styles.stepContent)}>{item.content}</div>
+ ),
icon: (
<Avatar
shadow
@@ -229,7 +231,7 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
{/* App Context */}
{hasAppContext && (
<Accordion
- className={styles.section}
+ className={stylex.props(styles.section).className}
gap={0}
items={[
{
@@ -238,7 +240,9 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
<Steps
orientation="vertical"
items={appContextItems.map((item) => ({
- description: <div className={styles.stepContent}>{item.content}</div>,
+ description: (
+ <div {...stylex.props(styles.stepContent)}>{item.content}</div>
+ ),
icon: (
<Avatar
shadow
@@ -274,21 +278,21 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
{/* Conclusion Directive */}
{conclusionDirectives && (
<Flexbox
- className={styles.section}
+ className={stylex.props(styles.section).className}
gap={8}
style={{ paddingBlock: 16, paddingInline: 12 }}
>
<Text fontSize={12} weight={500}>
<span className={highlightTextStyles.primary}>Directive</span>
</Text>
- <div className={styles.directive}>{conclusionDirectives}</div>
+ <div {...stylex.props(styles.directive)}>{conclusionDirectives}</div>
</Flexbox>
)}
{/* Suggestions */}
{hasSuggestions && (
<Flexbox
- className={styles.section}
+ className={stylex.props(styles.section).className}
gap={8}
style={{ paddingBlock: 16, paddingInline: 12 }}
>
@@ -297,7 +301,7 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
</Text>
<Flexbox gap={8}>
{safeSuggestions.map((suggestion, index) => (
- <div className={styles.suggestion} key={index}>
+ <div {...stylex.props(styles.suggestion)} key={index}>
{suggestion}
</div>
))}
@@ -307,19 +311,19 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
</>
) : (
/* When no context content: show summary and details */
- <Flexbox className={styles.content} gap={8}>
+ <Flexbox className={stylex.props(styles.content).className} gap={8}>
{!summary && loading ? (
<BubblesLoading />
) : (
<>
- {summary && <div className={styles.summary}>{summary}</div>}
+ {summary && <div {...stylex.props(styles.summary)}>{summary}</div>}
{details && <StreamingMarkdown>{details}</StreamingMarkdown>}
{conclusionDirectives && (
<Flexbox gap={4} paddingBlock={8}>
<Text fontSize={12} weight={500}>
<span className={highlightTextStyles.primary}>Directive</span>
</Text>
- <div className={styles.directive}>{conclusionDirectives}</div>
+ <div {...stylex.props(styles.directive)}>{conclusionDirectives}</div>
</Flexbox>
)}
{hasSuggestions && (
@@ -329,7 +333,7 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
</Text>
<Flexbox gap={8}>
{safeSuggestions.map((suggestion, index) => (
- <div className={styles.suggestion} key={index}>
+ <div {...stylex.props(styles.suggestion)} key={index}>
{suggestion}
</div>
))}
@@ -337,7 +341,12 @@ export const PreferenceMemoryCard = memo<PreferenceMemoryCardProps>(({ data, loa
</Flexbox>
)}
{safeTags.length > 0 && (
- <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>
+ <Flexbox
+ horizontal
+ className={stylex.props(styles.tags).className}
+ gap={8}
+ wrap={'wrap'}
+ >
{safeTags.map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
diff --git a/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx b/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx
index 06d38318966..0de6d1f5cff 100644
--- a/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx
+++ b/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Trash2 } from 'lucide-react';
import { memo } from 'react';
@@ -10,18 +10,10 @@ import type { RemoveIdentityMemoryParams } from '../../types';
import { getRemoveIdentityViewModel } from './identityMemoryViewModel';
import { memoryCardStyles as styles } from './MemoryCardParts';
-const localStyles = createStaticStyles(({ css, cssVar }) => ({
- id: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- `,
- reason: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const localStyles = stylex.create({
+ id: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px', color: cssVar.colorTextQuaternary },
+ reason: { fontSize: '13px', lineHeight: 1.6, color: cssVar.colorTextSecondary },
+});
export interface RemovedIdentityCardProps {
data?: RemoveIdentityMemoryParams;
@@ -45,12 +37,12 @@ export const RemovedIdentityCard = memo<RemovedIdentityCardProps>(({ data }) =>
Identity removed
</Text>
</Flexbox>
- {id && <span className={localStyles.id}>{id}</span>}
+ {id && <span {...stylex.props(localStyles.id)}>{id}</span>}
</Flexbox>
{reason && (
<Flexbox className={styles.content}>
- <div className={localStyles.reason}>{reason}</div>
+ <div {...stylex.props(localStyles.reason)}>{reason}</div>
</Flexbox>
)}
</Flexbox>
diff --git a/packages/builtin-tool-memory/vitest.config.mts b/packages/builtin-tool-memory/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-memory/vitest.config.mts
+++ b/packages/builtin-tool-memory/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
index fbcb6765371..21c2267fc27 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
@@ -2,9 +2,9 @@
import type { InitDocumentArgs } from '@lobechat/editor-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,12 +14,7 @@ import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { InitDocumentState } from '../../../types';
import { AnimatedNumber } from '../../components/AnimatedNumber';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- title: css`
- margin-inline-end: 8px;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({ title: { marginInlineEnd: '8px', color: cssVar.colorText } });
export const InitPageInspector = memo<BuiltinInspectorProps<InitDocumentArgs, InitDocumentState>>(
({ args, partialArgs, isArgumentsStreaming, pluginState }) => {
@@ -72,7 +67,7 @@ export const InitPageInspector = memo<BuiltinInspectorProps<InitDocumentArgs, In
return (
<div className={oneLineEllipsis}>
- <span className={styles.title}>
+ <span {...stylex.props(styles.title)}>
{t('builtins.lobe-page-agent.apiName.initPage.result')}
</span>
{displayLines > 0 && (
diff --git a/packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx b/packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx
index a07a1553b34..b42b690f953 100644
--- a/packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx
@@ -2,63 +2,54 @@
import type { ModifyNodesArgs, ModifyOperation } from '@lobechat/editor-runtime';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Block, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, DiffIcon, Minus, Plus, X } from 'lucide-react';
import { memo } from 'react';
import type { ModifyNodesState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- content: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- index: css`
- flex-shrink: 0;
-
- width: 18px;
-
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-align: end;
- `,
- position: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 11px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- row: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
-}));
+const styles = stylex.create({
+ content: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ index: {
+ flexShrink: 0,
+ width: '18px',
+ fontSize: '12px',
+ color: cssVar.colorTextQuaternary,
+ textAlign: 'end',
+ },
+ position: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '11px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ row: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+});
const actionMeta = {
insert: { color: cssVar.colorSuccess, icon: Plus },
@@ -99,11 +90,13 @@ export const ModifyNodesRender = memo<BuiltinRenderProps<ModifyNodesArgs, Modify
const failed = result?.success === false;
return (
- <div className={styles.row} key={index}>
- <span className={styles.index}>{index + 1}.</span>
+ <div {...stylex.props(styles.row)} key={index}>
+ <span {...stylex.props(styles.index)}>{index + 1}.</span>
<Icon icon={meta.icon} size={14} style={{ color: meta.color, flexShrink: 0 }} />
- {details.position && <span className={styles.position}>{details.position}</span>}
- {details.content && <span className={styles.content}>{details.content}</span>}
+ {details.position && (
+ <span {...stylex.props(styles.position)}>{details.position}</span>
+ )}
+ {details.content && <span {...stylex.props(styles.content)}>{details.content}</span>}
{success && (
<Icon
icon={Check}
diff --git a/packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx b/packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx
index 7f2cbf82eda..f27645d6cd7 100644
--- a/packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx
@@ -2,9 +2,9 @@
import type { InitDocumentArgs } from '@lobechat/editor-runtime';
import type { BuiltinStreamingProps } from '@lobechat/types';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileText, Hash, ListTree } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,43 +15,36 @@ import { AnimatedNumber } from '../../components/AnimatedNumber';
const MAX_PREVIEW_CHARS = 4000;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
-
- background: ${cssVar.colorBgContainer};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- color: ${cssVar.colorPrimary};
- `,
- meta: css`
- color: ${cssVar.colorTextDescription};
- `,
- preview: css`
- overflow: auto;
- max-height: 360px;
- padding-block: 8px;
- padding-inline: 12px;
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: { color: cssVar.colorPrimary },
+ meta: { color: cssVar.colorTextDescription },
+ preview: { overflow: 'auto', maxHeight: '360px', paddingBlock: '8px', paddingInline: '12px' },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
const extractTitle = (markdown: string) => {
const titleLine = markdown
@@ -82,14 +75,24 @@ export const InitPageStreaming = memo<BuiltinStreamingProps<InitDocumentArgs>>((
if (!markdown) return null;
return (
- <Flexbox className={styles.container}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
- <FileText className={styles.icon} size={16} />
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
+ <FileText className={stylex.props(styles.icon).className} size={16} />
<Flexbox flex={1} gap={2}>
- <div className={styles.title}>
+ <div {...stylex.props(styles.title)}>
{title || t('builtins.lobe-page-agent.apiName.initPage.creating')}
</div>
- <Flexbox horizontal align={'center'} className={styles.meta} gap={10}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.meta).className}
+ gap={10}
+ >
<Text as={'span'} color={cssVar.colorTextDescription} fontSize={12}>
<Icon icon={ListTree} size={12} /> <AnimatedNumber value={lines} />
{t('builtins.lobe-page-agent.apiName.initPage.lines')}
@@ -101,7 +104,7 @@ export const InitPageStreaming = memo<BuiltinStreamingProps<InitDocumentArgs>>((
</Flexbox>
</Flexbox>
</Flexbox>
- <div className={styles.preview}>
+ <div {...stylex.props(styles.preview)}>
<StreamingMarkdown>{preview}</StreamingMarkdown>
</div>
</Flexbox>
diff --git a/packages/builtin-tool-page-agent/vitest.config.mts b/packages/builtin-tool-page-agent/vitest.config.mts
index 6a7d8caedd0..c616aa6239e 100644
--- a/packages/builtin-tool-page-agent/vitest.config.mts
+++ b/packages/builtin-tool-page-agent/vitest.config.mts
@@ -3,10 +3,13 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(packageDir, '../..');
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
resolve: {
alias: {
'@': resolve(repoRoot, 'src'),
diff --git a/packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx b/packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx
index 35a39d12302..3a5120b4eb4 100644
--- a/packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx
+++ b/packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,23 +11,21 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ActivateDeviceParams, ActivateDeviceState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- device: css`
- overflow: hidden;
-
- max-width: 240px;
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadiusSM};
-
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ device: {
+ overflow: 'hidden',
+ maxWidth: '240px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadiusSM,
+ fontWeight: 500,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
export const ActivateDeviceInspector = memo<
BuiltinInspectorProps<ActivateDeviceParams, ActivateDeviceState>
@@ -43,7 +43,7 @@ export const ActivateDeviceInspector = memo<
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-remote-device.apiName.activateDevice')}
</span>
- {deviceLabel && <span className={styles.device}>{deviceLabel}</span>}
+ {deviceLabel && <span {...stylex.props(styles.device)}>{deviceLabel}</span>}
</div>
);
});
diff --git a/packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx b/packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx
index 9377cf70c0a..9afc9ba0d88 100644
--- a/packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx
+++ b/packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { MonitorIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,24 +12,18 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ListOnlineDevicesState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- count: css`
- display: inline-flex;
- align-items: center;
-
- height: 20px;
-
- font-size: ${cssVar.fontSizeSM};
- line-height: 20px;
- color: ${cssVar.colorTextDescription};
- `,
- icon: css`
- flex: none;
- `,
- root: css`
- gap: 8px;
- `,
-}));
+const styles = stylex.create({
+ count: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ height: '20px',
+ fontSize: cssVar.fontSizeSM,
+ lineHeight: '20px',
+ color: cssVar.colorTextDescription,
+ },
+ icon: { flex: 'none' },
+ root: { gap: '8px' },
+});
export const ListOnlineDevicesInspector = memo<
BuiltinInspectorProps<undefined, ListOnlineDevicesState>
@@ -38,13 +33,13 @@ export const ListOnlineDevicesInspector = memo<
const deviceCount = pluginState?.devices?.length;
return (
- <div className={cx(inspectorTextStyles.root, styles.root)}>
- <Icon className={styles.icon} icon={MonitorIcon} size={14} />
+ <div className={cx(stylex.props(styles.root).className, inspectorTextStyles.root)}>
+ <Icon className={stylex.props(styles.icon).className} icon={MonitorIcon} size={14} />
<span className={cx(isPending && shinyTextStyles.shinyText)}>
{t('builtins.lobe-remote-device.apiName.listOnlineDevices')}
</span>
{!isPending && deviceCount !== undefined && (
- <span className={styles.count}>
+ <span {...stylex.props(styles.count)}>
{t('builtins.lobe-remote-device.inspector.onlineCount', { count: deviceCount })}
</span>
)}
diff --git a/packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx b/packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx
index 7d067a5bea4..2d6121d05f1 100644
--- a/packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx
+++ b/packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx
@@ -2,7 +2,8 @@
import { type BuiltinRenderProps } from '@lobechat/types';
import { Icon } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AlertTriangleIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,23 +11,23 @@ import { useTranslation } from 'react-i18next';
import type { ActivateDeviceParams, ActivateDeviceState } from '../../../types';
import DeviceCard from '../DeviceCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- failure: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 12px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorWarningBorder};
- border-radius: ${cssVar.borderRadius};
-
- font-size: ${cssVar.fontSize};
- color: ${cssVar.colorWarningText};
-
- background: ${cssVar.colorWarningBg};
- `,
-}));
+const styles = stylex.create({
+ failure: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '12px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorWarningBorder,
+ borderRadius: cssVar.borderRadius,
+ fontSize: cssVar.fontSize,
+ color: cssVar.colorWarningText,
+ backgroundColor: cssVar.colorWarningBg,
+ backgroundImage: 'none',
+ },
+});
const ActivateDevice = memo<BuiltinRenderProps<ActivateDeviceParams, ActivateDeviceState, string>>(
({ pluginState, content }) => {
@@ -40,7 +41,7 @@ const ActivateDevice = memo<BuiltinRenderProps<ActivateDeviceParams, ActivateDev
// blank — the tool detail view only skips custom renders when `result.error` is set.
if (typeof content === 'string' && content.length > 0) {
return (
- <div className={styles.failure}>
+ <div {...stylex.props(styles.failure)}>
<Icon icon={AlertTriangleIcon} size={14} />
<span>
{t('builtins.lobe-remote-device.render.activationFailed')}: {content}
diff --git a/packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx b/packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx
index fe5706bbbab..5503d2713ad 100644
--- a/packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx
+++ b/packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx
@@ -1,102 +1,98 @@
'use client';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Flexbox, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckCircle2, MonitorIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { DeviceAttachment } from '../../../ExecutionRuntime/types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- activated: css`
- color: ${cssVar.colorSuccess};
- background: ${cssVar.colorSuccessBg};
- `,
- badge: css`
- display: inline-flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadiusSM};
-
- font-size: 12px;
- line-height: 16px;
- white-space: nowrap;
- `,
- card: css`
- padding-block: 12px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorBgContainer};
- `,
- details: css`
- overflow: hidden;
-
- max-width: 50%;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: ${cssVar.fontSizeSM};
- color: ${cssVar.colorTextDescription};
- text-align: end;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- hostname: css`
- overflow: hidden;
-
- font-size: ${cssVar.fontSize};
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- icon: css`
- flex: none;
-
- width: 32px;
- height: 32px;
- border-radius: 8px;
-
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- listItem: css`
- padding-block: 10px;
- padding-inline: 12px;
-
- &:not(:last-child) {
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- }
- `,
- root: css`
- width: 100%;
- `,
- status: css`
- display: inline-flex;
- flex: none;
- gap: 6px;
- align-items: center;
-
- font-size: ${cssVar.fontSizeSM};
- color: ${cssVar.colorTextSecondary};
- `,
- statusDot: css`
- width: 7px;
- height: 7px;
- border: 1px solid ${cssVar.colorTextQuaternary};
- border-radius: 50%;
- `,
- statusDotOnline: css`
- border: none;
- background: ${cssVar.colorSuccess};
- box-shadow: 0 0 0 3px ${cssVar.colorSuccessBg};
- `,
-}));
+const styles = stylex.create({
+ activated: {
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+ badge: {
+ display: 'inline-flex',
+ gap: '4px',
+ alignItems: 'center',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadiusSM,
+ fontSize: '12px',
+ lineHeight: '16px',
+ whiteSpace: 'nowrap',
+ },
+ card: {
+ paddingBlock: '12px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ details: {
+ overflow: 'hidden',
+ maxWidth: '50%',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ color: cssVar.colorTextDescription,
+ textAlign: 'end',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ hostname: {
+ overflow: 'hidden',
+ fontSize: cssVar.fontSize,
+ fontWeight: 500,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ icon: {
+ flex: 'none',
+ width: '32px',
+ height: '32px',
+ borderRadius: '8px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ listItem: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: { 'default': null, ':not(:last-child)': '1px' },
+ borderBlockEndStyle: { 'default': null, ':not(:last-child)': 'solid' },
+ borderBlockEndColor: { 'default': null, ':not(:last-child)': cssVar.colorBorderSecondary },
+ },
+ root: { width: '100%' },
+ status: {
+ display: 'inline-flex',
+ flex: 'none',
+ gap: '6px',
+ alignItems: 'center',
+ fontSize: cssVar.fontSizeSM,
+ color: cssVar.colorTextSecondary,
+ },
+ statusDot: {
+ width: '7px',
+ height: '7px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorTextQuaternary,
+ borderRadius: '50%',
+ },
+ statusDotOnline: {
+ borderStyle: 'none',
+ backgroundColor: cssVar.colorSuccess,
+ backgroundImage: 'none',
+ boxShadow: `0 0 0 3px ${cssVar.colorSuccessBg}`,
+ },
+});
interface DeviceCardProps {
/** Render the activated treatment (check badge) instead of the online badge. */
@@ -119,22 +115,20 @@ const DeviceCard = memo<DeviceCardProps>(({ device, activated, variant = 'card'
<Flexbox
horizontal
align={'center'}
- className={cx(styles.root, variant === 'card' ? styles.card : styles.listItem)}
gap={12}
role={variant === 'listItem' ? 'listitem' : undefined}
+ className={cx(
+ stylex.props(styles.root, variant === 'card' ? styles.card : styles.listItem).className,
+ )}
>
- <Flexbox align={'center'} className={styles.icon} justify={'center'}>
+ <Flexbox align={'center'} className={stylex.props(styles.icon).className} justify={'center'}>
<Icon icon={MonitorIcon} size={18} />
</Flexbox>
<Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
- <span className={styles.hostname}>{displayName}</span>
+ <span {...stylex.props(styles.hostname)}>{displayName}</span>
{!activated && (
- <span className={styles.status}>
- <span
- className={[styles.statusDot, device.online ? styles.statusDotOnline : undefined]
- .filter(Boolean)
- .join(' ')}
- />
+ <span {...stylex.props(styles.status)}>
+ <span {...stylex.props(styles.statusDot, device.online && styles.statusDotOnline)} />
{t(
device.online
? 'builtins.lobe-remote-device.render.online'
@@ -144,12 +138,17 @@ const DeviceCard = memo<DeviceCardProps>(({ device, activated, variant = 'card'
)}
</Flexbox>
{activated ? (
- <span className={[styles.badge, styles.activated].join(' ')}>
+ <span
+ className={[
+ stylex.props(styles.badge).className,
+ stylex.props(styles.activated).className,
+ ].join(' ')}
+ >
<Icon icon={CheckCircle2} size={12} />
{t('builtins.lobe-remote-device.render.activated')}
</span>
) : (
- details && <span className={styles.details}>{details}</span>
+ details && <span {...stylex.props(styles.details)}>{details}</span>
)}
</Flexbox>
);
diff --git a/packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx b/packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx
index 2533596ef88..9fa8ea3e042 100644
--- a/packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx
+++ b/packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx
@@ -2,35 +2,38 @@
import { type BuiltinRenderProps } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { ListOnlineDevicesState } from '../../../types';
import DeviceCard from '../DeviceCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorBgContainer};
- `,
- empty: css`
- padding-block: 12px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
-
- font-size: ${cssVar.fontSize};
- color: ${cssVar.colorTextDescription};
-
- background: ${cssVar.colorBgContainer};
- `,
-}));
+const styles = stylex.create({
+ card: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ empty: {
+ paddingBlock: '12px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ fontSize: cssVar.fontSize,
+ color: cssVar.colorTextDescription,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
const ListDevices = memo<BuiltinRenderProps<undefined, ListOnlineDevicesState>>(
({ pluginState }) => {
@@ -39,14 +42,14 @@ const ListDevices = memo<BuiltinRenderProps<undefined, ListOnlineDevicesState>>(
if (devices.length === 0) {
return (
- <div className={styles.empty}>
+ <div {...stylex.props(styles.empty)}>
{t('builtins.lobe-remote-device.render.noOnlineDevices')}
</div>
);
}
return (
- <Flexbox className={styles.card} role={'list'}>
+ <Flexbox className={stylex.props(styles.card).className} role={'list'}>
{devices.map((device) => (
<DeviceCard device={device} key={device.deviceId} variant={'listItem'} />
))}
diff --git a/packages/builtin-tool-remote-device/vitest.config.mts b/packages/builtin-tool-remote-device/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-remote-device/vitest.config.mts
+++ b/packages/builtin-tool-remote-device/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx b/packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx
index 80062008789..c420ea6df63 100644
--- a/packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx
+++ b/packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckCircle2, CircleAlert } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -38,30 +39,18 @@ const getIntentLabelKey = (data?: Partial<DeclareSelfFeedbackIntentParams>) => {
return 'builtins.lobe-self-feedback-intent.apiName.declareSelfFeedbackIntent';
};
-const styles = createStaticStyles(({ css, cssVar }) => ({
- iconAccepted: css`
- flex-shrink: 0;
- color: ${cssVar.colorSuccess};
- `,
- iconRejected: css`
- flex-shrink: 0;
- color: ${cssVar.colorWarning};
- `,
- meta: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- summary: css`
- overflow: hidden;
-
- min-width: 0;
- max-width: 320px;
-
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ iconAccepted: { flexShrink: 0, color: cssVar.colorSuccess },
+ iconRejected: { flexShrink: 0, color: cssVar.colorWarning },
+ meta: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextTertiary },
+ summary: {
+ overflow: 'hidden',
+ minWidth: '0',
+ maxWidth: '320px',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const DeclareSelfFeedbackIntentInspector = memo<
BuiltinInspectorProps<DeclareSelfFeedbackIntentParams, DeclareSelfFeedbackIntentState>
@@ -89,16 +78,26 @@ export const DeclareSelfFeedbackIntentInspector = memo<
{title}
</span>
{summary && (
- <span className={cx(highlightTextStyles.primary, styles.summary)}>{summary}</span>
+ <span className={cx(stylex.props(styles.summary).className, highlightTextStyles.primary)}>
+ {summary}
+ </span>
)}
{isSettled &&
pluginState &&
(pluginState.accepted ? (
- <Icon className={styles.iconAccepted} icon={CheckCircle2} size={14} />
+ <Icon
+ className={stylex.props(styles.iconAccepted).className}
+ icon={CheckCircle2}
+ size={14}
+ />
) : (
<>
- <Icon className={styles.iconRejected} icon={CircleAlert} size={14} />
- <span className={styles.meta}>
+ <Icon
+ className={stylex.props(styles.iconRejected).className}
+ icon={CircleAlert}
+ size={14}
+ />
+ <span {...stylex.props(styles.meta)}>
{t('builtins.lobe-self-feedback-intent.inspector.rejected')}
</span>
</>
diff --git a/packages/builtin-tool-self-iteration/vitest.config.mts b/packages/builtin-tool-self-iteration/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-self-iteration/vitest.config.mts
+++ b/packages/builtin-tool-self-iteration/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx b/packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx
index 4e3f9ac32a9..7fde0e46464 100644
--- a/packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx
+++ b/packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { ImportFromMarketParams, ImportFromMarketState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const ImportFromMarketInspector = memo<
BuiltinInspectorProps<ImportFromMarketParams, ImportFromMarketState>
@@ -47,9 +44,17 @@ export const ImportFromMarketInspector = memo<
{!isLoading &&
hasResult &&
(isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
))}
</div>
);
diff --git a/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx b/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
index 36676385b42..d636b3299ce 100644
--- a/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
+++ b/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { ImportSkillParams, ImportSkillState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const ImportSkillInspector = memo<
BuiltinInspectorProps<ImportSkillParams, ImportSkillState>
@@ -47,9 +44,17 @@ export const ImportSkillInspector = memo<
{!isLoading &&
hasResult &&
(isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
))}
</div>
);
diff --git a/packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx b/packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx
index a43f3d4b2c3..b8845bc2aab 100644
--- a/packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx
+++ b/packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx
@@ -1,58 +1,42 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Tag, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { MarketSkillItem, SearchSkillParams, SearchSkillState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- `,
- description: css`
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
- empty: css`
- padding: 24px;
- color: ${cssVar.colorTextTertiary};
- text-align: center;
- `,
- identifier: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- item: css`
- padding-block: 12px;
- padding-inline: 14px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- meta: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- title: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ description: { fontSize: '13px', lineHeight: 1.6, color: cssVar.colorTextSecondary },
+ empty: { padding: '24px', color: cssVar.colorTextTertiary, textAlign: 'center' },
+ identifier: {
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ },
+ item: {
+ paddingBlock: '12px',
+ paddingInline: '14px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ meta: { fontSize: '12px', color: cssVar.colorTextTertiary },
+ title: { fontSize: '14px', fontWeight: 500, color: cssVar.colorText },
+});
interface SkillItemProps {
skill: MarketSkillItem;
@@ -62,13 +46,13 @@ const SkillItem = memo<SkillItemProps>(({ skill }) => {
const { t } = useTranslation('plugin');
return (
- <Flexbox className={styles.item} gap={6}>
+ <Flexbox className={stylex.props(styles.item).className} gap={6}>
<Flexbox gap={2}>
- <div className={styles.title}>{skill.name}</div>
- <div className={styles.identifier}>{skill.identifier}</div>
+ <div {...stylex.props(styles.title)}>{skill.name}</div>
+ <div {...stylex.props(styles.identifier)}>{skill.identifier}</div>
</Flexbox>
{(skill.description || skill.summary) && (
- <div className={styles.description}>{skill.summary || skill.description}</div>
+ <div {...stylex.props(styles.description)}>{skill.summary || skill.description}</div>
)}
<Flexbox horizontal gap={6} wrap={'wrap'}>
{skill.version && (
@@ -82,7 +66,7 @@ const SkillItem = memo<SkillItemProps>(({ skill }) => {
{skill.category && <Tag size={'small'}>{skill.category}</Tag>}
</Flexbox>
{skill.repository && (
- <Text ellipsis className={styles.meta}>
+ <Text ellipsis className={stylex.props(styles.meta).className}>
{`${t('builtins.lobe-skill-store.render.repository')}: ${skill.repository}`}
</Text>
)}
@@ -100,14 +84,16 @@ const SearchSkill = memo<BuiltinRenderProps<SearchSkillParams, SearchSkillState>
if (items.length === 0) {
return (
- <div className={styles.container}>
- <div className={styles.empty}>{t('builtins.lobe-skill-store.inspector.noResults')}</div>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.empty)}>
+ {t('builtins.lobe-skill-store.inspector.noResults')}
+ </div>
</div>
);
}
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
{items.map((skill) => (
<SkillItem key={skill.identifier} skill={skill} />
))}
diff --git a/packages/builtin-tool-skill-store/vitest.config.mts b/packages/builtin-tool-skill-store/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-skill-store/vitest.config.mts
+++ b/packages/builtin-tool-skill-store/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
index b2b88f888a5..4e90cd696c8 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
@@ -1,8 +1,9 @@
'use client';
import { type BuiltinInspectorProps } from '@lobechat/types';
-import { Spin } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Spin } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,12 +12,7 @@ import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/sty
import type { ExecScriptParams, ExecScriptState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({ statusIcon: { marginBlockEnd: '-2px', marginInlineStart: '4px' } });
export const ExecScriptInspector = memo<BuiltinInspectorProps<ExecScriptParams, ExecScriptState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -60,12 +56,20 @@ export const ExecScriptInspector = memo<BuiltinInspectorProps<ExecScriptParams,
</span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
{isLoading ? null : isStillRunning ? (
- <Spin className={styles.statusIcon} size="small" />
+ <Spin className={stylex.props(styles.statusIcon).className} size="small" />
) : pluginState?.success !== undefined ? (
isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
)
) : null}
</span>
diff --git a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
index 8ee28e0da78..3a376bfb0b8 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
@@ -2,8 +2,10 @@
import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';
import { type BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -47,39 +49,35 @@ const resolveLabelKey = (
}
};
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- max-width: 100%;
- margin-inline-start: 6px;
- padding-block: 3px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 999px;
-
- background: ${cssVar.colorBgContainer};
- `,
- skillIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
- skillName: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '100%',
+ marginInlineStart: '6px',
+ paddingBlock: '3px',
+ paddingInline: '10px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ skillIcon: { flexShrink: 0, color: cssVar.colorTextDescription },
+ skillName: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const RunSkillInspector = memo<
BuiltinInspectorProps<ActivateSkillParams, ActivateSkillState>
@@ -101,9 +99,9 @@ export const RunSkillInspector = memo<
return (
<div className={inspectorTextStyles.root}>
<span className={shinyTextStyles.shinyText}>{label}:</span>
- <span className={styles.chip}>
- <SkillsIcon className={styles.skillIcon} size={12} />
- <span className={styles.skillName}>{displayName}</span>
+ <span {...stylex.props(styles.chip)}>
+ <SkillsIcon className={stylex.props(styles.skillIcon).className} size={12} />
+ <span {...stylex.props(styles.skillName)}>{displayName}</span>
</span>
</div>
);
@@ -113,9 +111,9 @@ export const RunSkillInspector = memo<
<div className={inspectorTextStyles.root}>
<span className={cx(isLoading && shinyTextStyles.shinyText)}>{label}:</span>
{displayName && (
- <span className={styles.chip}>
- <SkillsIcon className={styles.skillIcon} size={12} />
- <span className={styles.skillName}>{displayName}</span>
+ <span {...stylex.props(styles.chip)}>
+ <SkillsIcon className={stylex.props(styles.skillIcon).className} size={12} />
+ <span {...stylex.props(styles.skillName)}>{displayName}</span>
</span>
)}
</div>
diff --git a/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx b/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx
index 682ff332eba..750abe9cd05 100644
--- a/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx
@@ -2,24 +2,21 @@
import { type BuiltinRenderProps } from '@lobechat/types';
import { Block, Flexbox, Highlighter } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { ExecScriptParams, ExecScriptState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
+});
const ExecScript = memo<BuiltinRenderProps<ExecScriptParams, ExecScriptState>>(
({ args, content, pluginState }) => {
const { command } = pluginState || {};
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Block gap={8} padding={8} variant={'outlined'}>
<Highlighter
wrap
diff --git a/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx b/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx
index f72cb153b13..afae5b17ec3 100644
--- a/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx
@@ -1,19 +1,15 @@
'use client';
import { type BuiltinRenderProps } from '@lobechat/types';
-import { Block, Flexbox, Highlighter, Markdown } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Flexbox, Highlighter, Markdown, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { ReadReferenceParams, ReadReferenceState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
+});
const getFileExtension = (path: string): string => {
const parts = path.split('.');
@@ -66,7 +62,7 @@ const ReadReference = memo<BuiltinRenderProps<ReadReferenceParams, ReadReference
const sizeText = size ? formatSize(size) : '';
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
<Text code ellipsis as={'span'} fontSize={12}>
{displayPath}
diff --git a/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
index d513ac23f5d..787cf96874c 100644
--- a/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
@@ -2,39 +2,34 @@
import { type BuiltinRenderProps } from '@lobechat/types';
import { Flexbox, Markdown, ScrollShadow } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { ActivateSkillParams, ActivateSkillState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-block: 8px;
- padding-inline: 16px;
- font-size: 14px;
- `,
- description: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- header: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- name: css`
- font-weight: 500;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingBlock: '8px', paddingInline: '16px', fontSize: '14px' },
+ description: { fontSize: '12px', color: cssVar.colorTextSecondary },
+ header: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ name: { fontWeight: 500 },
+});
const RunSkill = memo<BuiltinRenderProps<ActivateSkillParams, ActivateSkillState>>(
({ content, pluginState }) => {
@@ -44,13 +39,18 @@ const RunSkill = memo<BuiltinRenderProps<ActivateSkillParams, ActivateSkillState
if (!displayName) return null;
return (
- <Flexbox className={styles.container}>
- <Flexbox className={styles.header} gap={4}>
- <span className={styles.name}>{displayName}</span>
- {description && <span className={styles.description}>{description}</span>}
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox className={stylex.props(styles.header).className} gap={4}>
+ <span {...stylex.props(styles.name)}>{displayName}</span>
+ {description && <span {...stylex.props(styles.description)}>{description}</span>}
</Flexbox>
{content && (
- <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>
+ <ScrollShadow
+ className={stylex.props(styles.content).className}
+ offset={12}
+ size={12}
+ style={{ maxHeight: 400 }}
+ >
<Markdown style={{ overflow: 'unset' }} variant={'chat'}>
{content}
</Markdown>
diff --git a/packages/builtin-tool-skills/vitest.config.mts b/packages/builtin-tool-skills/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-skills/vitest.config.mts
+++ b/packages/builtin-tool-skills/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx
index 755e69623c8..bbe4430f4c3 100644
--- a/packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon, Tooltip } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Icon, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CornerDownRight } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,58 +12,54 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { CreateTaskParams, CreateTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 240px;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- subtaskTag: css`
- display: inline-flex;
- flex-shrink: 0;
- gap: 4px;
- align-items: center;
-
- padding-block: 1px;
- padding-inline: 6px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 11px;
- color: ${cssVar.colorTextTertiary};
-
- background: transparent;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '240px',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ subtaskTag: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ gap: '4px',
+ alignItems: 'center',
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '11px',
+ color: cssVar.colorTextTertiary,
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ },
+});
export const CreateTaskInspector = memo<BuiltinInspectorProps<CreateTaskParams, CreateTaskState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -88,18 +85,21 @@ export const CreateTaskInspector = memo<BuiltinInspectorProps<CreateTaskParams,
{t('builtins.lobe-task.apiName.createTask')}
</span>
{identifier && (
- <span className={styles.identifierChip} style={{ marginInlineStart: 6 }}>
+ <span
+ className={stylex.props(styles.identifierChip).className}
+ style={{ marginInlineStart: 6 }}
+ >
{identifier}
</span>
)}
{name && (
- <span className={styles.chip} style={{ color: cssVar.colorText }}>
+ <span className={stylex.props(styles.chip).className} style={{ color: cssVar.colorText }}>
{name}
</span>
)}
{parentIdentifier && (
<Tooltip title={t('builtins.lobe-task.create.subtaskOf', { parent: parentIdentifier })}>
- <span className={styles.subtaskTag}>
+ <span {...stylex.props(styles.subtaskTag)}>
<Icon icon={CornerDownRight} size={11} />
{parentIdentifier}
</span>
diff --git a/packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx b/packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx
index d6a5eeed312..4c27cb9f8f6 100644
--- a/packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,49 +11,38 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { CreateTasksParams, CreateTasksState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- countBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorSuccess};
-
- background: ${cssVar.colorSuccessBg};
- `,
- moreBadge: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- previewChip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 280px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- separator: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ countBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+ moreBadge: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextTertiary },
+ previewChip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '280px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ separator: { flexShrink: 0, color: cssVar.colorTextQuaternary },
+});
export const CreateTasksInspector = memo<
BuiltinInspectorProps<CreateTasksParams, CreateTasksState>
@@ -80,16 +71,16 @@ export const CreateTasksInspector = memo<
{t('builtins.lobe-task.apiName.createTasks')}
</span>
{count > 0 && (
- <span className={styles.countBadge}>
+ <span {...stylex.props(styles.countBadge)}>
{t('builtins.lobe-task.createTasks.count', { count })}
</span>
)}
{previewName && (
<>
- <span className={styles.separator}>·</span>
- <span className={styles.previewChip}>{previewName}</span>
+ <span {...stylex.props(styles.separator)}>·</span>
+ <span {...stylex.props(styles.previewChip)}>{previewName}</span>
{remaining > 0 && (
- <span className={styles.moreBadge}>
+ <span {...stylex.props(styles.moreBadge)}>
{t('builtins.lobe-task.createTasks.more', { count: remaining })}
</span>
)}
diff --git a/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
index 57abaca4cc1..cc557daa40c 100644
--- a/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,24 +11,24 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { DeleteTaskParams, DeleteTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 8px;
- border: 1px dashed ${cssVar.colorErrorBorder};
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorError};
- text-decoration: line-through;
-
- background: transparent;
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorErrorBorder,
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorError,
+ textDecoration: 'line-through',
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ },
+});
export const DeleteTaskInspector = memo<BuiltinInspectorProps<DeleteTaskParams, DeleteTaskState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -42,7 +44,7 @@ export const DeleteTaskInspector = memo<BuiltinInspectorProps<DeleteTaskParams,
>
{t('builtins.lobe-task.apiName.deleteTask')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
index ced9e283d78..a8d30d53433 100644
--- a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
@@ -2,7 +2,9 @@
import { priorityLabel } from '@lobechat/prompts';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { ReactNode } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,116 +17,94 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { EditTaskParams, EditTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- addChip: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorSuccess};
-
- background: ${cssVar.colorSuccessBg};
- `,
- assigneeAvatar: css`
- flex-shrink: 0;
- `,
- assigneeChip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- max-width: 220px;
- padding-block: 1px;
- padding-inline: 4px 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
- assigneeName: css`
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 200px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- group: css`
- display: inline-flex;
- flex-wrap: wrap;
- gap: 4px;
- align-items: center;
- `,
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- label: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- removeChip: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border: 1px dashed ${cssVar.colorErrorBorder};
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorError};
- text-decoration: line-through;
-
- background: transparent;
- `,
-}));
+const styles = stylex.create({
+ addChip: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+ assigneeAvatar: { flexShrink: 0 },
+ assigneeChip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '220px',
+ paddingBlock: '1px',
+ paddingInlineStart: '4px',
+ paddingInlineEnd: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ assigneeName: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '200px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ group: { display: 'inline-flex', flexWrap: 'wrap', gap: '4px', alignItems: 'center' },
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ label: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextTertiary },
+ removeChip: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorErrorBorder,
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorError,
+ textDecoration: 'line-through',
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ },
+});
const AssigneeChip = memo<{ agentId: string }>(({ agentId }) => {
const agentMeta = useAgentDisplayMeta(agentId, { fallbackToDefault: false });
const displayName = agentMeta?.title || agentId;
return (
- <span className={styles.assigneeChip} title={displayName}>
- <span className={styles.assigneeAvatar}>
+ <span {...stylex.props(styles.assigneeChip)} title={displayName}>
+ <span {...stylex.props(styles.assigneeAvatar)}>
<AssigneeAvatar agentId={agentId} fallbackToDefault={false} size={16} />
</span>
- <span className={styles.assigneeName}>{displayName}</span>
+ <span {...stylex.props(styles.assigneeName)}>{displayName}</span>
</span>
);
});
@@ -136,11 +116,11 @@ const MemberChip = memo<{ userId: string }>(({ userId }) => {
const displayName = meta?.title || userId;
return (
- <span className={styles.assigneeChip} data-testid="member-chip" title={displayName}>
- <span className={styles.assigneeAvatar}>
+ <span {...stylex.props(styles.assigneeChip)} data-testid="member-chip" title={displayName}>
+ <span {...stylex.props(styles.assigneeAvatar)}>
<AssigneeUserAvatar size={16} userId={userId} />
</span>
- <span className={styles.assigneeName}>{displayName}</span>
+ <span {...stylex.props(styles.assigneeName)}>{displayName}</span>
</span>
);
});
@@ -160,8 +140,8 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content: (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.rename')}</span>
- <span className={styles.chip}>{params.name}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.rename')}</span>
+ <span {...stylex.props(styles.chip)}>{params.name}</span>
</>
),
key: 'name',
@@ -172,8 +152,8 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content: (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.priority')}</span>
- <span className={styles.chip}>{priorityLabel(params.priority)}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.priority')}</span>
+ <span {...stylex.props(styles.chip)}>{priorityLabel(params.priority)}</span>
</>
),
key: 'priority',
@@ -182,14 +162,18 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
if (params.instruction !== undefined) {
segments.push({
- content: <span className={styles.chip}>{t('builtins.lobe-task.edit.instruction')}</span>,
+ content: (
+ <span {...stylex.props(styles.chip)}>{t('builtins.lobe-task.edit.instruction')}</span>
+ ),
key: 'instruction',
});
}
if (params.description !== undefined) {
segments.push({
- content: <span className={styles.chip}>{t('builtins.lobe-task.edit.description')}</span>,
+ content: (
+ <span {...stylex.props(styles.chip)}>{t('builtins.lobe-task.edit.description')}</span>
+ ),
key: 'description',
});
}
@@ -198,11 +182,11 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content:
params.parentIdentifier === null ? (
- <span className={styles.chip}>{t('builtins.lobe-task.edit.parentClear')}</span>
+ <span {...stylex.props(styles.chip)}>{t('builtins.lobe-task.edit.parentClear')}</span>
) : (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.parent')}</span>
- <span className={styles.chip}>{params.parentIdentifier}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.parent')}</span>
+ <span {...stylex.props(styles.chip)}>{params.parentIdentifier}</span>
</>
),
key: 'parent',
@@ -217,12 +201,12 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content: hasAnyAssignee ? (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.assign')}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.assign')}</span>
{params.assigneeAgentId && <AssigneeChip agentId={params.assigneeAgentId} />}
{params.assigneeUserId && <MemberChip userId={params.assigneeUserId} />}
</>
) : (
- <span className={styles.chip}>{t('builtins.lobe-task.edit.unassign')}</span>
+ <span {...stylex.props(styles.chip)}>{t('builtins.lobe-task.edit.unassign')}</span>
),
key: 'assignee',
});
@@ -232,9 +216,9 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content: (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.blocksOn')}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.blocksOn')}</span>
{params.addDependencies.map((dep) => (
- <span className={styles.addChip} key={`add-${dep}`}>
+ <span {...stylex.props(styles.addChip)} key={`add-${dep}`}>
{dep}
</span>
))}
@@ -248,9 +232,9 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
segments.push({
content: (
<>
- <span className={styles.label}>{t('builtins.lobe-task.edit.unblocks')}</span>
+ <span {...stylex.props(styles.label)}>{t('builtins.lobe-task.edit.unblocks')}</span>
{params.removeDependencies.map((dep) => (
- <span className={styles.removeChip} key={`remove-${dep}`}>
+ <span {...stylex.props(styles.removeChip)} key={`remove-${dep}`}>
{dep}
</span>
))}
@@ -265,9 +249,9 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-task.apiName.editTask')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
{segments.map((segment, index) => (
- <span className={styles.group} key={segment.key}>
+ <span {...stylex.props(styles.group)} key={segment.key}>
{index > 0 && <span style={{ color: cssVar.colorTextQuaternary }}>·</span>}
{segment.content}
</span>
diff --git a/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
index 187de30a645..feb49b31aa0 100644
--- a/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx, Icon } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Play } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,44 +12,37 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { RunTaskParams, RunTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- promptChip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 240px;
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- separator: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ promptChip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '240px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ separator: { flexShrink: 0, color: cssVar.colorTextQuaternary },
+});
export const RunTaskInspector = memo<BuiltinInspectorProps<RunTaskParams, RunTaskState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -65,13 +60,16 @@ export const RunTaskInspector = memo<BuiltinInspectorProps<RunTaskParams, RunTas
{t('builtins.lobe-task.apiName.runTask')}
</span>
{identifier && (
- <span className={styles.identifierChip} style={{ marginInlineStart: 4 }}>
+ <span
+ className={stylex.props(styles.identifierChip).className}
+ style={{ marginInlineStart: 4 }}
+ >
{identifier}
</span>
)}
{continueTopicId && (
<>
- <span className={styles.separator}>·</span>
+ <span {...stylex.props(styles.separator)}>·</span>
<span style={{ color: cssVar.colorTextTertiary, fontSize: 12 }}>
{t('builtins.lobe-task.run.continueTopic')}
</span>
@@ -79,8 +77,8 @@ export const RunTaskInspector = memo<BuiltinInspectorProps<RunTaskParams, RunTas
)}
{prompt && (
<>
- <span className={styles.separator}>·</span>
- <span className={styles.promptChip}>{prompt}</span>
+ <span {...stylex.props(styles.separator)}>·</span>
+ <span {...stylex.props(styles.promptChip)}>{prompt}</span>
</>
)}
</div>
diff --git a/packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx b/packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx
index f1d74fc60ab..a4a3dfd0de2 100644
--- a/packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx
@@ -1,8 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Play } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,55 +12,42 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { RunTasksParams, RunTasksState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- countBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorWarning};
-
- background: ${cssVar.colorWarningBg};
- `,
- failedBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- moreBadge: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- separator: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ countBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorWarning,
+ backgroundColor: cssVar.colorWarningBg,
+ backgroundImage: 'none',
+ },
+ failedBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorError,
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ moreBadge: { flexShrink: 0, fontSize: '12px', color: cssVar.colorTextTertiary },
+ separator: { flexShrink: 0, color: cssVar.colorTextQuaternary },
+});
export const RunTasksInspector = memo<BuiltinInspectorProps<RunTasksParams, RunTasksState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -90,23 +78,23 @@ export const RunTasksInspector = memo<BuiltinInspectorProps<RunTasksParams, RunT
{t('builtins.lobe-task.apiName.runTasks')}
</span>
{count > 0 && (
- <span className={styles.countBadge}>
+ <span {...stylex.props(styles.countBadge)}>
{t('builtins.lobe-task.runTasks.count', { count })}
</span>
)}
{previewId && (
<>
- <span className={styles.separator}>·</span>
- <span className={styles.identifierChip}>{previewId}</span>
+ <span {...stylex.props(styles.separator)}>·</span>
+ <span {...stylex.props(styles.identifierChip)}>{previewId}</span>
{remaining > 0 && (
- <span className={styles.moreBadge}>
+ <span {...stylex.props(styles.moreBadge)}>
{t('builtins.lobe-task.runTasks.more', { count: remaining })}
</span>
)}
</>
)}
{failed > 0 && (
- <span className={styles.failedBadge}>
+ <span {...stylex.props(styles.failedBadge)}>
{t('builtins.lobe-task.runTasks.failedCount', { count: failed })}
</span>
)}
diff --git a/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx b/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
index 90a13becbf9..394a5e5dbbe 100644
--- a/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,37 +11,30 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { SetTaskScheduleParams, SetTaskScheduleState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- modeChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorInfo};
-
- background: ${cssVar.colorInfoBg};
- `,
- separator: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ modeChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorInfo,
+ backgroundColor: cssVar.colorInfoBg,
+ backgroundImage: 'none',
+ },
+ separator: { flexShrink: 0, color: cssVar.colorTextQuaternary },
+});
export const SetTaskScheduleInspector = memo<
BuiltinInspectorProps<SetTaskScheduleParams, SetTaskScheduleState>
@@ -55,11 +50,11 @@ export const SetTaskScheduleInspector = memo<
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-task.apiName.setTaskSchedule')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
{modeLabel && (
<>
- <span className={styles.separator}>·</span>
- <span className={styles.modeChip}>{modeLabel}</span>
+ <span {...stylex.props(styles.separator)}>·</span>
+ <span {...stylex.props(styles.modeChip)}>{modeLabel}</span>
</>
)}
</div>
diff --git a/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx b/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
index 0cfbe5cb530..bad6c84837b 100644
--- a/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,21 +11,19 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { SetTaskVerifyParams, SetTaskVerifyState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
export const SetTaskVerifyInspector = memo<
BuiltinInspectorProps<SetTaskVerifyParams, SetTaskVerifyState>
@@ -37,7 +37,7 @@ export const SetTaskVerifyInspector = memo<
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-task.apiName.setTaskVerify')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
</div>
);
});
diff --git a/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx b/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx
index 3945577ccb7..ba311e7095b 100644
--- a/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,49 +19,45 @@ import type {
} from '../../../types';
import { TaskApiName } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 220px;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- contentChip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- align-items: center;
-
- min-width: 0;
- max-width: 260px;
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '220px',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ contentChip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ alignItems: 'center',
+ minWidth: '0',
+ maxWidth: '260px',
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface TaskCommentInspectorProps extends BuiltinInspectorProps<
AddTaskCommentParams | UpdateTaskCommentParams | DeleteTaskCommentParams,
@@ -99,9 +97,9 @@ export const TaskCommentInspector = memo<TaskCommentInspectorProps>(
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t(selectLabelKey(apiName))}
</span>
- {identifier && <span className={styles.chip}>{identifier}</span>}
- {commentId && <span className={styles.chip}>{commentId}</span>}
- {content && <span className={styles.contentChip}>{content}</span>}
+ {identifier && <span {...stylex.props(styles.chip)}>{identifier}</span>}
+ {commentId && <span {...stylex.props(styles.chip)}>{commentId}</span>}
+ {content && <span {...stylex.props(styles.contentChip)}>{content}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx b/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
index 0258a8410d0..b5338729798 100644
--- a/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps, TaskStatus } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,34 +21,27 @@ const STATUS_TONE: Partial<Record<TaskStatus, { bg: string; fg: string }>> = {
scheduled: { bg: cssVar.colorInfoBg, fg: cssVar.colorInfo },
};
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- separator: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextQuaternary};
- `,
- statusChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ separator: { flexShrink: 0, color: cssVar.colorTextQuaternary },
+ statusChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ },
+});
export const UpdateTaskStatusInspector = memo<
BuiltinInspectorProps<UpdateTaskStatusParams, UpdateTaskStatusState>
@@ -62,12 +57,12 @@ export const UpdateTaskStatusInspector = memo<
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-task.apiName.updateTaskStatus')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
{status && (
<>
- <span className={styles.separator}>·</span>
+ <span {...stylex.props(styles.separator)}>·</span>
<span
- className={styles.statusChip}
+ className={stylex.props(styles.statusChip).className}
style={{
background: tone?.bg ?? cssVar.colorFillTertiary,
color: tone?.fg ?? cssVar.colorTextSecondary,
diff --git a/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
index b7a82c6fbb5..12a53f6d928 100644
--- a/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,22 +11,20 @@ import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ViewTaskParams, ViewTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- identifierChip: css`
- flex-shrink: 0;
-
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ identifierChip: {
+ flexShrink: 0,
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
export const ViewTaskInspector = memo<BuiltinInspectorProps<ViewTaskParams, ViewTaskState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -37,7 +37,7 @@ export const ViewTaskInspector = memo<BuiltinInspectorProps<ViewTaskParams, View
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-task.apiName.viewTask')}
</span>
- {identifier && <span className={styles.identifierChip}>{identifier}</span>}
+ {identifier && <span {...stylex.props(styles.identifierChip)}>{identifier}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
index 377f75e1f5c..757ff3c3edd 100644
--- a/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { ActionIcon, Block, createStaticStyles, cssVar, Markdown, Text } from '@lobehub/ui';
+import { ActionIcon, Block, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { PanelRight, PanelRightClose } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,65 +15,51 @@ import { resolveTaskOpenTarget } from '../../../taskRef';
import type { CreateTaskParams, CreateTaskState } from '../../../types';
import { useTaskDetailToggle } from '../shared';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- description: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 3;
-
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextTertiary};
- `,
- identifier: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- instruction: css`
- /* The instruction is model-facing markdown; render it as a faded preview
- rather than flattening it to plain text. Full content lives in the
- expanded detail panel. */
- overflow: hidden;
- max-height: 132px;
-
- mask-image: linear-gradient(to bottom, black 78%, transparent);
- `,
- row: css`
- display: flex;
- gap: 8px;
- align-items: center;
- `,
- taskItem: css`
- display: flex;
- flex-direction: column;
- gap: 6px;
-
- padding-block: 10px;
- padding-inline: 12px;
- `,
- title: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 0;
-
- font-size: 13px;
- line-height: 1.4;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ description: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '3',
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextTertiary,
+ },
+ identifier: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ instruction: {
+ overflow: 'hidden',
+ maxHeight: '132px',
+ maskImage: 'linear-gradient(to bottom, black 78%, transparent)',
+ },
+ row: { display: 'flex', gap: '8px', alignItems: 'center' },
+ taskItem: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '6px',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ },
+ title: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: '0',
+ fontSize: '13px',
+ lineHeight: 1.4,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
export const CreateTaskRender = memo<BuiltinRenderProps<CreateTaskParams, CreateTaskState>>(
({ args, pluginState }) => {
@@ -102,10 +90,10 @@ export const CreateTaskRender = memo<BuiltinRenderProps<CreateTaskParams, Create
width={'100%'}
onClick={canOpen ? open : undefined}
>
- <div className={styles.taskItem}>
- <div className={styles.row}>
- {identifier && <span className={styles.identifier}>{identifier}</span>}
- {name && <Text className={styles.title}>{name}</Text>}
+ <div {...stylex.props(styles.taskItem)}>
+ <div {...stylex.props(styles.row)}>
+ {identifier && <span {...stylex.props(styles.identifier)}>{identifier}</span>}
+ {name && <Text className={stylex.props(styles.title).className}>{name}</Text>}
{status && <TaskStatusTag disableDropdown size={14} status={status} />}
{!!priority && <TaskPriorityTag disableDropdown priority={priority} size={14} />}
{identifier && (
@@ -122,9 +110,9 @@ export const CreateTaskRender = memo<BuiltinRenderProps<CreateTaskParams, Create
)}
</div>
{description ? (
- <div className={styles.description}>{description}</div>
+ <div {...stylex.props(styles.description)}>{description}</div>
) : instruction ? (
- <div className={styles.instruction}>
+ <div {...stylex.props(styles.instruction)}>
<Markdown fontSize={12} variant={'chat'}>
{instruction}
</Markdown>
diff --git a/packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx
index 495427697a6..02f417d148f 100644
--- a/packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx
@@ -1,106 +1,77 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { CreateTaskParams, CreateTasksParams, CreateTasksState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- failedBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- headerCount: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
- identifier: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- index: css`
- flex-shrink: 0;
-
- width: 18px;
-
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-align: end;
- `,
- instruction: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextTertiary};
- `,
- row: css`
- display: flex;
- gap: 8px;
- align-items: center;
- min-width: 0;
- `,
- taskBody: css`
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 4px;
-
- min-width: 0;
- `,
- taskItem: css`
- display: flex;
- gap: 8px;
- align-items: flex-start;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- title: css`
- font-size: 13px;
- line-height: 1.4;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ failedBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorError,
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+ header: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ headerCount: { fontSize: '13px', fontWeight: 500, color: cssVar.colorText },
+ identifier: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ index: {
+ flexShrink: 0,
+ width: '18px',
+ fontSize: '12px',
+ color: cssVar.colorTextQuaternary,
+ textAlign: 'end',
+ },
+ instruction: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '2',
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextTertiary,
+ },
+ row: { display: 'flex', gap: '8px', alignItems: 'center', minWidth: '0' },
+ taskBody: { display: 'flex', flex: '1', flexDirection: 'column', gap: '4px', minWidth: '0' },
+ taskItem: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'flex-start',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ title: { fontSize: '13px', lineHeight: 1.4, color: cssVar.colorText },
+});
export const CreateTasksRender = memo<BuiltinRenderProps<CreateTasksParams, CreateTasksState>>(
({ args, pluginState }) => {
@@ -116,12 +87,12 @@ export const CreateTasksRender = memo<BuiltinRenderProps<CreateTasksParams, Crea
return (
<Block variant={'outlined'} width={'100%'}>
- <div className={styles.header}>
- <span className={styles.headerCount}>
+ <div {...stylex.props(styles.header)}>
+ <span {...stylex.props(styles.headerCount)}>
{t('builtins.lobe-task.createTasks.count', { count: rows.length })}
</span>
{failedCount > 0 && (
- <span className={styles.failedBadge}>
+ <span {...stylex.props(styles.failedBadge)}>
{t('builtins.lobe-task.createTasks.failedCount', { count: failedCount })}
</span>
)}
@@ -132,16 +103,18 @@ export const CreateTasksRender = memo<BuiltinRenderProps<CreateTasksParams, Crea
const failed = result && result.success === false;
return (
- <div className={styles.taskItem} key={`${identifier ?? index}-${task.name}`}>
- <div className={styles.index}>{index + 1}.</div>
- <div className={styles.taskBody}>
- <div className={styles.row}>
- {identifier && <span className={styles.identifier}>{identifier}</span>}
- <Text ellipsis className={styles.title}>
+ <div {...stylex.props(styles.taskItem)} key={`${identifier ?? index}-${task.name}`}>
+ <div {...stylex.props(styles.index)}>{index + 1}.</div>
+ <div {...stylex.props(styles.taskBody)}>
+ <div {...stylex.props(styles.row)}>
+ {identifier && <span {...stylex.props(styles.identifier)}>{identifier}</span>}
+ <Text ellipsis className={stylex.props(styles.title).className}>
{task.name}
</Text>
</div>
- {task.instruction && <div className={styles.instruction}>{task.instruction}</div>}
+ {task.instruction && (
+ <div {...stylex.props(styles.instruction)}>{task.instruction}</div>
+ )}
{failed && (
<Text as={'span'} fontSize={11} type={'danger'}>
{result?.error ?? 'Failed'}
diff --git a/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx b/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
index 402575f8bcb..953b8c1d8a1 100644
--- a/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { createStaticStyles, Markdown, Text } from '@lobehub/ui';
+import { Markdown, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Pencil } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,36 +21,31 @@ import {
TaskResultCard,
} from '../shared';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- addChip: css`
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorSuccess};
-
- background: ${cssVar.colorSuccessBg};
- `,
- deps: css`
- display: inline-flex;
- flex-wrap: wrap;
- gap: 4px;
- align-items: center;
- `,
- removeChip: css`
- padding-block: 1px;
- padding-inline: 8px;
- border: 1px dashed ${cssVar.colorErrorBorder};
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorError};
- text-decoration: line-through;
- `,
-}));
+const styles = stylex.create({
+ addChip: {
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+ deps: { display: 'inline-flex', flexWrap: 'wrap', gap: '4px', alignItems: 'center' },
+ removeChip: {
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorErrorBorder,
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorError,
+ textDecoration: 'line-through',
+ },
+});
export const EditTaskRender = memo<BuiltinRenderProps<EditTaskParams, EditTaskState>>(
({ args, pluginState }) => {
@@ -130,9 +127,9 @@ export const EditTaskRender = memo<BuiltinRenderProps<EditTaskParams, EditTaskSt
)}
{hasAddDeps && (
<InlineField label={t('builtins.lobe-task.edit.blocksOn')}>
- <div className={styles.deps}>
+ <div {...stylex.props(styles.deps)}>
{params.addDependencies!.map((dep) => (
- <span className={styles.addChip} key={`add-${dep}`}>
+ <span {...stylex.props(styles.addChip)} key={`add-${dep}`}>
{dep}
</span>
))}
@@ -141,9 +138,9 @@ export const EditTaskRender = memo<BuiltinRenderProps<EditTaskParams, EditTaskSt
)}
{hasRemoveDeps && (
<InlineField label={t('builtins.lobe-task.edit.unblocks')}>
- <div className={styles.deps}>
+ <div {...stylex.props(styles.deps)}>
{params.removeDependencies!.map((dep) => (
- <span className={styles.removeChip} key={`remove-${dep}`}>
+ <span {...stylex.props(styles.removeChip)} key={`remove-${dep}`}>
{dep}
</span>
))}
diff --git a/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx b/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
index 48cc326ed6a..c4c967307ba 100644
--- a/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, Markdown } from '@lobehub/ui';
+import { Markdown } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Play } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,23 +12,21 @@ import { resolveTaskOpenTarget } from '../../../taskRef';
import type { RunTaskParams, RunTaskState } from '../../../types';
import { InlineField, monoChipClassName, SectionField, TaskResultCard } from '../shared';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- topicChip: css`
- display: inline-flex;
- gap: 4px;
- align-items: center;
- align-self: flex-start;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorInfo};
-
- background: ${cssVar.colorInfoBg};
- `,
-}));
+const styles = stylex.create({
+ topicChip: {
+ display: 'inline-flex',
+ gap: '4px',
+ alignItems: 'center',
+ alignSelf: 'flex-start',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorInfo,
+ backgroundColor: cssVar.colorInfoBg,
+ backgroundImage: 'none',
+ },
+});
export const RunTaskRender = memo<BuiltinRenderProps<RunTaskParams, RunTaskState>>(
({ args, pluginState }) => {
@@ -51,7 +51,9 @@ export const RunTaskRender = memo<BuiltinRenderProps<RunTaskParams, RunTaskState
{hasBody ? (
<>
{continueTopic && (
- <span className={styles.topicChip}>{t('builtins.lobe-task.run.continueTopic')}</span>
+ <span {...stylex.props(styles.topicChip)}>
+ {t('builtins.lobe-task.run.continueTopic')}
+ </span>
)}
{prompt && (
<SectionField label={t('builtins.lobe-task.run.prompt')}>
diff --git a/packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx b/packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx
index 2adf8919ee9..729eb8bfa4c 100644
--- a/packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx
@@ -1,101 +1,76 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Block, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { RunTasksItemResult, RunTasksParams, RunTasksState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- failedBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- headerCount: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
- identifier: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- index: css`
- flex-shrink: 0;
-
- width: 18px;
-
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-align: end;
- `,
- meta: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 11px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- row: css`
- display: flex;
- gap: 8px;
- align-items: center;
- min-width: 0;
- `,
- taskBody: css`
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 4px;
-
- min-width: 0;
- `,
- taskItem: css`
- display: flex;
- gap: 8px;
- align-items: flex-start;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
-}));
+const styles = stylex.create({
+ failedBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorError,
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+ header: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ headerCount: { fontSize: '13px', fontWeight: 500, color: cssVar.colorText },
+ identifier: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ index: {
+ flexShrink: 0,
+ width: '18px',
+ fontSize: '12px',
+ color: cssVar.colorTextQuaternary,
+ textAlign: 'end',
+ },
+ meta: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '11px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ row: { display: 'flex', gap: '8px', alignItems: 'center', minWidth: '0' },
+ taskBody: { display: 'flex', flex: '1', flexDirection: 'column', gap: '4px', minWidth: '0' },
+ taskItem: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'flex-start',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'dashed', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+});
export const RunTasksRender = memo<BuiltinRenderProps<RunTasksParams, RunTasksState>>(
({ args, pluginState }) => {
@@ -114,12 +89,12 @@ export const RunTasksRender = memo<BuiltinRenderProps<RunTasksParams, RunTasksSt
return (
<Block variant={'outlined'} width={'100%'}>
- <div className={styles.header}>
- <span className={styles.headerCount}>
+ <div {...stylex.props(styles.header)}>
+ <span {...stylex.props(styles.headerCount)}>
{t('builtins.lobe-task.runTasks.count', { count: rows.length })}
</span>
{failedCount > 0 && (
- <span className={styles.failedBadge}>
+ <span {...stylex.props(styles.failedBadge)}>
{t('builtins.lobe-task.runTasks.failedCount', { count: failedCount })}
</span>
)}
@@ -130,17 +105,19 @@ export const RunTasksRender = memo<BuiltinRenderProps<RunTasksParams, RunTasksSt
const failedRow = result?.success === false;
return (
- <div className={styles.taskItem} key={`${row.identifier}-${index}`}>
- <div className={styles.index}>{index + 1}.</div>
- <div className={styles.taskBody}>
- <div className={styles.row}>
- <span className={styles.identifier}>{row.identifier}</span>
+ <div {...stylex.props(styles.taskItem)} key={`${row.identifier}-${index}`}>
+ <div {...stylex.props(styles.index)}>{index + 1}.</div>
+ <div {...stylex.props(styles.taskBody)}>
+ <div {...stylex.props(styles.row)}>
+ <span {...stylex.props(styles.identifier)}>{row.identifier}</span>
{success && (
<Icon icon={Check} size={14} style={{ color: cssVar.colorSuccess }} />
)}
{failedRow && <Icon icon={X} size={14} style={{ color: cssVar.colorError }} />}
</div>
- {result?.topicId && <span className={styles.meta}>topic {result.topicId}</span>}
+ {result?.topicId && (
+ <span {...stylex.props(styles.meta)}>topic {result.topicId}</span>
+ )}
{failedRow && (
<Text as={'span'} fontSize={11} type={'danger'}>
{result?.error || 'Failed'}
diff --git a/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx b/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
index 5872b38516d..faf69743106 100644
--- a/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, Icon, Markdown } from '@lobehub/ui';
+import { Icon, Markdown } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, ShieldCheck, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,38 +12,34 @@ import { resolveTaskOpenTarget } from '../../../taskRef';
import type { SetTaskVerifyParams, SetTaskVerifyState } from '../../../types';
import { TaskResultCard } from '../shared';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- offBadge: css`
- display: inline-flex;
- flex-shrink: 0;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- onBadge: css`
- display: inline-flex;
- flex-shrink: 0;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorSuccess};
-
- background: ${cssVar.colorSuccessBg};
- `,
-}));
+const styles = stylex.create({
+ offBadge: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ gap: '4px',
+ alignItems: 'center',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ onBadge: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ gap: '4px',
+ alignItems: 'center',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorSuccess,
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+});
export const SetTaskVerifyRender = memo<
BuiltinRenderProps<SetTaskVerifyParams, SetTaskVerifyState>
@@ -57,7 +55,7 @@ export const SetTaskVerifyRender = memo<
// The on/off state lives in the header; the body is just the acceptance
// requirement rendered as markdown.
const statusBadge = showStatus ? (
- <span className={enabled ? styles.onBadge : styles.offBadge}>
+ <span {...stylex.props(enabled ? styles.onBadge : styles.offBadge)}>
<Icon icon={enabled ? Check : X} size={13} />
{t(enabled ? 'builtins.lobe-task.verify.on' : 'builtins.lobe-task.verify.off')}
</span>
diff --git a/packages/builtin-tool-task/vitest.config.mts b/packages/builtin-tool-task/vitest.config.mts
index 04bfa099ade..3533670e5be 100644
--- a/packages/builtin-tool-task/vitest.config.mts
+++ b/packages/builtin-tool-task/vitest.config.mts
@@ -3,11 +3,14 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(packageDir, '../..');
export default defineConfig({
plugins: [
+ stylexPluginForVitest(),
{
enforce: 'pre',
name: 'stub-lobehub-ui-motion-provider',
diff --git a/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx b/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx
index 4695de98517..c826b43c1ca 100644
--- a/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx
+++ b/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx
@@ -3,30 +3,30 @@
import { normalizeAskUserQuestions } from '@lobechat/shared-tool-ui/ask-user';
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { AskUserQuestionArgs } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
export const AskUserQuestionInspector = memo<BuiltinInspectorProps<AskUserQuestionArgs>>(
({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
@@ -57,7 +57,7 @@ export const AskUserQuestionInspector = memo<BuiltinInspectorProps<AskUserQuesti
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{label}
</span>
- {summary && <span className={styles.chip}>{summary}</span>}
+ {summary && <span {...stylex.props(styles.chip)}>{summary}</span>}
</div>
);
},
diff --git a/packages/builtin-tool-user-interaction/vitest.config.mts b/packages/builtin-tool-user-interaction/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-user-interaction/vitest.config.mts
+++ b/packages/builtin-tool-user-interaction/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx b/packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx
index 17b78afdadc..a6eb9a62c4b 100644
--- a/packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx
+++ b/packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx
@@ -2,48 +2,48 @@
import type { BuiltinPlaceholderProps } from '@lobechat/types';
import { Block, Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { GenerateVideoParams } from '../../types';
import { GenerationProgress } from '../components/GenerationProgress';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- body: css`
- display: flex;
- align-items: center;
- justify-content: center;
-
- min-height: 180px;
- padding: 20px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- header: css`
- min-width: 0;
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- model: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- prompt: css`
- overflow: hidden;
-
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ body: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: '180px',
+ padding: '20px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ header: {
+ minWidth: '0',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ model: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ prompt: {
+ overflow: 'hidden',
+ fontSize: '14px',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface GenerateVideoPlaceholderProps extends BuiltinPlaceholderProps<GenerateVideoParams> {
toolCallId?: string;
@@ -55,11 +55,11 @@ export const GenerateVideoPlaceholder = memo<GenerateVideoPlaceholderProps>(
return (
<Block variant={'outlined'} width={'100%'}>
- <Flexbox className={styles.header} gap={2}>
- <span className={styles.prompt}>{args?.prompt}</span>
- {model && <span className={styles.model}>{model}</span>}
+ <Flexbox className={stylex.props(styles.header).className} gap={2}>
+ <span {...stylex.props(styles.prompt)}>{args?.prompt}</span>
+ {model && <span {...stylex.props(styles.model)}>{model}</span>}
</Flexbox>
- <div className={styles.body}>
+ <div {...stylex.props(styles.body)}>
<GenerationProgress
estimatedDurationMs={args?.estimatedDurationMs}
toolCallId={toolCallId}
diff --git a/packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx b/packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx
index e97a2c87df9..bb344a63692 100644
--- a/packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx
+++ b/packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps, VideoGenerationAsset } from '@lobechat/types';
-import { Alert, Block, Button, createStaticStyles, cssVar, Text } from '@lobehub/ui';
+import { Alert, Block, Button, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -23,84 +25,75 @@ import { resolveGenerationDisplayState } from '../utils/resolveGenerationDisplay
const POLLING_INTERVAL = 3000;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- body: css`
- overflow: hidden;
- display: flex;
- align-items: center;
- justify-content: center;
-
- min-height: 180px;
- padding: 12px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- error: css`
- color: ${cssVar.colorError};
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
-
- min-width: 0;
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- meta: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 2px;
-
- min-width: 0;
- `,
- model: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- prompt: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- statusBody: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
- align-items: center;
- justify-content: center;
-
- min-height: 180px;
- padding: 20px;
-
- text-align: center;
- `,
- statusChip: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ body: {
+ overflow: 'hidden',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: '180px',
+ padding: '12px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ error: { color: cssVar.colorError },
+ header: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ minWidth: '0',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ meta: {
+ overflow: 'hidden',
+ display: 'flex',
+ flex: '1',
+ flexDirection: 'column',
+ gap: '2px',
+ minWidth: '0',
+ },
+ model: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ prompt: {
+ overflow: 'hidden',
+ fontSize: '13px',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ statusBody: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: '180px',
+ padding: '20px',
+ textAlign: 'center',
+ },
+ statusChip: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
const isTerminalStatus = (status?: string) => status === 'success' || status === 'error';
@@ -224,21 +217,21 @@ export const GenerateVideoRender = memo<
return (
<Block variant={'outlined'} width={'100%'}>
- <div className={styles.header}>
- <div className={styles.meta}>
- <div className={styles.prompt}>{prompt}</div>
- <div className={styles.model}>{[provider, model].filter(Boolean).join('/')}</div>
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.meta)}>
+ <div {...stylex.props(styles.prompt)}>{prompt}</div>
+ <div {...stylex.props(styles.model)}>{[provider, model].filter(Boolean).join('/')}</div>
</div>
- <span className={styles.statusChip}>
+ <span {...stylex.props(styles.statusChip)}>
{t(`builtins.lobe-video-generation.render.status.${status}`)}
</span>
</div>
{url ? (
- <div className={styles.body}>
+ <div {...stylex.props(styles.body)}>
<MessageVideo maxHeight={560} poster={poster} src={url} />
</div>
) : (
- <div className={styles.statusBody}>
+ <div {...stylex.props(styles.statusBody)}>
{isGenerating ? (
<>
<GenerationProgress
@@ -246,7 +239,12 @@ export const GenerateVideoRender = memo<
toolCallId={toolCallId}
/>
{statusCheckFailed && (
- <Text as={'span'} className={styles.error} color={cssVar.colorError} fontSize={12}>
+ <Text
+ as={'span'}
+ className={stylex.props(styles.error).className}
+ color={cssVar.colorError}
+ fontSize={12}
+ >
{t('builtins.lobe-video-generation.render.statusCheckFailed')}
</Text>
)}
@@ -254,7 +252,7 @@ export const GenerateVideoRender = memo<
) : (
<Text
as={'span'}
- className={status === 'error' ? styles.error : undefined}
+ className={stylex.props(status === 'error' ? styles.error : undefined).className}
color={status === 'error' ? cssVar.colorError : cssVar.colorTextSecondary}
fontSize={12}
>
diff --git a/packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx b/packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx
index 3f771a52df2..48dc81cc99e 100644
--- a/packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx
+++ b/packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx
@@ -1,7 +1,9 @@
'use client';
import type { BuiltinRenderProps, VideoGenerationAsset } from '@lobechat/types';
-import { Alert, Block, createStaticStyles, Text } from '@lobehub/ui';
+import { Alert, Block, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,19 +11,10 @@ import MessageVideo from '@/components/MessageVideo';
import type { GetVideoGenerationStatusParams, GetVideoGenerationStatusState } from '../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- body: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 12px;
- `,
- status: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ body: { display: 'flex', flexDirection: 'column', gap: '8px', padding: '12px' },
+ status: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px', color: cssVar.colorTextSecondary },
+});
const getAssetUrl = (state?: GetVideoGenerationStatusState) => {
const asset = state?.generation?.asset;
@@ -54,8 +47,8 @@ export const GetVideoGenerationStatusRender = memo<
return (
<Block variant={'outlined'} width={'100%'}>
- <div className={styles.body}>
- <Text as={'span'} className={styles.status}>
+ <div {...stylex.props(styles.body)}>
+ <Text as={'span'} className={stylex.props(styles.status).className}>
{t(`builtins.lobe-video-generation.render.status.${pluginState.status}`)}
</Text>
{url && <MessageVideo maxHeight={560} poster={getPosterUrl(pluginState)} src={url} />}
diff --git a/packages/builtin-tool-video-generation/vitest.config.mts b/packages/builtin-tool-video-generation/vitest.config.mts
index 9e935ef21d1..b9ff9c80646 100644
--- a/packages/builtin-tool-video-generation/vitest.config.mts
+++ b/packages/builtin-tool-video-generation/vitest.config.mts
@@ -3,10 +3,13 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(packageDir, '../..');
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
resolve: {
alias: {
'@': path.resolve(repoRoot, 'src'),
diff --git a/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx b/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx
index 61365fe62ed..c7a394dda98 100644
--- a/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx
@@ -1,63 +1,53 @@
import type { UniformSearchResult } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Avatar, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Avatar, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useState } from 'react';
import { ENGINE_ICON_MAP } from '../../../../../const';
import TitleExtra from './TitleExtra';
-const styles = createStaticStyles(({ css }) => {
- return {
- container: css`
- display: flex;
- flex: 1;
-
- padding: 8px;
- border-radius: 8px;
-
- color: initial;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- desc: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- `,
- displayLink: css`
- color: ${cssVar.colorTextQuaternary};
- `,
- iframe: css`
- border: 1px solid ${cssVar.colorBorder};
- border-radius: 8px;
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-size: 16px;
- color: ${cssVar.colorLink};
- text-overflow: ellipsis;
- `,
- url: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextDescription};
- text-overflow: ellipsis;
- `,
- };
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ flex: '1',
+ padding: '8px',
+ borderRadius: '8px',
+ color: 'initial',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ desc: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '2',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ },
+ iframe: {
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: '8px',
+ },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontSize: '16px',
+ color: cssVar.colorLink,
+ textOverflow: 'ellipsis',
+ },
+ url: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ color: cssVar.colorTextDescription,
+ textOverflow: 'ellipsis',
+ },
});
interface SearchResultProps extends UniformSearchResult {
@@ -70,13 +60,16 @@ const VideoItem = memo<SearchResultProps>(
const videoUrl = iframeSrc || (res as any).iframe_src; // iframe_src is a SearchXNG field, for backward compatibility with old data structure
return (
<Flexbox gap={12}>
- <Flexbox className={styles.container} onClick={() => setExpand(!expand)}>
+ <Flexbox
+ className={stylex.props(styles.container).className}
+ onClick={() => setExpand(!expand)}
+ >
<Flexbox horizontal flex={1} gap={8} padding={12}>
{videoUrl && (
<Flexbox>
<iframe
// alt={title}
- className={styles.iframe}
+ className={stylex.props(styles.iframe).className}
height={100}
src={videoUrl}
width={200}
@@ -106,7 +99,7 @@ const VideoItem = memo<SearchResultProps>(
title: engine,
}))}
/>
- <Flexbox className={styles.title}>{title}</Flexbox>
+ <Flexbox className={stylex.props(styles.title).className}>{title}</Flexbox>
</Flexbox>
<TitleExtra
category={category}
@@ -115,16 +108,16 @@ const VideoItem = memo<SearchResultProps>(
score={score}
/>
</Flexbox>
- <Text className={styles.url} type={'secondary'}>
+ <Text className={stylex.props(styles.url).className} type={'secondary'}>
{url}
</Text>
- <Flexbox className={styles.desc}>{content}</Flexbox>
+ <Flexbox className={stylex.props(styles.desc).className}>{content}</Flexbox>
</Flexbox>
</Flexbox>
</Flexbox>
{expand && videoUrl && (
<Flexbox>
- <iframe className={styles.iframe} height={440} src={videoUrl} width={'100%'} />
+ <iframe {...stylex.props(styles.iframe)} height={440} src={videoUrl} width={'100%'} />
</Flexbox>
)}
</Flexbox>
diff --git a/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx b/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx
index a158bdaf741..368edba8d06 100644
--- a/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx
@@ -1,9 +1,9 @@
import { isDesktop } from '@lobechat/const';
import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import type { UniformSearchResult } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { MouseEvent } from 'react';
import { memo } from 'react';
@@ -13,47 +13,33 @@ import { useGlobalStore } from '@/store/global';
import TitleExtra from './TitleExtra';
import Video from './Video';
-const styles = createStaticStyles(({ css, cssVar }) => {
- return {
- container: css`
- display: flex;
- flex: 1;
-
- padding: 8px;
- border-radius: 8px;
-
- color: initial;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- desc: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- `,
- displayLink: css`
- color: ${cssVar.colorTextQuaternary};
- `,
- title: css`
- font-size: 16px;
- color: ${cssVar.colorLink};
- `,
- url: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextDescription};
- text-overflow: ellipsis;
- `,
- };
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ flex: '1',
+ padding: '8px',
+ borderRadius: '8px',
+ color: 'initial',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ desc: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '2',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ },
+ title: { fontSize: '16px', color: cssVar.colorLink },
+ url: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ color: cssVar.colorTextDescription,
+ textOverflow: 'ellipsis',
+ },
});
interface SearchResultProps extends UniformSearchResult {
@@ -81,7 +67,7 @@ const SearchItem = memo<SearchResultProps>((props) => {
return (
<a
{...(handlesClick ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}
- className={styles.container}
+ {...stylex.props(styles.container)}
href={url!}
rel="noreferrer"
target={'_blank'}
@@ -92,7 +78,7 @@ const SearchItem = memo<SearchResultProps>((props) => {
<Flexbox horizontal align={'center'} distribution={'space-between'}>
<Flexbox horizontal align={'center'} gap={8}>
<WebFavicon title={title} url={url} />
- <Flexbox className={styles.title}>{title}</Flexbox>
+ <Flexbox className={stylex.props(styles.title).className}>{title}</Flexbox>
</Flexbox>
<TitleExtra
category={category}
@@ -101,10 +87,10 @@ const SearchItem = memo<SearchResultProps>((props) => {
score={score}
/>
</Flexbox>
- <Text className={styles.url} type={'secondary'}>
+ <Text className={stylex.props(styles.url).className} type={'secondary'}>
{url}
</Text>
- <Flexbox className={styles.desc}>{content}</Flexbox>
+ <Flexbox className={stylex.props(styles.desc).className}>{content}</Flexbox>
</Flexbox>
</Flexbox>
</a>
diff --git a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx
index d1776418aad..4b565035443 100644
--- a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx
@@ -1,6 +1,6 @@
-import { Block, Flexbox, Icon } from '@lobehub/ui';
-import { Skeleton, Text } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { Block, cx, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { SearchIcon } from 'lucide-react';
import { memo } from 'react';
@@ -9,14 +9,14 @@ import { shinyTextStyles } from '@/styles';
import { EngineAvatarGroup } from '../../../components/EngineAvatar';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- query: css`
- padding-block: 4px;
- padding-inline: 8px;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ query: {
+ paddingBlock: '4px',
+ paddingInline: '8px',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ },
+});
interface SearchBarProps {
defaultEngines: string[];
@@ -41,7 +41,7 @@ const SearchBar = memo<SearchBarProps>(
clickable
horizontal
align={'center'}
- className={styles.query}
+ className={stylex.props(styles.query).className}
gap={8}
variant={'borderless'}
onClick={() => {
diff --git a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx
index 0cf59a89307..fc3a863a2e9 100644
--- a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx
@@ -1,26 +1,23 @@
import { isDesktop } from '@lobechat/const';
import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import type { UniformSearchResult } from '@lobechat/types';
-import { Block, Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import type { CSSProperties, MouseEvent } from 'react';
import { memo } from 'react';
import WebFavicon from '@/components/WebFavicon';
import { useGlobalStore } from '@/store/global';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- cursor: pointer;
-
- height: 100%;
- padding: 8px;
-
- font-size: 12px;
- color: initial;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ cursor: 'pointer',
+ height: '100%',
+ padding: '8px',
+ fontSize: '12px',
+ color: 'initial',
+ },
+});
const SearchResultItem = memo<UniformSearchResult & { style?: CSSProperties }>(
({ url, title, style }) => {
@@ -49,7 +46,7 @@ const SearchResultItem = memo<UniformSearchResult & { style?: CSSProperties }>(
>
<Block
clickable
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={2}
justify={'space-between'}
style={style}
diff --git a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx
index ac348c96510..04a04d5a30e 100644
--- a/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx
@@ -1,6 +1,5 @@
-import { Block, Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import type { CSSProperties } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,14 +9,9 @@ import { useChatStore } from '@/store/chat';
import { WebBrowsingManifest } from '../../../../manifest';
import { EngineAvatarGroup } from '../../../components/EngineAvatar';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- cursor: pointer;
- padding: 8px;
- font-size: 12px;
- color: initial;
- `,
-}));
+const styles = stylex.create({
+ container: { cursor: 'pointer', padding: '8px', fontSize: '12px', color: 'initial' },
+});
interface ShowMoreProps {
engines: string[];
@@ -32,7 +26,7 @@ const ShowMore = memo<ShowMoreProps>(({ style, messageId, engines, resultsNumber
return (
<Block
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={2}
justify={'space-between'}
style={style}
diff --git a/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx b/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
index c73ec4d8f40..7d4da5e7449 100644
--- a/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
@@ -1,7 +1,15 @@
import type { SearchQuery } from '@lobechat/types';
-import { Block, Flexbox, SearchBar as Search, Tooltip } from '@lobehub/ui';
-import { CheckboxGroup, Segmented, Select, Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import {
+ Block,
+ CheckboxGroup,
+ Flexbox,
+ SearchBar as Search,
+ Segmented,
+ Select,
+ Text,
+ Tooltip,
+} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import type { ReactNode } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,12 +22,7 @@ import { CATEGORY_ICON_MAP, ENGINE_ICON_MAP } from '../../const';
import { CategoryAvatar } from './CategoryAvatar';
import { EngineAvatar } from './EngineAvatar';
-const styles = createStaticStyles(({ css }) => ({
- textHeader: css`
- flex: none;
- width: 120px;
- `,
-}));
+const styles = stylex.create({ textHeader: { flex: 'none', width: '120px' } });
interface SearchBarProps {
aiSummary?: boolean;
@@ -117,7 +120,7 @@ const SearchBar = memo<SearchBarProps>(
/>
) : (
<Flexbox horizontal align={'flex-start'} gap={8}>
- <Text className={styles.textHeader} type={'secondary'}>
+ <Text className={stylex.props(styles.textHeader).className} type={'secondary'}>
{t('search.searchEngine.title')}
</Text>
<CheckboxGroup
@@ -166,7 +169,7 @@ const SearchBar = memo<SearchBarProps>(
/>
) : (
<Flexbox horizontal align="flex-start" gap={8}>
- <Text className={styles.textHeader} type={'secondary'}>
+ <Text className={stylex.props(styles.textHeader).className} type={'secondary'}>
{t('search.searchCategory.title')}
</Text>
<CheckboxGroup
@@ -186,7 +189,7 @@ const SearchBar = memo<SearchBarProps>(
)}
<Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>
- <Text className={styles.textHeader} type={'secondary'}>
+ <Text className={stylex.props(styles.textHeader).className} type={'secondary'}>
{t('search.searchTimeRange.title')}
</Text>
<Segmented
diff --git a/packages/builtin-tool-web-browsing/vitest.config.mts b/packages/builtin-tool-web-browsing/vitest.config.mts
index 9e935ef21d1..b9ff9c80646 100644
--- a/packages/builtin-tool-web-browsing/vitest.config.mts
+++ b/packages/builtin-tool-web-browsing/vitest.config.mts
@@ -3,10 +3,13 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
const packageDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(packageDir, '../..');
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
resolve: {
alias: {
'@': path.resolve(repoRoot, 'src'),
diff --git a/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx b/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx
index 1288c9b6591..73e8c8c41c4 100644
--- a/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx
+++ b/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Avatar, Text } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { Avatar, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,74 +17,58 @@ interface SubmitAgentPickState {
summaries?: InstallMarketplaceAgentSummary[];
}
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- display: flex;
- gap: 12px;
- align-items: center;
-
- padding: 12px;
- border: 1px solid ${cssVar.colorFillSecondary};
- border-radius: ${cssVar.borderRadiusLG};
-
- background: ${cssVar.colorBgElevated};
- `,
- cardSkipped: css`
- opacity: 0.65;
- `,
- description: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextSecondary};
- `,
- list: css`
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
- gap: 8px;
- width: 100%;
- `,
- meta: css`
- flex-shrink: 0;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- skippedTag: css`
- flex-shrink: 0;
-
- margin-inline-start: 4px;
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 999px;
-
- font-size: 11px;
- color: ${cssVar.colorTextTertiary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- title: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 0;
-
- font-size: 14px;
- font-weight: 600;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- titleRow: css`
- display: flex;
- gap: 6px;
- align-items: center;
- width: 100%;
- `,
-}));
+const styles = stylex.create({
+ card: {
+ display: 'flex',
+ gap: '12px',
+ alignItems: 'center',
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorFillSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgElevated,
+ backgroundImage: 'none',
+ },
+ cardSkipped: { opacity: 0.65 },
+ description: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '2',
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextSecondary,
+ },
+ list: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
+ gap: '8px',
+ width: '100%',
+ },
+ skippedTag: {
+ flexShrink: 0,
+ marginInlineStart: '4px',
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '999px',
+ fontSize: '11px',
+ color: cssVar.colorTextTertiary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ title: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: '0',
+ fontSize: '14px',
+ fontWeight: 600,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ titleRow: { display: 'flex', gap: '6px', alignItems: 'center', width: '100%' },
+});
export type SubmitAgentPickRenderProps = Pick<
BuiltinRenderProps<SubmitAgentPickArgs, SubmitAgentPickState>,
@@ -107,24 +91,24 @@ const SubmitAgentPick = memo<SubmitAgentPickRenderProps>(({ pluginState }) => {
{skippedCount > 0 &&
` · ${t('agentMarketplace.render.alreadyInLibrary', { count: skippedCount })}`}
</Text>
- <div className={styles.list}>
+ <div {...stylex.props(styles.list)}>
{summaries.map((summary) => (
<div
- className={cx(styles.card, summary.skipped && styles.cardSkipped)}
+ {...stylex.props(styles.card, summary.skipped && styles.cardSkipped)}
key={summary.templateId}
>
<Avatar avatar={summary.avatar || '🤖'} shape="square" size={36} />
<Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
- <div className={styles.titleRow}>
- <span className={styles.title}>{summary.title || summary.templateId}</span>
+ <div {...stylex.props(styles.titleRow)}>
+ <span {...stylex.props(styles.title)}>{summary.title || summary.templateId}</span>
{summary.skipped && (
- <span className={styles.skippedTag}>
+ <span {...stylex.props(styles.skippedTag)}>
{t('agentMarketplace.render.alreadyInLibraryTag')}
</span>
)}
</div>
{summary.description && (
- <div className={styles.description}>{summary.description}</div>
+ <div {...stylex.props(styles.description)}>{summary.description}</div>
)}
</Flexbox>
</div>
diff --git a/packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx b/packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx
index 5c567d37a0f..afa3c35866b 100644
--- a/packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx
+++ b/packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx
@@ -1,19 +1,16 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckCircle2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '@/styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- done: css`
- color: ${cssVar.colorSuccess};
- `,
-}));
+const styles = stylex.create({ done: { color: cssVar.colorSuccess } });
export const FinishOnboardingInspector = memo<
BuiltinInspectorProps<Record<string, never>, Record<string, unknown>>
@@ -26,7 +23,9 @@ export const FinishOnboardingInspector = memo<
<span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>
{t('builtins.lobe-web-onboarding.apiName.finishOnboarding')}
</span>
- {succeeded && <Icon className={styles.done} icon={CheckCircle2} size={14} />}
+ {succeeded && (
+ <Icon className={stylex.props(styles.done).className} icon={CheckCircle2} size={14} />
+ )}
</div>
);
});
diff --git a/packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx b/packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx
index 35822f61968..c46eb59485d 100644
--- a/packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx
+++ b/packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx
@@ -2,69 +2,59 @@
import type { InterestAreaKey } from '@lobechat/const';
import type { BuiltinRenderProps, SaveUserQuestionInput } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- avatar: css`
- display: inline-flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- box-sizing: border-box;
- width: 48px;
- height: 48px;
- border-radius: 16px;
-
- font-size: 28px;
- line-height: 1;
-
- background: ${cssVar.colorFillQuaternary};
- `,
- chip: css`
- display: inline-flex;
- align-items: center;
-
- padding-block: 4px;
- padding-inline: 10px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- detailCard: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
- background: ${cssVar.colorFillTertiary};
- `,
- name: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-size: 16px;
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
- sectionLabel: css`
- font-size: 12px;
- font-weight: 600;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- font-size: 14px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ avatar: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ boxSizing: 'border-box',
+ width: '48px',
+ height: '48px',
+ borderRadius: '16px',
+ fontSize: '28px',
+ lineHeight: 1,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ chip: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ paddingBlock: '4px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ detailCard: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ name: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontSize: '16px',
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+ sectionLabel: { fontSize: '12px', fontWeight: 600, color: cssVar.colorTextSecondary },
+ value: { fontSize: '14px', fontWeight: 500, color: cssVar.colorText },
+});
const SaveUserQuestion = memo<BuiltinRenderProps<SaveUserQuestionInput, unknown, unknown>>(
({ args }) => {
@@ -94,13 +84,13 @@ const SaveUserQuestion = memo<BuiltinRenderProps<SaveUserQuestionInput, unknown,
<Flexbox gap={16}>
{hasAgentIdentity && (
<Flexbox gap={8}>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
{t('builtins.lobe-web-onboarding.render.agent')}
</Text>
- <div className={styles.detailCard}>
+ <div {...stylex.props(styles.detailCard)}>
<Flexbox horizontal align="center" gap={12}>
- <div className={styles.avatar}>{agentEmoji || '🤖'}</div>
- {agentName && <div className={styles.name}>{agentName}</div>}
+ <div {...stylex.props(styles.avatar)}>{agentEmoji || '🤖'}</div>
+ {agentName && <div {...stylex.props(styles.name)}>{agentName}</div>}
</Flexbox>
</div>
</Flexbox>
@@ -108,23 +98,23 @@ const SaveUserQuestion = memo<BuiltinRenderProps<SaveUserQuestionInput, unknown,
{hasUserProfile && (
<Flexbox gap={8}>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
{t('builtins.lobe-web-onboarding.render.fullName')}
</Text>
- <div className={styles.detailCard}>
- <div className={styles.value}>{fullName}</div>
+ <div {...stylex.props(styles.detailCard)}>
+ <div {...stylex.props(styles.value)}>{fullName}</div>
</div>
</Flexbox>
)}
{hasInterests && (
<Flexbox gap={8}>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
{t('builtins.lobe-web-onboarding.render.interests')}
</Text>
<Flexbox horizontal style={{ flexWrap: 'wrap', gap: 8 }}>
{interestLabels.map((label) => (
- <span className={styles.chip} key={label}>
+ <span {...stylex.props(styles.chip)} key={label}>
{label}
</span>
))}
diff --git a/packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx b/packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx
index 82c4ff991e3..555536ab51a 100644
--- a/packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx
+++ b/packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx
@@ -1,85 +1,84 @@
'use client';
import type { MarkdownPatchHunk } from '@lobechat/markdown-patch';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { ReactNode } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- added: css`
- overflow: auto;
-
- max-height: 200px;
- margin: 0;
- padding-block: 6px;
- padding-inline: 10px;
- border-inline-start: 2px solid ${cssVar.colorSuccess};
- border-radius: 0 6px 6px 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorText};
- word-break: break-word;
- white-space: pre-wrap;
-
- background: ${cssVar.colorSuccessBg};
- `,
- block: css`
- display: flex;
- flex-direction: column;
- gap: 6px;
- `,
- count: css`
- flex-shrink: 0;
-
- margin-inline-start: auto;
-
- font-size: 12px;
- font-weight: 400;
- color: ${cssVar.colorTextTertiary};
- `,
- label: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- lineRange: css`
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 11px;
- color: ${cssVar.colorTextTertiary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- removed: css`
- overflow: auto;
-
- max-height: 200px;
- margin: 0;
- padding-block: 6px;
- padding-inline: 10px;
- border-inline-start: 2px solid ${cssVar.colorError};
- border-radius: 0 6px 6px 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextSecondary};
- word-break: break-word;
- white-space: pre-wrap;
-
- background: ${cssVar.colorErrorBg};
- `,
-}));
+const styles = stylex.create({
+ added: {
+ overflow: 'auto',
+ maxHeight: '200px',
+ margin: '0',
+ paddingBlock: '6px',
+ paddingInline: '10px',
+ borderInlineStartWidth: '2px',
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: cssVar.colorSuccess,
+ borderTopLeftRadius: '0',
+ borderTopRightRadius: '6px',
+ borderBottomRightRadius: '6px',
+ borderBottomLeftRadius: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorText,
+ wordBreak: 'break-word',
+ whiteSpace: 'pre-wrap',
+ backgroundColor: cssVar.colorSuccessBg,
+ backgroundImage: 'none',
+ },
+ block: { display: 'flex', flexDirection: 'column', gap: '6px' },
+ count: {
+ flexShrink: 0,
+ marginInlineStart: 'auto',
+ fontSize: '12px',
+ fontWeight: 400,
+ color: cssVar.colorTextTertiary,
+ },
+ label: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ },
+ lineRange: {
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '11px',
+ color: cssVar.colorTextTertiary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ removed: {
+ overflow: 'auto',
+ maxHeight: '200px',
+ margin: '0',
+ paddingBlock: '6px',
+ paddingInline: '10px',
+ borderInlineStartWidth: '2px',
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: cssVar.colorError,
+ borderTopLeftRadius: '0',
+ borderTopRightRadius: '6px',
+ borderBottomRightRadius: '6px',
+ borderBottomLeftRadius: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextSecondary,
+ wordBreak: 'break-word',
+ whiteSpace: 'pre-wrap',
+ backgroundColor: cssVar.colorErrorBg,
+ backgroundImage: 'none',
+ },
+});
interface HunkBlockProps {
countLabel?: string;
@@ -144,23 +143,23 @@ const HunkBlock = memo<HunkBlockProps>(({ countLabel, hunk }) => {
const blocks: ReactNode[] = [];
if (removed)
blocks.push(
- <pre className={styles.removed} key="removed">
+ <pre {...stylex.props(styles.removed)} key="removed">
{removed}
</pre>,
);
if (added)
blocks.push(
- <pre className={styles.added} key="added">
+ <pre {...stylex.props(styles.added)} key="added">
{added}
</pre>,
);
return (
- <div className={styles.block}>
- <div className={styles.label}>
+ <div {...stylex.props(styles.block)}>
+ <div {...stylex.props(styles.label)}>
<span>{t(labelKey)}</span>
- {lineRange && <span className={styles.lineRange}>{lineRange}</span>}
- {countLabel && <span className={styles.count}>{countLabel}</span>}
+ {lineRange && <span {...stylex.props(styles.lineRange)}>{lineRange}</span>}
+ {countLabel && <span {...stylex.props(styles.count)}>{countLabel}</span>}
</div>
{blocks}
</div>
diff --git a/packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx b/packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx
index c44d36f7e75..cdb35fc3dfb 100644
--- a/packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx
+++ b/packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx
@@ -1,42 +1,40 @@
'use client';
import { CopyButton, Flexbox, Markdown, ScrollShadow, TooltipGroup } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileTextIcon } from 'lucide-react';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-inline: 16px;
- font-size: 14px;
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- color: ${cssVar.colorPrimary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingInline: '16px', fontSize: '14px' },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: { color: cssVar.colorPrimary },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
interface DocumentCardProps {
content: string;
@@ -44,17 +42,22 @@ interface DocumentCardProps {
}
const DocumentCard = memo<DocumentCardProps>(({ content, title }) => (
- <Flexbox className={styles.container}>
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
- <FileTextIcon className={styles.icon} size={16} />
+ <Flexbox className={stylex.props(styles.container).className}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.header).className} gap={8}>
+ <FileTextIcon className={stylex.props(styles.icon).className} size={16} />
<Flexbox flex={1}>
- <div className={styles.title}>{title}</div>
+ <div {...stylex.props(styles.title)}>{title}</div>
</Flexbox>
<TooltipGroup>
<CopyButton content={content} size={'small'} />
</TooltipGroup>
</Flexbox>
- <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>
+ <ScrollShadow
+ className={stylex.props(styles.content).className}
+ offset={12}
+ size={12}
+ style={{ maxHeight: 400 }}
+ >
<Markdown style={{ overflow: 'unset', paddingBottom: 16 }} variant={'chat'}>
{content}
</Markdown>
diff --git a/packages/builtin-tool-web-onboarding/vitest.config.mts b/packages/builtin-tool-web-onboarding/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/builtin-tool-web-onboarding/vitest.config.mts
+++ b/packages/builtin-tool-web-onboarding/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/builtin-tools/src/codex/FileChangeInspector.tsx b/packages/builtin-tools/src/codex/FileChangeInspector.tsx
index 276f1cebc17..2c7ddfa6311 100644
--- a/packages/builtin-tools/src/codex/FileChangeInspector.tsx
+++ b/packages/builtin-tools/src/codex/FileChangeInspector.tsx
@@ -3,32 +3,20 @@
import { FilePathDisplay } from '@lobechat/shared-tool-ui/components';
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { type CodexFileChangeArgs, type CodexFileChangeState, getFileChangeStats } from './utils';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- count: css`
- margin-inline-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- lineAdded: css`
- margin-inline-start: 6px;
- font-size: 12px;
- color: ${cssVar.colorSuccess};
- `,
- lineDeleted: css`
- margin-inline-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorError};
- `,
- summary: css`
- margin-inline-end: 6px;
- `,
-}));
+const styles = stylex.create({
+ count: { marginInlineStart: '4px', fontSize: '12px', color: cssVar.colorTextTertiary },
+ lineAdded: { marginInlineStart: '6px', fontSize: '12px', color: cssVar.colorSuccess },
+ lineDeleted: { marginInlineStart: '4px', fontSize: '12px', color: cssVar.colorError },
+ summary: { marginInlineEnd: '6px' },
+});
const FileChangeInspector = memo<BuiltinInspectorProps<CodexFileChangeArgs, CodexFileChangeState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -55,17 +43,17 @@ const FileChangeInspector = memo<BuiltinInspectorProps<CodexFileChangeArgs, Code
<div className={cx(inspectorTextStyles.root, isEditing && shinyTextStyles.shinyText)}>
{stats.firstPath ? (
<>
- <span className={styles.summary}>{summary}:</span>
+ <span {...stylex.props(styles.summary)}>{summary}:</span>
<FilePathDisplay filePath={stats.firstPath} />
</>
) : (
<span>{summary}</span>
)}
- {stats.total > 1 && <span className={styles.count}>+{stats.total - 1}</span>}
+ {stats.total > 1 && <span {...stylex.props(styles.count)}>+{stats.total - 1}</span>}
{hasLineStats && (
<>
- <span className={styles.lineAdded}>+{stats.linesAdded}</span>
- <span className={styles.lineDeleted}>-{stats.linesDeleted}</span>
+ <span {...stylex.props(styles.lineAdded)}>+{stats.linesAdded}</span>
+ <span {...stylex.props(styles.lineDeleted)}>-{stats.linesDeleted}</span>
</>
)}
</div>
diff --git a/packages/builtin-tools/src/codex/FileChangeRender.tsx b/packages/builtin-tools/src/codex/FileChangeRender.tsx
index 67b4f58f21f..06857b94d44 100644
--- a/packages/builtin-tools/src/codex/FileChangeRender.tsx
+++ b/packages/builtin-tools/src/codex/FileChangeRender.tsx
@@ -8,9 +8,9 @@ import {
LineStats,
} from '@lobechat/shared-tool-ui/components';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, PatchDiff } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, PatchDiff, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,50 +22,21 @@ import {
getFileChangeStats,
} from './utils';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- emptyState: css`
- padding: 4px;
- font-size: 13px;
- color: ${cssVar.colorTextTertiary};
- `,
- list: css`
- gap: 2px;
- min-width: 0;
- padding-block: 2px;
- padding-inline: 4px;
- `,
- patch: css`
- overflow: hidden;
- padding-block-end: 8px;
- padding-inline-start: 16px;
- `,
- rowMain: css`
- display: flex;
- flex: 1;
- gap: 10px;
- align-items: center;
-
- min-width: 0;
- `,
- path: css`
- overflow: hidden;
- display: flex;
- align-items: center;
- min-width: 0;
- `,
- row: css`
- gap: 8px;
- align-items: center;
-
- min-height: 26px;
- padding-block: 3px;
- padding-inline: 0;
- `,
- unknownPath: css`
- font-size: 13px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+const styles = stylex.create({
+ emptyState: { padding: '4px', fontSize: '13px', color: cssVar.colorTextTertiary },
+ list: { gap: '2px', minWidth: '0', paddingBlock: '2px', paddingInline: '4px' },
+ patch: { overflow: 'hidden', paddingBlockEnd: '8px', paddingInlineStart: '16px' },
+ rowMain: { display: 'flex', flex: '1', gap: '10px', alignItems: 'center', minWidth: '0' },
+ path: { overflow: 'hidden', display: 'flex', alignItems: 'center', minWidth: '0' },
+ row: {
+ gap: '8px',
+ alignItems: 'center',
+ minHeight: '26px',
+ paddingBlock: '3px',
+ paddingInline: '0',
+ },
+ unknownPath: { fontSize: '13px', color: cssVar.colorTextTertiary },
+});
const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileChangeState>>(
({ args, pluginState }) => {
@@ -75,28 +46,28 @@ const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileC
if (stats.total === 0) {
return (
- <Text className={styles.emptyState}>
+ <Text className={stylex.props(styles.emptyState).className}>
{t('builtins.codex.fileChange.noChanges', { defaultValue: 'No file changes' })}
</Text>
);
}
return (
- <Flexbox className={styles.list}>
+ <Flexbox className={stylex.props(styles.list).className}>
{data.changes.map((change, index) => {
const kind = getFileChangeKind(change.kind);
const path = change.path || '';
return (
<Flexbox key={`${path}-${index}`}>
- <Flexbox horizontal className={styles.row}>
+ <Flexbox horizontal className={stylex.props(styles.row).className}>
<KindDot kind={kind} />
- <div className={styles.rowMain}>
- <div className={styles.path}>
+ <div {...stylex.props(styles.rowMain)}>
+ <div {...stylex.props(styles.path)}>
{path ? (
<FilePathDisplay filePath={path} />
) : (
- <Text className={styles.unknownPath}>
+ <Text className={stylex.props(styles.unknownPath).className}>
{t('builtins.codex.fileChange.unknownFile', {
defaultValue: 'Unknown file',
})}
@@ -107,7 +78,7 @@ const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileC
</div>
</Flexbox>
{change.diffText && (
- <div className={styles.patch}>
+ <div {...stylex.props(styles.patch)}>
<PatchDiff
fileName={getFileName(path)}
language={getFileLanguage(path)}
diff --git a/packages/builtin-tools/src/codex/McpToolRender.tsx b/packages/builtin-tools/src/codex/McpToolRender.tsx
index 34f9d2f33b2..006136c4e3b 100644
--- a/packages/builtin-tools/src/codex/McpToolRender.tsx
+++ b/packages/builtin-tools/src/codex/McpToolRender.tsx
@@ -3,9 +3,9 @@
import { LINEAR_TOOL_NAMES } from '@lobechat/shared-tool-ui/inspectors';
import { GitHubRender, LinearRender } from '@lobechat/shared-tool-ui/renders';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Highlighter } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { ComponentType } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,13 +24,9 @@ import {
getMcpToolName,
} from './mcpToolUtils';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- sectionLabel: css`
- margin-block-end: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ sectionLabel: { marginBlockEnd: '4px', fontSize: '12px', color: cssVar.colorTextSecondary },
+});
const LINEAR_TOOL_NAME_SET = new Set<string>([...LINEAR_TOOL_NAMES, 'fetch', 'search']);
const SharedLinearRender = LinearRender as ComponentType<
@@ -97,7 +93,7 @@ const McpToolRender = memo<BuiltinRenderProps<CodexMcpToolArgs, CodexMcpToolStat
<Flexbox gap={12}>
{input && (
<div>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
{t('builtins.codex.mcpTool.input', { defaultValue: 'Input' })}
</Text>
<Highlighter
@@ -113,7 +109,7 @@ const McpToolRender = memo<BuiltinRenderProps<CodexMcpToolArgs, CodexMcpToolStat
)}
{output && (
<div>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
{t('builtins.codex.mcpTool.result', { defaultValue: 'Result' })}
</Text>
<Highlighter
@@ -129,7 +125,10 @@ const McpToolRender = memo<BuiltinRenderProps<CodexMcpToolArgs, CodexMcpToolStat
)}
{error && (
<div>
- <Text className={styles.sectionLabel} style={{ color: cssVar.colorError }}>
+ <Text
+ className={stylex.props(styles.sectionLabel).className}
+ style={{ color: cssVar.colorError }}
+ >
{t('builtins.codex.mcpTool.error', { defaultValue: 'Error' })}
</Text>
<Highlighter
diff --git a/packages/builtin-tools/src/codex/WebSearchRender.tsx b/packages/builtin-tools/src/codex/WebSearchRender.tsx
index 4346dd69a36..9970315cc49 100644
--- a/packages/builtin-tools/src/codex/WebSearchRender.tsx
+++ b/packages/builtin-tools/src/codex/WebSearchRender.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,90 +14,62 @@ import {
getWebSearchResults,
} from './webSearchUtils';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- output: css`
- overflow: auto;
-
- max-height: 280px;
- margin: 0;
- padding-block: 2px;
- padding-inline: 4px;
-
- font-family: ${cssVar.fontFamily};
- font-size: 13px;
- line-height: 1.55;
- color: ${cssVar.colorTextSecondary};
- white-space: pre-wrap;
- `,
- query: css`
- overflow: hidden;
-
- min-width: 0;
-
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- queryLabel: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextTertiary};
- `,
- queryRow: css`
- gap: 6px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
-
- font-size: 12px;
- `,
- resultItem: css`
- min-width: 0;
- padding-block: 5px;
- padding-inline: 4px;
- border-block-end: 1px solid ${cssVar.colorSplit};
-
- &:last-child {
- border-block-end: 0;
- }
- `,
- resultList: css`
- gap: 0;
- min-width: 0;
- `,
- root: css`
- gap: 4px;
- min-width: 0;
- padding-block: 2px;
- `,
- snippet: css`
- font-size: 12px;
- line-height: 1.45;
- color: ${cssVar.colorTextSecondary};
- `,
- title: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- line-height: 1.45;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- &:hover {
- color: ${cssVar.colorLink};
- }
- `,
- url: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ output: {
+ overflow: 'auto',
+ maxHeight: '280px',
+ margin: '0',
+ paddingBlock: '2px',
+ paddingInline: '4px',
+ fontFamily: cssVar.fontFamily,
+ fontSize: '13px',
+ lineHeight: 1.55,
+ color: cssVar.colorTextSecondary,
+ whiteSpace: 'pre-wrap',
+ },
+ query: {
+ overflow: 'hidden',
+ minWidth: '0',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ queryLabel: { flexShrink: 0, color: cssVar.colorTextTertiary },
+ queryRow: {
+ gap: '6px',
+ alignItems: 'center',
+ paddingBlock: '2px',
+ paddingInline: '4px',
+ fontSize: '12px',
+ },
+ resultItem: {
+ minWidth: '0',
+ paddingBlock: '5px',
+ paddingInline: '4px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'solid', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorSplit,
+ },
+ resultList: { gap: '0', minWidth: '0' },
+ root: { gap: '4px', minWidth: '0', paddingBlock: '2px' },
+ snippet: { fontSize: '12px', lineHeight: 1.45, color: cssVar.colorTextSecondary },
+ title: {
+ overflow: 'hidden',
+ fontSize: '13px',
+ fontWeight: 500,
+ lineHeight: 1.45,
+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorLink },
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ url: {
+ overflow: 'hidden',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
const WebSearchRender = memo<BuiltinRenderProps<CodexWebSearchArgs, CodexWebSearchArgs>>(
({ args, content, pluginState }) => {
@@ -110,23 +82,23 @@ const WebSearchRender = memo<BuiltinRenderProps<CodexWebSearchArgs, CodexWebSear
if (!query && results.length === 0 && !output) return null;
return (
- <Flexbox className={styles.root}>
+ <Flexbox className={stylex.props(styles.root).className}>
{query && (
- <Flexbox horizontal className={styles.queryRow}>
- <span className={styles.queryLabel}>
+ <Flexbox horizontal className={stylex.props(styles.queryRow).className}>
+ <span {...stylex.props(styles.queryLabel)}>
{t('builtins.codex.webSearch.query', { defaultValue: 'Query' })}
</span>
- <span className={styles.query}>{query}</span>
+ <span {...stylex.props(styles.query)}>{query}</span>
</Flexbox>
)}
{results.length > 0 && (
- <Flexbox className={styles.resultList}>
+ <Flexbox className={stylex.props(styles.resultList).className}>
{results.map((result, index) => {
const key = result.url || `${result.title}-${index}`;
- const title = <span className={styles.title}>{result.title}</span>;
+ const title = <span {...stylex.props(styles.title)}>{result.title}</span>;
return (
- <Flexbox className={styles.resultItem} gap={3} key={key}>
+ <Flexbox className={stylex.props(styles.resultItem).className} gap={3} key={key}>
{result.url ? (
<a href={result.url} rel={'noreferrer'} target={'_blank'}>
{title}
@@ -134,14 +106,18 @@ const WebSearchRender = memo<BuiltinRenderProps<CodexWebSearchArgs, CodexWebSear
) : (
title
)}
- {result.url && <Text className={styles.url}>{result.url}</Text>}
- {result.snippet && <Text className={styles.snippet}>{result.snippet}</Text>}
+ {result.url && (
+ <Text className={stylex.props(styles.url).className}>{result.url}</Text>
+ )}
+ {result.snippet && (
+ <Text className={stylex.props(styles.snippet).className}>{result.snippet}</Text>
+ )}
</Flexbox>
);
})}
</Flexbox>
)}
- {output && <pre className={styles.output}>{output}</pre>}
+ {output && <pre {...stylex.props(styles.output)}>{output}</pre>}
</Flexbox>
);
},
diff --git a/packages/builtin-tools/src/github/RunCommandRender.tsx b/packages/builtin-tools/src/github/RunCommandRender.tsx
index 9126bca7187..0e02c8b2d85 100644
--- a/packages/builtin-tools/src/github/RunCommandRender.tsx
+++ b/packages/builtin-tools/src/github/RunCommandRender.tsx
@@ -1,9 +1,9 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Highlighter } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useMemo } from 'react';
import {
@@ -14,24 +14,12 @@ import {
tryParseJson,
} from './utils';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- exitCode: css`
- margin-inline-start: 8px;
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- `,
- exitCodeError: css`
- color: ${cssVar.colorError};
- `,
- exitCodeSuccess: css`
- color: ${cssVar.colorSuccess};
- `,
- sectionLabel: css`
- margin-block-end: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ exitCode: { marginInlineStart: '8px', fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },
+ exitCodeError: { color: cssVar.colorError },
+ exitCodeSuccess: { color: cssVar.colorSuccess },
+ sectionLabel: { marginBlockEnd: '4px', fontSize: '12px', color: cssVar.colorTextSecondary },
+});
const GithubRunCommandRender = memo<
BuiltinRenderProps<GithubRunCommandArgs, GithubRunCommandState>
@@ -58,12 +46,12 @@ const GithubRunCommandRender = memo<
<Flexbox gap={12}>
{normalized && (
<div>
- <Text className={styles.sectionLabel}>
+ <Text className={stylex.props(styles.sectionLabel).className}>
Command
{success !== undefined && (
<span
- className={`${styles.exitCode} ${
- success ? styles.exitCodeSuccess : styles.exitCodeError
+ className={`${stylex.props(styles.exitCode).className} ${
+ stylex.props(success ? styles.exitCodeSuccess : styles.exitCodeError).className
}`}
>
exit {exitCode ?? (success ? 0 : 1)}
@@ -83,7 +71,7 @@ const GithubRunCommandRender = memo<
)}
{outputBody && (
<div>
- <Text className={styles.sectionLabel}>Output</Text>
+ <Text className={stylex.props(styles.sectionLabel).className}>Output</Text>
<Highlighter
wrap
language={outputLanguage}
@@ -97,7 +85,10 @@ const GithubRunCommandRender = memo<
)}
{stderr && (
<div>
- <Text className={styles.sectionLabel} style={{ color: cssVar.colorError }}>
+ <Text
+ className={stylex.props(styles.sectionLabel).className}
+ style={{ color: cssVar.colorError }}
+ >
Stderr
</Text>
<Highlighter
diff --git a/packages/builtin-tools/src/notebook/DocumentCard.tsx b/packages/builtin-tools/src/notebook/DocumentCard.tsx
index d35c401149d..35eec8c7fe2 100644
--- a/packages/builtin-tools/src/notebook/DocumentCard.tsx
+++ b/packages/builtin-tools/src/notebook/DocumentCard.tsx
@@ -1,8 +1,16 @@
'use client';
-import { CopyButton, Flexbox, Markdown, ScrollShadow, TooltipGroup } from '@lobehub/ui';
-import { ActionIcon, Button } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ CopyButton,
+ Flexbox,
+ Markdown,
+ ScrollShadow,
+ TooltipGroup,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Maximize2, Minimize2, NotebookText, PencilLine } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,48 +20,43 @@ import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
import type { NotebookDocument } from './types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- position: relative;
-
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 16px;
-
- background: ${cssVar.colorBgContainer};
- `,
- content: css`
- padding-inline: 16px;
- font-size: 14px;
- `,
- expandButton: css`
- position: absolute;
- inset-block-end: 16px;
- inset-inline-start: 50%;
- transform: translateX(-50%);
-
- box-shadow: ${cssVar.boxShadow};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- color: ${cssVar.colorPrimary};
- `,
- title: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ position: 'relative',
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '16px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ content: { paddingInline: '16px', fontSize: '14px' },
+ expandButton: {
+ position: 'absolute',
+ insetBlockEnd: '16px',
+ insetInlineStart: '50%',
+ transform: 'translateX(-50%)',
+ boxShadow: cssVar.boxShadow,
+ },
+ header: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: { color: cssVar.colorPrimary },
+ title: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: '1',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
interface DocumentCardProps {
document: NotebookDocument;
@@ -78,12 +81,17 @@ const DocumentCard = memo<DocumentCardProps>(({ document }) => {
};
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
{/* Header */}
- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
- <NotebookText className={styles.icon} size={16} />
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ gap={8}
+ >
+ <NotebookText className={stylex.props(styles.icon).className} size={16} />
<Flexbox flex={1}>
- <div className={styles.title}>{document.title}</div>
+ <div {...stylex.props(styles.title)}>{document.title}</div>
</Flexbox>
<TooltipGroup>
<Flexbox horizontal gap={4}>
@@ -102,7 +110,12 @@ const DocumentCard = memo<DocumentCardProps>(({ document }) => {
</TooltipGroup>
</Flexbox>
{/* Content */}
- <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>
+ <ScrollShadow
+ className={stylex.props(styles.content).className}
+ offset={12}
+ size={12}
+ style={{ maxHeight: 400 }}
+ >
<Markdown style={{ overflow: 'unset', paddingBottom: 40 }} variant={'chat'}>
{document.content}
</Markdown>
@@ -110,7 +123,7 @@ const DocumentCard = memo<DocumentCardProps>(({ document }) => {
{/* Floating expand/collapse button */}
<Button
- className={styles.expandButton}
+ className={stylex.props(styles.expandButton).className}
icon={isExpanded ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
shape={'round'}
type={'default'}
diff --git a/packages/builtin-tools/vitest.config.mts b/packages/builtin-tools/vitest.config.mts
index b618dfb336c..3f98855ccd0 100644
--- a/packages/builtin-tools/vitest.config.mts
+++ b/packages/builtin-tools/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
server: {
diff --git a/packages/database/migrations/meta/0202_snapshot.json b/packages/database/migrations/meta/0202_snapshot.json
index dc6ba4d25c2..ece253eda4a 100644
--- a/packages/database/migrations/meta/0202_snapshot.json
+++ b/packages/database/migrations/meta/0202_snapshot.json
@@ -1,8 +1,28 @@
{
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ },
+ "dialect": "postgresql",
+ "enums": {},
"id": "285ec8a4-45bc-409c-adfc-993edac7a4f8",
+ "policies": {},
"prevId": "e8a1f357-1bc4-496e-a22d-946c48f501f6",
- "version": "7",
- "dialect": "postgresql",
+ "roles": {},
+ "schemas": {},
+ "sequences": {
+ "public.fts_search_sync_revision_seq": {
+ "name": "fts_search_sync_revision_seq",
+ "schema": "public",
+ "increment": "1",
+ "startWith": "1",
+ "minValue": "1",
+ "maxValue": "9223372036854775807",
+ "cache": "1",
+ "cycle": false
+ }
+ },
"tables": {
"public.acceptance_comments": {
"name": "acceptance_comments",
@@ -287,12 +307,8 @@
"name": "acceptance_comments_acceptance_id_acceptances_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "acceptances",
- "columnsFrom": [
- "acceptance_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -300,12 +316,8 @@
"name": "acceptance_comments_author_user_id_users_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "users",
- "columnsFrom": [
- "author_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -313,12 +325,8 @@
"name": "acceptance_comments_author_agent_id_agents_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "agents",
- "columnsFrom": [
- "author_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -326,12 +334,8 @@
"name": "acceptance_comments_workspace_id_workspaces_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -339,12 +343,8 @@
"name": "acceptance_comments_parent_comment_id_acceptance_comments_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "acceptance_comments",
- "columnsFrom": [
- "parent_comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_comment_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -352,12 +352,8 @@
"name": "acceptance_comments_context_run_id_verify_runs_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "verify_runs",
- "columnsFrom": [
- "context_run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["context_run_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -365,12 +361,8 @@
"name": "acceptance_comments_evidence_id_verify_evidence_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "verify_evidence",
- "columnsFrom": [
- "evidence_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["evidence_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -378,12 +370,8 @@
"name": "acceptance_comments_resolved_by_user_id_users_id_fk",
"tableFrom": "acceptance_comments",
"tableTo": "users",
- "columnsFrom": [
- "resolved_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["resolved_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -492,12 +480,8 @@
"name": "acceptance_flow_edges_flow_id_acceptance_flows_id_fk",
"tableFrom": "acceptance_flow_edges",
"tableTo": "acceptance_flows",
- "columnsFrom": [
- "flow_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["flow_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -505,14 +489,8 @@
"name": "acceptance_flow_edges_flow_id_source_node_id_acceptance_flow_nodes_flow_id_id_fk",
"tableFrom": "acceptance_flow_edges",
"tableTo": "acceptance_flow_nodes",
- "columnsFrom": [
- "flow_id",
- "source_node_id"
- ],
- "columnsTo": [
- "flow_id",
- "id"
- ],
+ "columnsFrom": ["flow_id", "source_node_id"],
+ "columnsTo": ["flow_id", "id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -520,14 +498,8 @@
"name": "acceptance_flow_edges_flow_id_target_node_id_acceptance_flow_nodes_flow_id_id_fk",
"tableFrom": "acceptance_flow_edges",
"tableTo": "acceptance_flow_nodes",
- "columnsFrom": [
- "flow_id",
- "target_node_id"
- ],
- "columnsTo": [
- "flow_id",
- "id"
- ],
+ "columnsFrom": ["flow_id", "target_node_id"],
+ "columnsTo": ["flow_id", "id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -655,12 +627,8 @@
"name": "acceptance_flow_nodes_flow_id_acceptance_flows_id_fk",
"tableFrom": "acceptance_flow_nodes",
"tableTo": "acceptance_flows",
- "columnsFrom": [
- "flow_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["flow_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -668,12 +636,8 @@
"name": "acceptance_flow_nodes_criterion_id_verify_criteria_id_fk",
"tableFrom": "acceptance_flow_nodes",
"tableTo": "verify_criteria",
- "columnsFrom": [
- "criterion_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["criterion_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -681,12 +645,8 @@
"name": "acceptance_flow_nodes_sub_flow_id_acceptance_flows_id_fk",
"tableFrom": "acceptance_flow_nodes",
"tableTo": "acceptance_flows",
- "columnsFrom": [
- "sub_flow_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["sub_flow_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -769,12 +729,8 @@
"name": "acceptance_flows_acceptance_id_acceptances_id_fk",
"tableFrom": "acceptance_flows",
"tableTo": "acceptances",
- "columnsFrom": [
- "acceptance_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -1203,12 +1159,8 @@
"name": "agents_user_id_users_id_fk",
"tableFrom": "agents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1216,12 +1168,8 @@
"name": "agents_workspace_id_workspaces_id_fk",
"tableFrom": "agents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1229,12 +1177,8 @@
"name": "agents_session_group_id_session_groups_id_fk",
"tableFrom": "agents",
"tableTo": "session_groups",
- "columnsFrom": [
- "session_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["session_group_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -1369,12 +1313,8 @@
"name": "agents_files_file_id_files_id_fk",
"tableFrom": "agents_files",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1382,12 +1322,8 @@
"name": "agents_files_agent_id_agents_id_fk",
"tableFrom": "agents_files",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1395,12 +1331,8 @@
"name": "agents_files_user_id_users_id_fk",
"tableFrom": "agents_files",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1408,12 +1340,8 @@
"name": "agents_files_workspace_id_workspaces_id_fk",
"tableFrom": "agents_files",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -1421,11 +1349,7 @@
"compositePrimaryKeys": {
"agents_files_file_id_agent_id_user_id_pk": {
"name": "agents_files_file_id_agent_id_user_id_pk",
- "columns": [
- "file_id",
- "agent_id",
- "user_id"
- ]
+ "columns": ["file_id", "agent_id", "user_id"]
}
},
"uniqueConstraints": {},
@@ -1557,12 +1481,8 @@
"name": "agents_knowledge_bases_agent_id_agents_id_fk",
"tableFrom": "agents_knowledge_bases",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1570,12 +1490,8 @@
"name": "agents_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "agents_knowledge_bases",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1583,12 +1499,8 @@
"name": "agents_knowledge_bases_user_id_users_id_fk",
"tableFrom": "agents_knowledge_bases",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1596,12 +1508,8 @@
"name": "agents_knowledge_bases_workspace_id_workspaces_id_fk",
"tableFrom": "agents_knowledge_bases",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -1609,10 +1517,7 @@
"compositePrimaryKeys": {
"agents_knowledge_bases_agent_id_knowledge_base_id_pk": {
"name": "agents_knowledge_bases_agent_id_knowledge_base_id_pk",
- "columns": [
- "agent_id",
- "knowledge_base_id"
- ]
+ "columns": ["agent_id", "knowledge_base_id"]
}
},
"uniqueConstraints": {},
@@ -1841,12 +1746,8 @@
"name": "agent_accounts_agent_id_agents_id_fk",
"tableFrom": "agent_accounts",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1854,12 +1755,8 @@
"name": "agent_accounts_user_id_users_id_fk",
"tableFrom": "agent_accounts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -1867,12 +1764,8 @@
"name": "agent_accounts_workspace_id_workspaces_id_fk",
"tableFrom": "agent_accounts",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -2054,12 +1947,8 @@
"name": "agent_bot_providers_agent_id_agents_id_fk",
"tableFrom": "agent_bot_providers",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2067,12 +1956,8 @@
"name": "agent_bot_providers_user_id_users_id_fk",
"tableFrom": "agent_bot_providers",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2080,12 +1965,8 @@
"name": "agent_bot_providers_workspace_id_workspaces_id_fk",
"tableFrom": "agent_bot_providers",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -2351,12 +2232,8 @@
"name": "agent_cron_jobs_agent_id_agents_id_fk",
"tableFrom": "agent_cron_jobs",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2364,12 +2241,8 @@
"name": "agent_cron_jobs_group_id_chat_groups_id_fk",
"tableFrom": "agent_cron_jobs",
"tableTo": "chat_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2377,12 +2250,8 @@
"name": "agent_cron_jobs_user_id_users_id_fk",
"tableFrom": "agent_cron_jobs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2390,12 +2259,8 @@
"name": "agent_cron_jobs_workspace_id_workspaces_id_fk",
"tableFrom": "agent_cron_jobs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -2833,12 +2698,8 @@
"name": "agent_documents_user_id_users_id_fk",
"tableFrom": "agent_documents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2846,12 +2707,8 @@
"name": "agent_documents_workspace_id_workspaces_id_fk",
"tableFrom": "agent_documents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2859,12 +2716,8 @@
"name": "agent_documents_agent_id_agents_id_fk",
"tableFrom": "agent_documents",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2872,12 +2725,8 @@
"name": "agent_documents_document_id_documents_id_fk",
"tableFrom": "agent_documents",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -2885,12 +2734,8 @@
"name": "agent_documents_deleted_by_user_id_users_id_fk",
"tableFrom": "agent_documents",
"tableTo": "users",
- "columnsFrom": [
- "deleted_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["deleted_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -2898,12 +2743,8 @@
"name": "agent_documents_deleted_by_agent_id_agents_id_fk",
"tableFrom": "agent_documents",
"tableTo": "agents",
- "columnsFrom": [
- "deleted_by_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["deleted_by_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -3097,12 +2938,8 @@
"name": "agent_eval_benchmarks_user_id_users_id_fk",
"tableFrom": "agent_eval_benchmarks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3110,12 +2947,8 @@
"name": "agent_eval_benchmarks_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_benchmarks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -3329,12 +3162,8 @@
"name": "agent_eval_datasets_benchmark_id_agent_eval_benchmarks_id_fk",
"tableFrom": "agent_eval_datasets",
"tableTo": "agent_eval_benchmarks",
- "columnsFrom": [
- "benchmark_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["benchmark_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3342,12 +3171,8 @@
"name": "agent_eval_datasets_source_experiment_id_agent_eval_experiments_id_fk",
"tableFrom": "agent_eval_datasets",
"tableTo": "agent_eval_experiments",
- "columnsFrom": [
- "source_experiment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_experiment_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -3355,12 +3180,8 @@
"name": "agent_eval_datasets_user_id_users_id_fk",
"tableFrom": "agent_eval_datasets",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3368,12 +3189,8 @@
"name": "agent_eval_datasets_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_datasets",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -3472,12 +3289,8 @@
"name": "agent_eval_experiment_benchmarks_experiment_id_agent_eval_experiments_id_fk",
"tableFrom": "agent_eval_experiment_benchmarks",
"tableTo": "agent_eval_experiments",
- "columnsFrom": [
- "experiment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["experiment_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3485,12 +3298,8 @@
"name": "agent_eval_experiment_benchmarks_benchmark_id_agent_eval_benchmarks_id_fk",
"tableFrom": "agent_eval_experiment_benchmarks",
"tableTo": "agent_eval_benchmarks",
- "columnsFrom": [
- "benchmark_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["benchmark_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3498,12 +3307,8 @@
"name": "agent_eval_experiment_benchmarks_user_id_users_id_fk",
"tableFrom": "agent_eval_experiment_benchmarks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3511,12 +3316,8 @@
"name": "agent_eval_experiment_benchmarks_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_experiment_benchmarks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -3524,10 +3325,7 @@
"compositePrimaryKeys": {
"agent_eval_experiment_benchmarks_experiment_id_benchmark_id_pk": {
"name": "agent_eval_experiment_benchmarks_experiment_id_benchmark_id_pk",
- "columns": [
- "experiment_id",
- "benchmark_id"
- ]
+ "columns": ["experiment_id", "benchmark_id"]
}
},
"uniqueConstraints": {},
@@ -3634,12 +3432,8 @@
"name": "agent_eval_experiments_user_id_users_id_fk",
"tableFrom": "agent_eval_experiments",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3647,12 +3441,8 @@
"name": "agent_eval_experiments_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_experiments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -3796,12 +3586,8 @@
"name": "agent_eval_run_topics_user_id_users_id_fk",
"tableFrom": "agent_eval_run_topics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3809,12 +3595,8 @@
"name": "agent_eval_run_topics_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_run_topics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3822,12 +3604,8 @@
"name": "agent_eval_run_topics_run_id_agent_eval_runs_id_fk",
"tableFrom": "agent_eval_run_topics",
"tableTo": "agent_eval_runs",
- "columnsFrom": [
- "run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["run_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3835,12 +3613,8 @@
"name": "agent_eval_run_topics_topic_id_topics_id_fk",
"tableFrom": "agent_eval_run_topics",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -3848,12 +3622,8 @@
"name": "agent_eval_run_topics_test_case_id_agent_eval_test_cases_id_fk",
"tableFrom": "agent_eval_run_topics",
"tableTo": "agent_eval_test_cases",
- "columnsFrom": [
- "test_case_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["test_case_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -3861,10 +3631,7 @@
"compositePrimaryKeys": {
"agent_eval_run_topics_run_id_topic_id_pk": {
"name": "agent_eval_run_topics_run_id_topic_id_pk",
- "columns": [
- "run_id",
- "topic_id"
- ]
+ "columns": ["run_id", "topic_id"]
}
},
"uniqueConstraints": {},
@@ -4083,12 +3850,8 @@
"name": "agent_eval_runs_dataset_id_agent_eval_datasets_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "agent_eval_datasets",
- "columnsFrom": [
- "dataset_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4096,12 +3859,8 @@
"name": "agent_eval_runs_experiment_id_agent_eval_experiments_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "agent_eval_experiments",
- "columnsFrom": [
- "experiment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["experiment_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -4109,12 +3868,8 @@
"name": "agent_eval_runs_target_agent_id_agents_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "agents",
- "columnsFrom": [
- "target_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["target_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4122,12 +3877,8 @@
"name": "agent_eval_runs_user_id_users_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4135,12 +3886,8 @@
"name": "agent_eval_runs_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4148,12 +3895,8 @@
"name": "agent_eval_runs_parent_run_id_agent_eval_runs_id_fk",
"tableFrom": "agent_eval_runs",
"tableTo": "agent_eval_runs",
- "columnsFrom": [
- "parent_run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_run_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -4311,12 +4054,8 @@
"name": "agent_eval_test_cases_user_id_users_id_fk",
"tableFrom": "agent_eval_test_cases",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4324,12 +4063,8 @@
"name": "agent_eval_test_cases_workspace_id_workspaces_id_fk",
"tableFrom": "agent_eval_test_cases",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4337,12 +4072,8 @@
"name": "agent_eval_test_cases_dataset_id_agent_eval_datasets_id_fk",
"tableFrom": "agent_eval_test_cases",
"tableTo": "agent_eval_datasets",
- "columnsFrom": [
- "dataset_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -4420,12 +4151,8 @@
"name": "agent_history_job_agents_job_id_agent_history_jobs_id_fk",
"tableFrom": "agent_history_job_agents",
"tableTo": "agent_history_jobs",
- "columnsFrom": [
- "job_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4433,12 +4160,8 @@
"name": "agent_history_job_agents_agent_id_agents_id_fk",
"tableFrom": "agent_history_job_agents",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -4516,12 +4239,8 @@
"name": "agent_history_job_groups_job_id_agent_history_jobs_id_fk",
"tableFrom": "agent_history_job_groups",
"tableTo": "agent_history_jobs",
- "columnsFrom": [
- "job_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4529,12 +4248,8 @@
"name": "agent_history_job_groups_group_id_chat_groups_id_fk",
"tableFrom": "agent_history_job_groups",
"tableTo": "chat_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -4658,12 +4373,8 @@
"name": "agent_history_job_topics_job_id_agent_history_jobs_id_fk",
"tableFrom": "agent_history_job_topics",
"tableTo": "agent_history_jobs",
- "columnsFrom": [
- "job_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -4671,12 +4382,8 @@
"name": "agent_history_job_topics_topic_id_topics_id_fk",
"tableFrom": "agent_history_job_topics",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -5163,12 +4870,8 @@
"name": "agent_inbox_messages_agent_id_agents_id_fk",
"tableFrom": "agent_inbox_messages",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5176,12 +4879,8 @@
"name": "agent_inbox_messages_user_id_users_id_fk",
"tableFrom": "agent_inbox_messages",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5189,12 +4888,8 @@
"name": "agent_inbox_messages_workspace_id_workspaces_id_fk",
"tableFrom": "agent_inbox_messages",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5202,12 +4897,8 @@
"name": "agent_inbox_messages_account_id_agent_accounts_id_fk",
"tableFrom": "agent_inbox_messages",
"tableTo": "agent_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5215,12 +4906,8 @@
"name": "agent_inbox_messages_topic_id_topics_id_fk",
"tableFrom": "agent_inbox_messages",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -5534,12 +5221,8 @@
"name": "agent_intervention_resolutions_operation_id_agent_operations_id_fk",
"tableFrom": "agent_intervention_resolutions",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5547,12 +5230,8 @@
"name": "agent_intervention_resolutions_user_id_users_id_fk",
"tableFrom": "agent_intervention_resolutions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -5560,12 +5239,8 @@
"name": "agent_intervention_resolutions_workspace_id_workspaces_id_fk",
"tableFrom": "agent_intervention_resolutions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -6029,12 +5704,8 @@
"name": "agent_interventions_operation_id_agent_operations_id_fk",
"tableFrom": "agent_interventions",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6042,12 +5713,8 @@
"name": "agent_interventions_user_id_users_id_fk",
"tableFrom": "agent_interventions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6055,12 +5722,8 @@
"name": "agent_interventions_workspace_id_workspaces_id_fk",
"tableFrom": "agent_interventions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6068,12 +5731,8 @@
"name": "agent_interventions_resolution_id_agent_intervention_resolutions_id_fk",
"tableFrom": "agent_interventions",
"tableTo": "agent_intervention_resolutions",
- "columnsFrom": [
- "resolution_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["resolution_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -6235,12 +5894,8 @@
"name": "agent_label_assignments_label_id_agent_labels_id_fk",
"tableFrom": "agent_label_assignments",
"tableTo": "agent_labels",
- "columnsFrom": [
- "label_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["label_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6248,12 +5903,8 @@
"name": "agent_label_assignments_agent_id_agents_id_fk",
"tableFrom": "agent_label_assignments",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6261,12 +5912,8 @@
"name": "agent_label_assignments_user_id_users_id_fk",
"tableFrom": "agent_label_assignments",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6274,12 +5921,8 @@
"name": "agent_label_assignments_workspace_id_workspaces_id_fk",
"tableFrom": "agent_label_assignments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -6441,12 +6084,8 @@
"name": "agent_labels_user_id_users_id_fk",
"tableFrom": "agent_labels",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6454,12 +6093,8 @@
"name": "agent_labels_workspace_id_workspaces_id_fk",
"tableFrom": "agent_labels",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -6742,12 +6377,8 @@
"name": "agent_mails_agent_id_agents_id_fk",
"tableFrom": "agent_mails",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6755,12 +6386,8 @@
"name": "agent_mails_user_id_users_id_fk",
"tableFrom": "agent_mails",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6768,12 +6395,8 @@
"name": "agent_mails_workspace_id_workspaces_id_fk",
"tableFrom": "agent_mails",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6781,12 +6404,8 @@
"name": "agent_mails_account_id_agent_accounts_id_fk",
"tableFrom": "agent_mails",
"tableTo": "agent_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -6794,12 +6413,8 @@
"name": "agent_mails_signal_id_signals_id_fk",
"tableFrom": "agent_mails",
"tableTo": "signals",
- "columnsFrom": [
- "signal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["signal_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -7262,12 +6877,8 @@
"name": "agent_operations_workspace_id_workspaces_id_fk",
"tableFrom": "agent_operations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7275,12 +6886,8 @@
"name": "agent_operations_agent_id_agents_id_fk",
"tableFrom": "agent_operations",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -7288,12 +6895,8 @@
"name": "agent_operations_topic_id_topics_id_fk",
"tableFrom": "agent_operations",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -7301,12 +6904,8 @@
"name": "agent_operations_thread_id_threads_id_fk",
"tableFrom": "agent_operations",
"tableTo": "threads",
- "columnsFrom": [
- "thread_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -7314,12 +6913,8 @@
"name": "agent_operations_task_id_tasks_id_fk",
"tableFrom": "agent_operations",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -7327,12 +6922,8 @@
"name": "agent_operations_chat_group_id_chat_groups_id_fk",
"tableFrom": "agent_operations",
"tableTo": "chat_groups",
- "columnsFrom": [
- "chat_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -7532,12 +7123,8 @@
"name": "agent_account_bindings_agent_id_agents_id_fk",
"tableFrom": "agent_account_bindings",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7545,12 +7132,8 @@
"name": "agent_account_bindings_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_account_bindings",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7558,12 +7141,8 @@
"name": "agent_account_bindings_user_id_users_id_fk",
"tableFrom": "agent_account_bindings",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7571,12 +7150,8 @@
"name": "agent_account_bindings_workspace_id_workspaces_id_fk",
"tableFrom": "agent_account_bindings",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -7744,12 +7319,8 @@
"name": "agent_device_account_bindings_agent_id_agents_id_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7757,12 +7328,8 @@
"name": "agent_device_account_bindings_user_id_users_id_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7770,12 +7337,8 @@
"name": "agent_device_account_bindings_workspace_id_workspaces_id_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7783,12 +7346,8 @@
"name": "agent_device_account_bindings_device_id_devices_id_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "devices",
- "columnsFrom": [
- "device_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7796,12 +7355,8 @@
"name": "agent_device_account_bindings_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7809,14 +7364,8 @@
"name": "agent_device_account_bindings_login_fk",
"tableFrom": "agent_device_account_bindings",
"tableTo": "agent_provider_account_logins",
- "columnsFrom": [
- "account_id",
- "device_id"
- ],
- "columnsTo": [
- "account_id",
- "device_id"
- ],
+ "columnsFrom": ["account_id", "device_id"],
+ "columnsTo": ["account_id", "device_id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -7950,12 +7499,8 @@
"name": "agent_provider_account_logins_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_provider_account_logins",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7963,12 +7508,8 @@
"name": "agent_provider_account_logins_device_id_devices_id_fk",
"tableFrom": "agent_provider_account_logins",
"tableTo": "devices",
- "columnsFrom": [
- "device_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7976,12 +7517,8 @@
"name": "agent_provider_account_logins_user_id_users_id_fk",
"tableFrom": "agent_provider_account_logins",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -7989,12 +7526,8 @@
"name": "agent_provider_account_logins_workspace_id_workspaces_id_fk",
"tableFrom": "agent_provider_account_logins",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -8004,10 +7537,7 @@
"agent_provider_account_logins_account_device_unique": {
"name": "agent_provider_account_logins_account_device_unique",
"nullsNotDistinct": false,
- "columns": [
- "account_id",
- "device_id"
- ]
+ "columns": ["account_id", "device_id"]
}
},
"policies": {},
@@ -8300,12 +7830,8 @@
"name": "agent_provider_accounts_user_id_users_id_fk",
"tableFrom": "agent_provider_accounts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8313,12 +7839,8 @@
"name": "agent_provider_accounts_workspace_id_workspaces_id_fk",
"tableFrom": "agent_provider_accounts",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -8504,12 +8026,8 @@
"name": "agent_quota_calibrations_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_quota_calibrations",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8517,12 +8035,8 @@
"name": "agent_quota_calibrations_user_id_users_id_fk",
"tableFrom": "agent_quota_calibrations",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8530,12 +8044,8 @@
"name": "agent_quota_calibrations_workspace_id_workspaces_id_fk",
"tableFrom": "agent_quota_calibrations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -8745,12 +8255,8 @@
"name": "agent_quota_snapshots_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_quota_snapshots",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8758,12 +8264,8 @@
"name": "agent_quota_snapshots_user_id_users_id_fk",
"tableFrom": "agent_quota_snapshots",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8771,12 +8273,8 @@
"name": "agent_quota_snapshots_workspace_id_workspaces_id_fk",
"tableFrom": "agent_quota_snapshots",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -8784,12 +8282,8 @@
"name": "agent_quota_snapshots_device_id_devices_id_fk",
"tableFrom": "agent_quota_snapshots",
"tableTo": "devices",
- "columnsFrom": [
- "device_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -9064,12 +8558,8 @@
"name": "agent_quota_usage_ledger_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -9077,12 +8567,8 @@
"name": "agent_quota_usage_ledger_user_id_users_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -9090,12 +8576,8 @@
"name": "agent_quota_usage_ledger_workspace_id_workspaces_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -9103,12 +8585,8 @@
"name": "agent_quota_usage_ledger_message_id_messages_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -9116,12 +8594,8 @@
"name": "agent_quota_usage_ledger_operation_id_agent_operations_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -9129,12 +8603,8 @@
"name": "agent_quota_usage_ledger_topic_id_topics_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -9142,12 +8612,8 @@
"name": "agent_quota_usage_ledger_agent_id_agents_id_fk",
"tableFrom": "agent_quota_usage_ledger",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -9387,12 +8853,8 @@
"name": "agent_quota_windows_account_id_agent_provider_accounts_id_fk",
"tableFrom": "agent_quota_windows",
"tableTo": "agent_provider_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -9400,12 +8862,8 @@
"name": "agent_quota_windows_user_id_users_id_fk",
"tableFrom": "agent_quota_windows",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -9413,12 +8871,8 @@
"name": "agent_quota_windows_workspace_id_workspaces_id_fk",
"tableFrom": "agent_quota_windows",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -9525,12 +8979,8 @@
"name": "agent_shares_agent_id_agents_id_fk",
"tableFrom": "agent_shares",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -9779,12 +9229,8 @@
"name": "agent_skills_zip_file_hash_global_files_hash_id_fk",
"tableFrom": "agent_skills",
"tableTo": "global_files",
- "columnsFrom": [
- "zip_file_hash"
- ],
- "columnsTo": [
- "hash_id"
- ],
+ "columnsFrom": ["zip_file_hash"],
+ "columnsTo": ["hash_id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -9792,12 +9238,8 @@
"name": "agent_skills_user_id_users_id_fk",
"tableFrom": "agent_skills",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -9805,12 +9247,8 @@
"name": "agent_skills_workspace_id_workspaces_id_fk",
"tableFrom": "agent_skills",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10065,12 +9503,8 @@
"name": "ai_models_user_id_users_id_fk",
"tableFrom": "ai_models",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -10078,12 +9512,8 @@
"name": "ai_models_workspace_id_workspaces_id_fk",
"tableFrom": "ai_models",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10298,12 +9728,8 @@
"name": "ai_providers_user_id_users_id_fk",
"tableFrom": "ai_providers",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -10311,12 +9737,8 @@
"name": "ai_providers_workspace_id_workspaces_id_fk",
"tableFrom": "ai_providers",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10451,12 +9873,8 @@
"name": "api_keys_user_id_users_id_fk",
"tableFrom": "api_keys",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -10464,12 +9882,8 @@
"name": "api_keys_workspace_id_workspaces_id_fk",
"tableFrom": "api_keys",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10479,16 +9893,12 @@
"api_keys_key_unique": {
"name": "api_keys_key_unique",
"nullsNotDistinct": false,
- "columns": [
- "key"
- ]
+ "columns": ["key"]
},
"api_keys_key_hash_unique": {
"name": "api_keys_key_hash_unique",
"nullsNotDistinct": false,
- "columns": [
- "key_hash"
- ]
+ "columns": ["key_hash"]
}
},
"policies": {},
@@ -10686,12 +10096,8 @@
"name": "async_tasks_user_id_users_id_fk",
"tableFrom": "async_tasks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -10699,12 +10105,8 @@
"name": "async_tasks_workspace_id_workspaces_id_fk",
"tableFrom": "async_tasks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10821,12 +10223,8 @@
"name": "accounts_user_id_users_id_fk",
"tableFrom": "accounts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -10946,12 +10344,8 @@
"name": "passkey_userId_users_id_fk",
"tableFrom": "passkey",
"tableTo": "users",
- "columnsFrom": [
- "userId"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["userId"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -11044,12 +10438,8 @@
"name": "auth_sessions_user_id_users_id_fk",
"tableFrom": "auth_sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -11059,9 +10449,7 @@
"auth_sessions_token_unique": {
"name": "auth_sessions_token_unique",
"nullsNotDistinct": false,
- "columns": [
- "token"
- ]
+ "columns": ["token"]
}
},
"policies": {},
@@ -11134,12 +10522,8 @@
"name": "two_factor_user_id_users_id_fk",
"tableFrom": "two_factor",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -11322,12 +10706,8 @@
"name": "channel_audit_channel_id_channels_id_fk",
"tableFrom": "channel_audit",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -11689,12 +11069,8 @@
"name": "channel_jobs_channel_id_channels_id_fk",
"tableFrom": "channel_jobs",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -11702,12 +11078,8 @@
"name": "channel_jobs_topic_id_topics_id_fk",
"tableFrom": "channel_jobs",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -11715,12 +11087,8 @@
"name": "channel_jobs_operation_id_agent_operations_id_fk",
"tableFrom": "channel_jobs",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -11728,14 +11096,8 @@
"name": "channel_jobs_member_fk",
"tableFrom": "channel_jobs",
"tableTo": "channel_members",
- "columnsFrom": [
- "channel_id",
- "member_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "member_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -11743,14 +11105,8 @@
"name": "channel_jobs_requester_fk",
"tableFrom": "channel_jobs",
"tableTo": "channel_members",
- "columnsFrom": [
- "channel_id",
- "requester_member_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "requester_member_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -11758,14 +11114,8 @@
"name": "channel_jobs_message_fk",
"tableFrom": "channel_jobs",
"tableTo": "channel_messages",
- "columnsFrom": [
- "channel_id",
- "message_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "message_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -11773,14 +11123,8 @@
"name": "channel_jobs_thread_fk",
"tableFrom": "channel_jobs",
"tableTo": "channel_threads",
- "columnsFrom": [
- "channel_id",
- "thread_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "thread_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -11790,17 +11134,12 @@
"channel_jobs_operation_id_unique": {
"name": "channel_jobs_operation_id_unique",
"nullsNotDistinct": false,
- "columns": [
- "operation_id"
- ]
+ "columns": ["operation_id"]
},
"channel_jobs_scope_unique": {
"name": "channel_jobs_scope_unique",
"nullsNotDistinct": false,
- "columns": [
- "channel_id",
- "id"
- ]
+ "columns": ["channel_id", "id"]
}
},
"policies": {},
@@ -11944,12 +11283,8 @@
"name": "channel_member_grants_channel_id_channels_id_fk",
"tableFrom": "channel_member_grants",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -11957,12 +11292,8 @@
"name": "channel_member_grants_device_owner_id_users_id_fk",
"tableFrom": "channel_member_grants",
"tableTo": "users",
- "columnsFrom": [
- "device_owner_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_owner_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -11970,14 +11301,8 @@
"name": "channel_member_grants_member_fk",
"tableFrom": "channel_member_grants",
"tableTo": "channel_members",
- "columnsFrom": [
- "channel_id",
- "member_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "member_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -11985,14 +11310,8 @@
"name": "channel_member_grants_requester_fk",
"tableFrom": "channel_member_grants",
"tableTo": "channel_members",
- "columnsFrom": [
- "channel_id",
- "requested_by_member_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "requested_by_member_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -12157,12 +11476,8 @@
"name": "channel_members_channel_id_channels_id_fk",
"tableFrom": "channel_members",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -12170,12 +11485,8 @@
"name": "channel_members_user_id_users_id_fk",
"tableFrom": "channel_members",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -12183,12 +11494,8 @@
"name": "channel_members_agent_id_agents_id_fk",
"tableFrom": "channel_members",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -12198,10 +11505,7 @@
"channel_members_scope_unique": {
"name": "channel_members_scope_unique",
"nullsNotDistinct": false,
- "columns": [
- "channel_id",
- "id"
- ]
+ "columns": ["channel_id", "id"]
}
},
"policies": {},
@@ -12289,12 +11593,8 @@
"name": "channel_message_files_message_id_channel_messages_id_fk",
"tableFrom": "channel_message_files",
"tableTo": "channel_messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -12302,12 +11602,8 @@
"name": "channel_message_files_file_id_files_id_fk",
"tableFrom": "channel_message_files",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -12317,10 +11613,7 @@
"channel_message_files_message_file_unique": {
"name": "channel_message_files_message_file_unique",
"nullsNotDistinct": false,
- "columns": [
- "message_id",
- "file_id"
- ]
+ "columns": ["message_id", "file_id"]
}
},
"policies": {},
@@ -12566,12 +11859,8 @@
"name": "channel_messages_channel_id_channels_id_fk",
"tableFrom": "channel_messages",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -12579,12 +11868,8 @@
"name": "channel_messages_user_id_users_id_fk",
"tableFrom": "channel_messages",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -12592,12 +11877,8 @@
"name": "channel_messages_agent_id_agents_id_fk",
"tableFrom": "channel_messages",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -12605,14 +11886,8 @@
"name": "channel_messages_thread_fk",
"tableFrom": "channel_messages",
"tableTo": "channel_threads",
- "columnsFrom": [
- "channel_id",
- "thread_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "thread_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -12622,10 +11897,7 @@
"channel_messages_scope_unique": {
"name": "channel_messages_scope_unique",
"nullsNotDistinct": false,
- "columns": [
- "channel_id",
- "id"
- ]
+ "columns": ["channel_id", "id"]
}
},
"policies": {},
@@ -12743,12 +12015,8 @@
"name": "channel_threads_channel_id_channels_id_fk",
"tableFrom": "channel_threads",
"tableTo": "channels",
- "columnsFrom": [
- "channel_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -12756,14 +12024,8 @@
"name": "channel_threads_root_fk",
"tableFrom": "channel_threads",
"tableTo": "channel_messages",
- "columnsFrom": [
- "channel_id",
- "root_message_id"
- ],
- "columnsTo": [
- "channel_id",
- "id"
- ],
+ "columnsFrom": ["channel_id", "root_message_id"],
+ "columnsTo": ["channel_id", "id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -12773,10 +12035,7 @@
"channel_threads_scope_unique": {
"name": "channel_threads_scope_unique",
"nullsNotDistinct": false,
- "columns": [
- "channel_id",
- "id"
- ]
+ "columns": ["channel_id", "id"]
}
},
"policies": {},
@@ -12971,12 +12230,8 @@
"name": "channels_user_id_users_id_fk",
"tableFrom": "channels",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -12984,12 +12239,8 @@
"name": "channels_workspace_id_workspaces_id_fk",
"tableFrom": "channels",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -12997,12 +12248,8 @@
"name": "channels_project_id_projects_id_fk",
"tableFrom": "channels",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -13010,12 +12257,8 @@
"name": "channels_agent_id_agents_id_fk",
"tableFrom": "channels",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -13261,12 +12504,8 @@
"name": "chat_groups_user_id_users_id_fk",
"tableFrom": "chat_groups",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13274,12 +12513,8 @@
"name": "chat_groups_workspace_id_workspaces_id_fk",
"tableFrom": "chat_groups",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13287,12 +12522,8 @@
"name": "chat_groups_group_id_session_groups_id_fk",
"tableFrom": "chat_groups",
"tableTo": "session_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -13411,12 +12642,8 @@
"name": "chat_groups_agents_chat_group_id_chat_groups_id_fk",
"tableFrom": "chat_groups_agents",
"tableTo": "chat_groups",
- "columnsFrom": [
- "chat_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13424,12 +12651,8 @@
"name": "chat_groups_agents_agent_id_agents_id_fk",
"tableFrom": "chat_groups_agents",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13437,12 +12660,8 @@
"name": "chat_groups_agents_user_id_users_id_fk",
"tableFrom": "chat_groups_agents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13450,12 +12669,8 @@
"name": "chat_groups_agents_workspace_id_workspaces_id_fk",
"tableFrom": "chat_groups_agents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -13463,10 +12678,7 @@
"compositePrimaryKeys": {
"chat_groups_agents_chat_group_id_agent_id_pk": {
"name": "chat_groups_agents_chat_group_id_agent_id_pk",
- "columns": [
- "chat_group_id",
- "agent_id"
- ]
+ "columns": ["chat_group_id", "agent_id"]
}
},
"uniqueConstraints": {},
@@ -13671,12 +12883,8 @@
"name": "user_connector_tools_user_connector_id_user_connectors_id_fk",
"tableFrom": "user_connector_tools",
"tableTo": "user_connectors",
- "columnsFrom": [
- "user_connector_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_connector_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13684,12 +12892,8 @@
"name": "user_connector_tools_user_id_users_id_fk",
"tableFrom": "user_connector_tools",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13697,12 +12901,8 @@
"name": "user_connector_tools_workspace_id_workspaces_id_fk",
"tableFrom": "user_connector_tools",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -13976,12 +13176,8 @@
"name": "user_connectors_user_id_users_id_fk",
"tableFrom": "user_connectors",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -13989,12 +13185,8 @@
"name": "user_connectors_workspace_id_workspaces_id_fk",
"tableFrom": "user_connectors",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14002,12 +13194,8 @@
"name": "user_connectors_agent_id_agents_id_fk",
"tableFrom": "user_connectors",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -14114,12 +13302,8 @@
"name": "user_installed_plugins_user_id_users_id_fk",
"tableFrom": "user_installed_plugins",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14127,12 +13311,8 @@
"name": "user_installed_plugins_workspace_id_workspaces_id_fk",
"tableFrom": "user_installed_plugins",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -14140,10 +13320,7 @@
"compositePrimaryKeys": {
"user_installed_plugins_user_id_identifier_pk": {
"name": "user_installed_plugins_user_id_identifier_pk",
- "columns": [
- "user_id",
- "identifier"
- ]
+ "columns": ["user_id", "identifier"]
}
},
"uniqueConstraints": {},
@@ -14315,12 +13492,8 @@
"name": "dashboard_items_dashboard_id_dashboards_id_fk",
"tableFrom": "dashboard_items",
"tableTo": "dashboards",
- "columnsFrom": [
- "dashboard_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dashboard_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14328,12 +13501,8 @@
"name": "dashboard_items_widget_id_widgets_id_fk",
"tableFrom": "dashboard_items",
"tableTo": "widgets",
- "columnsFrom": [
- "widget_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["widget_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14341,12 +13510,8 @@
"name": "dashboard_items_user_id_users_id_fk",
"tableFrom": "dashboard_items",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14354,12 +13519,8 @@
"name": "dashboard_items_workspace_id_workspaces_id_fk",
"tableFrom": "dashboard_items",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -14602,12 +13763,8 @@
"name": "dashboards_user_id_users_id_fk",
"tableFrom": "dashboards",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14615,12 +13772,8 @@
"name": "dashboards_workspace_id_workspaces_id_fk",
"tableFrom": "dashboards",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14628,12 +13781,8 @@
"name": "dashboards_project_id_projects_id_fk",
"tableFrom": "dashboards",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14641,12 +13790,8 @@
"name": "dashboards_agent_id_agents_id_fk",
"tableFrom": "dashboards",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -14899,12 +14044,8 @@
"name": "devices_user_id_users_id_fk",
"tableFrom": "devices",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -14912,12 +14053,8 @@
"name": "devices_workspace_id_workspaces_id_fk",
"tableFrom": "devices",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -15029,12 +14166,8 @@
"name": "document_comment_mentions_comment_id_document_comments_id_fk",
"tableFrom": "document_comment_mentions",
"tableTo": "document_comments",
- "columnsFrom": [
- "comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["comment_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15042,12 +14175,8 @@
"name": "document_comment_mentions_mentioned_user_id_users_id_fk",
"tableFrom": "document_comment_mentions",
"tableTo": "users",
- "columnsFrom": [
- "mentioned_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["mentioned_user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15055,12 +14184,8 @@
"name": "document_comment_mentions_workspace_id_workspaces_id_fk",
"tableFrom": "document_comment_mentions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -15290,12 +14415,8 @@
"name": "document_comments_document_id_documents_id_fk",
"tableFrom": "document_comments",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15303,12 +14424,8 @@
"name": "document_comments_parent_comment_id_document_comments_id_fk",
"tableFrom": "document_comments",
"tableTo": "document_comments",
- "columnsFrom": [
- "parent_comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_comment_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -15316,12 +14433,8 @@
"name": "document_comments_reply_to_comment_id_document_comments_id_fk",
"tableFrom": "document_comments",
"tableTo": "document_comments",
- "columnsFrom": [
- "reply_to_comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["reply_to_comment_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -15329,12 +14442,8 @@
"name": "document_comments_author_user_id_users_id_fk",
"tableFrom": "document_comments",
"tableTo": "users",
- "columnsFrom": [
- "author_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -15342,12 +14451,8 @@
"name": "document_comments_workspace_id_workspaces_id_fk",
"tableFrom": "document_comments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -15495,12 +14600,8 @@
"name": "document_histories_document_id_documents_id_fk",
"tableFrom": "document_histories",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15508,12 +14609,8 @@
"name": "document_histories_user_id_users_id_fk",
"tableFrom": "document_histories",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15521,12 +14618,8 @@
"name": "document_histories_workspace_id_workspaces_id_fk",
"tableFrom": "document_histories",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -15653,12 +14746,8 @@
"name": "document_likes_document_id_documents_id_fk",
"tableFrom": "document_likes",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15666,12 +14755,8 @@
"name": "document_likes_user_id_users_id_fk",
"tableFrom": "document_likes",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15679,12 +14764,8 @@
"name": "document_likes_workspace_id_workspaces_id_fk",
"tableFrom": "document_likes",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -15819,12 +14900,8 @@
"name": "document_shares_document_id_documents_id_fk",
"tableFrom": "document_shares",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15832,12 +14909,8 @@
"name": "document_shares_user_id_users_id_fk",
"tableFrom": "document_shares",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -15845,12 +14918,8 @@
"name": "document_shares_workspace_id_workspaces_id_fk",
"tableFrom": "document_shares",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -16052,12 +15121,8 @@
"name": "environments_user_id_users_id_fk",
"tableFrom": "environments",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
},
@@ -16065,12 +15130,8 @@
"name": "environments_workspace_id_workspaces_id_fk",
"tableFrom": "environments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
}
@@ -16314,12 +15375,8 @@
"name": "environment_instances_environment_id_environments_id_fk",
"tableFrom": "environment_instances",
"tableTo": "environments",
- "columnsFrom": [
- "environment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["environment_id"],
+ "columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
},
@@ -16327,12 +15384,8 @@
"name": "environment_instances_device_id_devices_id_fk",
"tableFrom": "environment_instances",
"tableTo": "devices",
- "columnsFrom": [
- "device_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
}
@@ -16585,12 +15638,8 @@
"name": "expertise_bindings_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16598,12 +15647,8 @@
"name": "expertise_bindings_agent_id_agents_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16611,12 +15656,8 @@
"name": "expertise_bindings_project_id_projects_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16624,12 +15665,8 @@
"name": "expertise_bindings_bound_workspace_id_workspaces_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "workspaces",
- "columnsFrom": [
- "bound_workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["bound_workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16637,12 +15674,8 @@
"name": "expertise_bindings_bound_user_id_users_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "users",
- "columnsFrom": [
- "bound_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["bound_user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16650,12 +15683,8 @@
"name": "expertise_bindings_added_by_user_id_users_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -16663,12 +15692,8 @@
"name": "expertise_bindings_workspace_id_workspaces_id_fk",
"tableFrom": "expertise_bindings",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -16898,12 +15923,8 @@
"name": "expertise_domain_snapshots_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_domain_snapshots",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -16911,12 +15932,8 @@
"name": "expertise_domain_snapshots_run_id_expertise_runs_id_fk",
"tableFrom": "expertise_domain_snapshots",
"tableTo": "expertise_runs",
- "columnsFrom": [
- "run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["run_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -16924,14 +15941,8 @@
"name": "expertise_domain_snapshots_run_domain_fk",
"tableFrom": "expertise_domain_snapshots",
"tableTo": "expertise_runs",
- "columnsFrom": [
- "run_id",
- "domain_id"
- ],
- "columnsTo": [
- "id",
- "domain_id"
- ],
+ "columnsFrom": ["run_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
"onDelete": "no action",
"onUpdate": "no action"
}
@@ -17216,12 +16227,8 @@
"name": "expertise_domains_user_id_users_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17229,12 +16236,8 @@
"name": "expertise_domains_workspace_id_workspaces_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17242,12 +16245,8 @@
"name": "expertise_domains_parent_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "parent_domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_domain_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17255,12 +16254,8 @@
"name": "expertise_domains_canon_document_id_documents_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "documents",
- "columnsFrom": [
- "canon_document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["canon_document_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17268,12 +16263,8 @@
"name": "expertise_domains_lesson_base_document_id_documents_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "documents",
- "columnsFrom": [
- "lesson_base_document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["lesson_base_document_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17281,12 +16272,8 @@
"name": "expertise_domains_anchor_chosen_by_user_id_users_id_fk",
"tableFrom": "expertise_domains",
"tableTo": "users",
- "columnsFrom": [
- "anchor_chosen_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["anchor_chosen_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -17495,12 +16482,8 @@
"name": "expertise_hits_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_hits",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17508,12 +16491,8 @@
"name": "expertise_hits_evidence_id_verify_evidence_id_fk",
"tableFrom": "expertise_hits",
"tableTo": "verify_evidence",
- "columnsFrom": [
- "evidence_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["evidence_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17521,12 +16500,8 @@
"name": "expertise_hits_operation_id_agent_operations_id_fk",
"tableFrom": "expertise_hits",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17534,12 +16509,8 @@
"name": "expertise_hits_source_check_result_id_verify_check_results_id_fk",
"tableFrom": "expertise_hits",
"tableTo": "verify_check_results",
- "columnsFrom": [
- "source_check_result_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_check_result_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17547,12 +16518,8 @@
"name": "expertise_hits_source_message_id_messages_id_fk",
"tableFrom": "expertise_hits",
"tableTo": "messages",
- "columnsFrom": [
- "source_message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_message_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17560,14 +16527,8 @@
"name": "expertise_hits_run_domain_fk",
"tableFrom": "expertise_hits",
"tableTo": "expertise_runs",
- "columnsFrom": [
- "run_id",
- "domain_id"
- ],
- "columnsTo": [
- "id",
- "domain_id"
- ],
+ "columnsFrom": ["run_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17575,14 +16536,8 @@
"name": "expertise_hits_lesson_domain_fk",
"tableFrom": "expertise_hits",
"tableTo": "expertise_lessons",
- "columnsFrom": [
- "lesson_id",
- "domain_id"
- ],
- "columnsTo": [
- "id",
- "domain_id"
- ],
+ "columnsFrom": ["lesson_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -17769,12 +16724,8 @@
"name": "expertise_insights_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_insights",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17782,12 +16733,8 @@
"name": "expertise_insights_user_id_users_id_fk",
"tableFrom": "expertise_insights",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17795,12 +16742,8 @@
"name": "expertise_insights_workspace_id_workspaces_id_fk",
"tableFrom": "expertise_insights",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17808,12 +16751,8 @@
"name": "expertise_insights_generated_by_operation_id_agent_operations_id_fk",
"tableFrom": "expertise_insights",
"tableTo": "agent_operations",
- "columnsFrom": [
- "generated_by_operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["generated_by_operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -17953,12 +16892,8 @@
"name": "expertise_lesson_revisions_lesson_id_expertise_lessons_id_fk",
"tableFrom": "expertise_lesson_revisions",
"tableTo": "expertise_lessons",
- "columnsFrom": [
- "lesson_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["lesson_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -17966,12 +16901,8 @@
"name": "expertise_lesson_revisions_changed_by_user_id_users_id_fk",
"tableFrom": "expertise_lesson_revisions",
"tableTo": "users",
- "columnsFrom": [
- "changed_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["changed_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -17979,12 +16910,8 @@
"name": "expertise_lesson_revisions_operation_id_agent_operations_id_fk",
"tableFrom": "expertise_lesson_revisions",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -18318,12 +17245,8 @@
"name": "expertise_lessons_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_lessons",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -18331,12 +17254,8 @@
"name": "expertise_lessons_created_by_user_id_users_id_fk",
"tableFrom": "expertise_lessons",
"tableTo": "users",
- "columnsFrom": [
- "created_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -18344,12 +17263,8 @@
"name": "expertise_lessons_salvaged_from_id_expertise_lessons_id_fk",
"tableFrom": "expertise_lessons",
"tableTo": "expertise_lessons",
- "columnsFrom": [
- "salvaged_from_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["salvaged_from_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -18357,12 +17272,8 @@
"name": "expertise_lessons_compiled_criterion_id_verify_criteria_id_fk",
"tableFrom": "expertise_lessons",
"tableTo": "verify_criteria",
- "columnsFrom": [
- "compiled_criterion_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["compiled_criterion_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -18372,10 +17283,7 @@
"expertise_lessons_id_domain_unique": {
"name": "expertise_lessons_id_domain_unique",
"nullsNotDistinct": false,
- "columns": [
- "id",
- "domain_id"
- ]
+ "columns": ["id", "domain_id"]
}
},
"policies": {},
@@ -18642,12 +17550,8 @@
"name": "expertise_runs_domain_id_expertise_domains_id_fk",
"tableFrom": "expertise_runs",
"tableTo": "expertise_domains",
- "columnsFrom": [
- "domain_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -18655,12 +17559,8 @@
"name": "expertise_runs_user_id_users_id_fk",
"tableFrom": "expertise_runs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -18668,12 +17568,8 @@
"name": "expertise_runs_workspace_id_workspaces_id_fk",
"tableFrom": "expertise_runs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -18683,10 +17579,7 @@
"expertise_runs_id_domain_unique": {
"name": "expertise_runs_id_domain_unique",
"nullsNotDistinct": false,
- "columns": [
- "id",
- "domain_id"
- ]
+ "columns": ["id", "domain_id"]
}
},
"policies": {},
@@ -18874,12 +17767,8 @@
"name": "user_favorites_user_id_users_id_fk",
"tableFrom": "user_favorites",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -18887,12 +17776,8 @@
"name": "user_favorites_workspace_id_workspaces_id_fk",
"tableFrom": "user_favorites",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -19287,12 +18172,8 @@
"name": "documents_file_id_files_id_fk",
"tableFrom": "documents",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19300,12 +18181,8 @@
"name": "documents_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "documents",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19313,12 +18190,8 @@
"name": "documents_parent_id_documents_id_fk",
"tableFrom": "documents",
"tableTo": "documents",
- "columnsFrom": [
- "parent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19326,12 +18199,8 @@
"name": "documents_user_id_users_id_fk",
"tableFrom": "documents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -19339,12 +18208,8 @@
"name": "documents_workspace_id_workspaces_id_fk",
"tableFrom": "documents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -19561,12 +18426,8 @@
"name": "file_uploads_user_id_users_id_fk",
"tableFrom": "file_uploads",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -19574,12 +18435,8 @@
"name": "file_uploads_workspace_id_workspaces_id_fk",
"tableFrom": "file_uploads",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -19587,12 +18444,8 @@
"name": "file_uploads_file_id_files_id_fk",
"tableFrom": "file_uploads",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -19877,12 +18730,8 @@
"name": "files_user_id_users_id_fk",
"tableFrom": "files",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -19890,12 +18739,8 @@
"name": "files_file_hash_global_files_hash_id_fk",
"tableFrom": "files",
"tableTo": "global_files",
- "columnsFrom": [
- "file_hash"
- ],
- "columnsTo": [
- "hash_id"
- ],
+ "columnsFrom": ["file_hash"],
+ "columnsTo": ["hash_id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -19903,12 +18748,8 @@
"name": "files_parent_id_documents_id_fk",
"tableFrom": "files",
"tableTo": "documents",
- "columnsFrom": [
- "parent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19916,12 +18757,8 @@
"name": "files_chunk_task_id_async_tasks_id_fk",
"tableFrom": "files",
"tableTo": "async_tasks",
- "columnsFrom": [
- "chunk_task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19929,12 +18766,8 @@
"name": "files_embedding_task_id_async_tasks_id_fk",
"tableFrom": "files",
"tableTo": "async_tasks",
- "columnsFrom": [
- "embedding_task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["embedding_task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -19942,12 +18775,8 @@
"name": "files_workspace_id_workspaces_id_fk",
"tableFrom": "files",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -20035,12 +18864,8 @@
"name": "global_files_creator_users_id_fk",
"tableFrom": "global_files",
"tableTo": "users",
- "columnsFrom": [
- "creator"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["creator"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -20154,12 +18979,8 @@
"name": "knowledge_base_files_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "knowledge_base_files",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20167,12 +18988,8 @@
"name": "knowledge_base_files_file_id_files_id_fk",
"tableFrom": "knowledge_base_files",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20180,12 +18997,8 @@
"name": "knowledge_base_files_user_id_users_id_fk",
"tableFrom": "knowledge_base_files",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20193,12 +19006,8 @@
"name": "knowledge_base_files_workspace_id_workspaces_id_fk",
"tableFrom": "knowledge_base_files",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -20206,10 +19015,7 @@
"compositePrimaryKeys": {
"knowledge_base_files_knowledge_base_id_file_id_pk": {
"name": "knowledge_base_files_knowledge_base_id_file_id_pk",
- "columns": [
- "knowledge_base_id",
- "file_id"
- ]
+ "columns": ["knowledge_base_id", "file_id"]
}
},
"uniqueConstraints": {},
@@ -20408,12 +19214,8 @@
"name": "knowledge_bases_user_id_users_id_fk",
"tableFrom": "knowledge_bases",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20421,12 +19223,8 @@
"name": "knowledge_bases_workspace_id_workspaces_id_fk",
"tableFrom": "knowledge_bases",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -20565,12 +19363,8 @@
"name": "file_shares_file_id_files_id_fk",
"tableFrom": "file_shares",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20578,12 +19372,8 @@
"name": "file_shares_user_id_users_id_fk",
"tableFrom": "file_shares",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20591,12 +19381,8 @@
"name": "file_shares_workspace_id_workspaces_id_fk",
"tableFrom": "file_shares",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -20962,12 +19748,8 @@
"name": "generation_batches_user_id_users_id_fk",
"tableFrom": "generation_batches",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20975,12 +19757,8 @@
"name": "generation_batches_workspace_id_workspaces_id_fk",
"tableFrom": "generation_batches",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -20988,12 +19766,8 @@
"name": "generation_batches_generation_topic_id_generation_topics_id_fk",
"tableFrom": "generation_batches",
"tableTo": "generation_topics",
- "columnsFrom": [
- "generation_topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["generation_topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -21150,12 +19924,8 @@
"name": "generation_topics_user_id_users_id_fk",
"tableFrom": "generation_topics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21163,12 +19933,8 @@
"name": "generation_topics_workspace_id_workspaces_id_fk",
"tableFrom": "generation_topics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -21332,12 +20098,8 @@
"name": "generations_user_id_users_id_fk",
"tableFrom": "generations",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21345,12 +20107,8 @@
"name": "generations_workspace_id_workspaces_id_fk",
"tableFrom": "generations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21358,12 +20116,8 @@
"name": "generations_generation_batch_id_generation_batches_id_fk",
"tableFrom": "generations",
"tableTo": "generation_batches",
- "columnsFrom": [
- "generation_batch_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["generation_batch_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21371,12 +20125,8 @@
"name": "generations_async_task_id_async_tasks_id_fk",
"tableFrom": "generations",
"tableTo": "async_tasks",
- "columnsFrom": [
- "async_task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["async_task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -21384,12 +20134,8 @@
"name": "generations_file_id_files_id_fk",
"tableFrom": "generations",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -21665,12 +20411,8 @@
"name": "goals_user_id_users_id_fk",
"tableFrom": "goals",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21678,12 +20420,8 @@
"name": "goals_workspace_id_workspaces_id_fk",
"tableFrom": "goals",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21691,12 +20429,8 @@
"name": "goals_agent_id_agents_id_fk",
"tableFrom": "goals",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -21704,12 +20438,8 @@
"name": "goals_project_id_projects_id_fk",
"tableFrom": "goals",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -21827,12 +20557,8 @@
"name": "goal_edges_goal_id_goals_id_fk",
"tableFrom": "goal_edges",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21840,14 +20566,8 @@
"name": "goal_edges_goal_source_node_fk",
"tableFrom": "goal_edges",
"tableTo": "goal_nodes",
- "columnsFrom": [
- "goal_id",
- "source_node_id"
- ],
- "columnsTo": [
- "goal_id",
- "id"
- ],
+ "columnsFrom": ["goal_id", "source_node_id"],
+ "columnsTo": ["goal_id", "id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -21855,14 +20575,8 @@
"name": "goal_edges_goal_target_node_fk",
"tableFrom": "goal_edges",
"tableTo": "goal_nodes",
- "columnsFrom": [
- "goal_id",
- "target_node_id"
- ],
- "columnsTo": [
- "goal_id",
- "id"
- ],
+ "columnsFrom": ["goal_id", "target_node_id"],
+ "columnsTo": ["goal_id", "id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -22030,12 +20744,8 @@
"name": "goal_events_goal_id_goals_id_fk",
"tableFrom": "goal_events",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22043,12 +20753,8 @@
"name": "goal_events_task_id_tasks_id_fk",
"tableFrom": "goal_events",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -22250,12 +20956,8 @@
"name": "goal_node_decisions_node_id_goal_nodes_id_fk",
"tableFrom": "goal_node_decisions",
"tableTo": "goal_nodes",
- "columnsFrom": [
- "node_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["node_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22263,12 +20965,8 @@
"name": "goal_node_decisions_requested_user_id_users_id_fk",
"tableFrom": "goal_node_decisions",
"tableTo": "users",
- "columnsFrom": [
- "requested_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["requested_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -22276,12 +20974,8 @@
"name": "goal_node_decisions_resolved_by_user_id_users_id_fk",
"tableFrom": "goal_node_decisions",
"tableTo": "users",
- "columnsFrom": [
- "resolved_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["resolved_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -22289,12 +20983,8 @@
"name": "goal_node_decisions_resolved_by_agent_id_agents_id_fk",
"tableFrom": "goal_node_decisions",
"tableTo": "agents",
- "columnsFrom": [
- "resolved_by_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["resolved_by_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -22391,12 +21081,8 @@
"name": "goal_node_work_versions_node_id_goal_nodes_id_fk",
"tableFrom": "goal_node_work_versions",
"tableTo": "goal_nodes",
- "columnsFrom": [
- "node_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["node_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22404,12 +21090,8 @@
"name": "goal_node_work_versions_work_version_id_work_versions_id_fk",
"tableFrom": "goal_node_work_versions",
"tableTo": "work_versions",
- "columnsFrom": [
- "work_version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["work_version_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -22601,12 +21283,8 @@
"name": "goal_nodes_goal_id_goals_id_fk",
"tableFrom": "goal_nodes",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22614,12 +21292,8 @@
"name": "goal_nodes_task_id_tasks_id_fk",
"tableFrom": "goal_nodes",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -22627,12 +21301,8 @@
"name": "goal_nodes_created_by_user_id_users_id_fk",
"tableFrom": "goal_nodes",
"tableTo": "users",
- "columnsFrom": [
- "created_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -22640,12 +21310,8 @@
"name": "goal_nodes_created_by_agent_id_agents_id_fk",
"tableFrom": "goal_nodes",
"tableTo": "agents",
- "columnsFrom": [
- "created_by_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -22655,10 +21321,7 @@
"goal_nodes_goal_id_id_unique": {
"name": "goal_nodes_goal_id_id_unique",
"nullsNotDistinct": false,
- "columns": [
- "goal_id",
- "id"
- ]
+ "columns": ["goal_id", "id"]
}
},
"policies": {},
@@ -22798,12 +21461,8 @@
"name": "goal_shares_goal_id_goals_id_fk",
"tableFrom": "goal_shares",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22811,12 +21470,8 @@
"name": "goal_shares_user_id_users_id_fk",
"tableFrom": "goal_shares",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -22824,12 +21479,8 @@
"name": "goal_shares_workspace_id_workspaces_id_fk",
"tableFrom": "goal_shares",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -23128,12 +21779,8 @@
"name": "goal_subscriptions_goal_id_goals_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23141,12 +21788,8 @@
"name": "goal_subscriptions_widget_id_widgets_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "widgets",
- "columnsFrom": [
- "widget_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["widget_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23154,12 +21797,8 @@
"name": "goal_subscriptions_metric_id_metrics_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "metrics",
- "columnsFrom": [
- "metric_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["metric_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23167,12 +21806,8 @@
"name": "goal_subscriptions_user_id_users_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23180,12 +21815,8 @@
"name": "goal_subscriptions_workspace_id_workspaces_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23193,12 +21824,8 @@
"name": "goal_subscriptions_confirmed_version_id_widget_versions_id_fk",
"tableFrom": "goal_subscriptions",
"tableTo": "widget_versions",
- "columnsFrom": [
- "confirmed_version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["confirmed_version_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -23384,12 +22011,8 @@
"name": "goal_traces_goal_id_goals_id_fk",
"tableFrom": "goal_traces",
"tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -23587,12 +22210,8 @@
"name": "linear_connections_user_id_users_id_fk",
"tableFrom": "linear_connections",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23600,12 +22219,8 @@
"name": "linear_connections_workspace_id_workspaces_id_fk",
"tableFrom": "linear_connections",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -23782,12 +22397,8 @@
"name": "linear_sync_rules_project_id_projects_id_fk",
"tableFrom": "linear_sync_rules",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23795,12 +22406,8 @@
"name": "linear_sync_rules_connection_id_linear_connections_id_fk",
"tableFrom": "linear_sync_rules",
"tableTo": "linear_connections",
- "columnsFrom": [
- "connection_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["connection_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23808,12 +22415,8 @@
"name": "linear_sync_rules_user_id_users_id_fk",
"tableFrom": "linear_sync_rules",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -23821,12 +22424,8 @@
"name": "linear_sync_rules_workspace_id_workspaces_id_fk",
"tableFrom": "linear_sync_rules",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -24246,12 +22845,8 @@
"name": "llm_generation_tracing_workspace_id_workspaces_id_fk",
"tableFrom": "llm_generation_tracing",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -24343,12 +22938,8 @@
"name": "message_chunks_message_id_messages_id_fk",
"tableFrom": "message_chunks",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24356,12 +22947,8 @@
"name": "message_chunks_chunk_id_chunks_id_fk",
"tableFrom": "message_chunks",
"tableTo": "chunks",
- "columnsFrom": [
- "chunk_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24369,12 +22956,8 @@
"name": "message_chunks_user_id_users_id_fk",
"tableFrom": "message_chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24382,12 +22965,8 @@
"name": "message_chunks_workspace_id_workspaces_id_fk",
"tableFrom": "message_chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -24395,10 +22974,7 @@
"compositePrimaryKeys": {
"message_chunks_chunk_id_message_id_pk": {
"name": "message_chunks_chunk_id_message_id_pk",
- "columns": [
- "chunk_id",
- "message_id"
- ]
+ "columns": ["chunk_id", "message_id"]
}
},
"uniqueConstraints": {},
@@ -24628,12 +23204,8 @@
"name": "message_groups_topic_id_topics_id_fk",
"tableFrom": "message_groups",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24641,12 +23213,8 @@
"name": "message_groups_user_id_users_id_fk",
"tableFrom": "message_groups",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24654,12 +23222,8 @@
"name": "message_groups_workspace_id_workspaces_id_fk",
"tableFrom": "message_groups",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24667,12 +23231,8 @@
"name": "message_groups_parent_group_id_message_groups_id_fk",
"tableFrom": "message_groups",
"tableTo": "message_groups",
- "columnsFrom": [
- "parent_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24680,12 +23240,8 @@
"name": "message_groups_parent_message_id_messages_id_fk",
"tableFrom": "message_groups",
"tableTo": "messages",
- "columnsFrom": [
- "parent_message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -24847,12 +23403,8 @@
"name": "message_plugins_id_messages_id_fk",
"tableFrom": "message_plugins",
"tableTo": "messages",
- "columnsFrom": [
- "id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24860,12 +23412,8 @@
"name": "message_plugins_user_id_users_id_fk",
"tableFrom": "message_plugins",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -24873,12 +23421,8 @@
"name": "message_plugins_workspace_id_workspaces_id_fk",
"tableFrom": "message_plugins",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -25031,12 +23575,8 @@
"name": "message_queries_message_id_messages_id_fk",
"tableFrom": "message_queries",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25044,12 +23584,8 @@
"name": "message_queries_user_id_users_id_fk",
"tableFrom": "message_queries",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25057,12 +23593,8 @@
"name": "message_queries_workspace_id_workspaces_id_fk",
"tableFrom": "message_queries",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25070,12 +23602,8 @@
"name": "message_queries_embeddings_id_embeddings_id_fk",
"tableFrom": "message_queries",
"tableTo": "embeddings",
- "columnsFrom": [
- "embeddings_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["embeddings_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -25194,12 +23722,8 @@
"name": "message_query_chunks_id_messages_id_fk",
"tableFrom": "message_query_chunks",
"tableTo": "messages",
- "columnsFrom": [
- "id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25207,12 +23731,8 @@
"name": "message_query_chunks_query_id_message_queries_id_fk",
"tableFrom": "message_query_chunks",
"tableTo": "message_queries",
- "columnsFrom": [
- "query_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["query_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25220,12 +23740,8 @@
"name": "message_query_chunks_chunk_id_chunks_id_fk",
"tableFrom": "message_query_chunks",
"tableTo": "chunks",
- "columnsFrom": [
- "chunk_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25233,12 +23749,8 @@
"name": "message_query_chunks_user_id_users_id_fk",
"tableFrom": "message_query_chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25246,12 +23758,8 @@
"name": "message_query_chunks_workspace_id_workspaces_id_fk",
"tableFrom": "message_query_chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -25259,11 +23767,7 @@
"compositePrimaryKeys": {
"message_query_chunks_chunk_id_id_query_id_pk": {
"name": "message_query_chunks_chunk_id_id_query_id_pk",
- "columns": [
- "chunk_id",
- "id",
- "query_id"
- ]
+ "columns": ["chunk_id", "id", "query_id"]
}
},
"uniqueConstraints": {},
@@ -25376,12 +23880,8 @@
"name": "message_tts_id_messages_id_fk",
"tableFrom": "message_tts",
"tableTo": "messages",
- "columnsFrom": [
- "id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25389,12 +23889,8 @@
"name": "message_tts_file_id_files_id_fk",
"tableFrom": "message_tts",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25402,12 +23898,8 @@
"name": "message_tts_user_id_users_id_fk",
"tableFrom": "message_tts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25415,12 +23907,8 @@
"name": "message_tts_workspace_id_workspaces_id_fk",
"tableFrom": "message_tts",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -25536,12 +24024,8 @@
"name": "message_translates_id_messages_id_fk",
"tableFrom": "message_translates",
"tableTo": "messages",
- "columnsFrom": [
- "id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25549,12 +24033,8 @@
"name": "message_translates_user_id_users_id_fk",
"tableFrom": "message_translates",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -25562,12 +24042,8 @@
"name": "message_translates_workspace_id_workspaces_id_fk",
"tableFrom": "message_translates",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -26029,12 +24505,8 @@
"name": "messages_user_id_users_id_fk",
"tableFrom": "messages",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26042,12 +24514,8 @@
"name": "messages_session_id_sessions_id_fk",
"tableFrom": "messages",
"tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26055,12 +24523,8 @@
"name": "messages_topic_id_topics_id_fk",
"tableFrom": "messages",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26068,12 +24532,8 @@
"name": "messages_thread_id_threads_id_fk",
"tableFrom": "messages",
"tableTo": "threads",
- "columnsFrom": [
- "thread_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26081,12 +24541,8 @@
"name": "messages_parent_id_messages_id_fk",
"tableFrom": "messages",
"tableTo": "messages",
- "columnsFrom": [
- "parent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -26094,12 +24550,8 @@
"name": "messages_quota_id_messages_id_fk",
"tableFrom": "messages",
"tableTo": "messages",
- "columnsFrom": [
- "quota_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["quota_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -26107,12 +24559,8 @@
"name": "messages_agent_id_agents_id_fk",
"tableFrom": "messages",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26120,12 +24568,8 @@
"name": "messages_group_id_chat_groups_id_fk",
"tableFrom": "messages",
"tableTo": "chat_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -26133,12 +24577,8 @@
"name": "messages_message_group_id_message_groups_id_fk",
"tableFrom": "messages",
"tableTo": "message_groups",
- "columnsFrom": [
- "message_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26146,12 +24586,8 @@
"name": "messages_workspace_id_workspaces_id_fk",
"tableFrom": "messages",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -26243,12 +24679,8 @@
"name": "messages_files_file_id_files_id_fk",
"tableFrom": "messages_files",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26256,12 +24688,8 @@
"name": "messages_files_message_id_messages_id_fk",
"tableFrom": "messages_files",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26269,12 +24697,8 @@
"name": "messages_files_user_id_users_id_fk",
"tableFrom": "messages_files",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26282,12 +24706,8 @@
"name": "messages_files_workspace_id_workspaces_id_fk",
"tableFrom": "messages_files",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -26295,10 +24715,7 @@
"compositePrimaryKeys": {
"messages_files_file_id_message_id_pk": {
"name": "messages_files_file_id_message_id_pk",
- "columns": [
- "file_id",
- "message_id"
- ]
+ "columns": ["file_id", "message_id"]
}
},
"uniqueConstraints": {},
@@ -26513,12 +24930,8 @@
"name": "messenger_account_links_user_id_users_id_fk",
"tableFrom": "messenger_account_links",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26526,12 +24939,8 @@
"name": "messenger_account_links_workspace_id_workspaces_id_fk",
"tableFrom": "messenger_account_links",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26539,12 +24948,8 @@
"name": "messenger_account_links_active_agent_id_agents_id_fk",
"tableFrom": "messenger_account_links",
"tableTo": "agents",
- "columnsFrom": [
- "active_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["active_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -26719,12 +25124,8 @@
"name": "messenger_installations_installed_by_user_id_users_id_fk",
"tableFrom": "messenger_installations",
"tableTo": "users",
- "columnsFrom": [
- "installed_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["installed_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -26872,12 +25273,8 @@
"name": "metric_points_metric_id_metrics_id_fk",
"tableFrom": "metric_points",
"tableTo": "metrics",
- "columnsFrom": [
- "metric_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["metric_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26885,12 +25282,8 @@
"name": "metric_points_user_id_users_id_fk",
"tableFrom": "metric_points",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -26898,12 +25291,8 @@
"name": "metric_points_workspace_id_workspaces_id_fk",
"tableFrom": "metric_points",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27076,12 +25465,8 @@
"name": "metrics_user_id_users_id_fk",
"tableFrom": "metrics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -27089,12 +25474,8 @@
"name": "metrics_workspace_id_workspaces_id_fk",
"tableFrom": "metrics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27198,12 +25579,8 @@
"name": "nextauth_accounts_user_id_users_id_fk",
"tableFrom": "nextauth_accounts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27211,10 +25588,7 @@
"compositePrimaryKeys": {
"nextauth_accounts_provider_providerAccountId_pk": {
"name": "nextauth_accounts_provider_providerAccountId_pk",
- "columns": [
- "provider",
- "providerAccountId"
- ]
+ "columns": ["provider", "providerAccountId"]
}
},
"uniqueConstraints": {},
@@ -27281,12 +25655,8 @@
"name": "nextauth_authenticators_user_id_users_id_fk",
"tableFrom": "nextauth_authenticators",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27294,19 +25664,14 @@
"compositePrimaryKeys": {
"nextauth_authenticators_user_id_credentialID_pk": {
"name": "nextauth_authenticators_user_id_credentialID_pk",
- "columns": [
- "user_id",
- "credentialID"
- ]
+ "columns": ["user_id", "credentialID"]
}
},
"uniqueConstraints": {
"nextauth_authenticators_credentialID_unique": {
"name": "nextauth_authenticators_credentialID_unique",
"nullsNotDistinct": false,
- "columns": [
- "credentialID"
- ]
+ "columns": ["credentialID"]
}
},
"policies": {},
@@ -27358,12 +25723,8 @@
"name": "nextauth_sessions_user_id_users_id_fk",
"tableFrom": "nextauth_sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27402,10 +25763,7 @@
"compositePrimaryKeys": {
"nextauth_verificationtokens_identifier_token_pk": {
"name": "nextauth_verificationtokens_identifier_token_pk",
- "columns": [
- "identifier",
- "token"
- ]
+ "columns": ["identifier", "token"]
}
},
"uniqueConstraints": {},
@@ -27520,12 +25878,8 @@
"name": "notification_deliveries_notification_id_notifications_id_fk",
"tableFrom": "notification_deliveries",
"tableTo": "notifications",
- "columnsFrom": [
- "notification_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["notification_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27781,12 +26135,8 @@
"name": "notifications_user_id_users_id_fk",
"tableFrom": "notifications",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -27794,12 +26144,8 @@
"name": "notifications_workspace_id_workspaces_id_fk",
"tableFrom": "notifications",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -27952,12 +26298,8 @@
"name": "oidc_access_tokens_user_id_users_id_fk",
"tableFrom": "oidc_access_tokens",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28058,12 +26400,8 @@
"name": "oidc_authorization_codes_user_id_users_id_fk",
"tableFrom": "oidc_authorization_codes",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28252,12 +26590,8 @@
"name": "oidc_clients_user_id_users_id_fk",
"tableFrom": "oidc_clients",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -28265,12 +26599,8 @@
"name": "oidc_clients_workspace_id_workspaces_id_fk",
"tableFrom": "oidc_clients",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28337,12 +26667,8 @@
"name": "oidc_consents_user_id_users_id_fk",
"tableFrom": "oidc_consents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -28350,12 +26676,8 @@
"name": "oidc_consents_client_id_oidc_clients_id_fk",
"tableFrom": "oidc_consents",
"tableTo": "oidc_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["client_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28363,10 +26685,7 @@
"compositePrimaryKeys": {
"oidc_consents_user_id_client_id_pk": {
"name": "oidc_consents_user_id_client_id_pk",
- "columns": [
- "user_id",
- "client_id"
- ]
+ "columns": ["user_id", "client_id"]
}
},
"uniqueConstraints": {},
@@ -28470,12 +26789,8 @@
"name": "oidc_device_codes_user_id_users_id_fk",
"tableFrom": "oidc_device_codes",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28570,12 +26885,8 @@
"name": "oidc_grants_user_id_users_id_fk",
"tableFrom": "oidc_grants",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28728,12 +27039,8 @@
"name": "oidc_refresh_tokens_user_id_users_id_fk",
"tableFrom": "oidc_refresh_tokens",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28816,12 +27123,8 @@
"name": "oidc_sessions_user_id_users_id_fk",
"tableFrom": "oidc_sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -28994,12 +27297,8 @@
"name": "project_agents_project_id_projects_id_fk",
"tableFrom": "project_agents",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29007,12 +27306,8 @@
"name": "project_agents_agent_id_agents_id_fk",
"tableFrom": "project_agents",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29020,12 +27315,8 @@
"name": "project_agents_added_by_user_id_users_id_fk",
"tableFrom": "project_agents",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -29033,12 +27324,8 @@
"name": "project_agents_workspace_id_workspaces_id_fk",
"tableFrom": "project_agents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -29211,12 +27498,8 @@
"name": "project_chat_groups_project_id_projects_id_fk",
"tableFrom": "project_chat_groups",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29224,12 +27507,8 @@
"name": "project_chat_groups_chat_group_id_chat_groups_id_fk",
"tableFrom": "project_chat_groups",
"tableTo": "chat_groups",
- "columnsFrom": [
- "chat_group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29237,12 +27516,8 @@
"name": "project_chat_groups_added_by_user_id_users_id_fk",
"tableFrom": "project_chat_groups",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -29250,12 +27525,8 @@
"name": "project_chat_groups_workspace_id_workspaces_id_fk",
"tableFrom": "project_chat_groups",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -29414,12 +27685,8 @@
"name": "project_completion_reviews_project_id_projects_id_fk",
"tableFrom": "project_completion_reviews",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29427,12 +27694,8 @@
"name": "project_completion_reviews_reviewer_user_id_users_id_fk",
"tableFrom": "project_completion_reviews",
"tableTo": "users",
- "columnsFrom": [
- "reviewer_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["reviewer_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -29440,12 +27703,8 @@
"name": "project_completion_reviews_workspace_id_workspaces_id_fk",
"tableFrom": "project_completion_reviews",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -29611,12 +27870,8 @@
"name": "project_knowledge_bases_project_id_projects_id_fk",
"tableFrom": "project_knowledge_bases",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29624,12 +27879,8 @@
"name": "project_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "project_knowledge_bases",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29637,12 +27888,8 @@
"name": "project_knowledge_bases_added_by_user_id_users_id_fk",
"tableFrom": "project_knowledge_bases",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -29650,12 +27897,8 @@
"name": "project_knowledge_bases_workspace_id_workspaces_id_fk",
"tableFrom": "project_knowledge_bases",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -29857,12 +28100,8 @@
"name": "project_working_directories_project_id_projects_id_fk",
"tableFrom": "project_working_directories",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29870,12 +28109,8 @@
"name": "project_working_directories_device_id_devices_id_fk",
"tableFrom": "project_working_directories",
"tableTo": "devices",
- "columnsFrom": [
- "device_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -29883,12 +28118,8 @@
"name": "project_working_directories_workspace_id_workspaces_id_fk",
"tableFrom": "project_working_directories",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -29896,12 +28127,8 @@
"name": "project_working_directories_added_by_user_id_users_id_fk",
"tableFrom": "project_working_directories",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -30287,12 +28514,8 @@
"name": "projects_coordinator_agent_id_agents_id_fk",
"tableFrom": "projects",
"tableTo": "agents",
- "columnsFrom": [
- "coordinator_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["coordinator_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -30300,12 +28523,8 @@
"name": "projects_user_id_users_id_fk",
"tableFrom": "projects",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30313,12 +28532,8 @@
"name": "projects_workspace_id_workspaces_id_fk",
"tableFrom": "projects",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -30543,12 +28758,8 @@
"name": "project_environments_project_id_projects_id_fk",
"tableFrom": "project_environments",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30556,12 +28767,8 @@
"name": "project_environments_environment_id_environments_id_fk",
"tableFrom": "project_environments",
"tableTo": "environments",
- "columnsFrom": [
- "environment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["environment_id"],
+ "columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
},
@@ -30569,12 +28776,8 @@
"name": "project_environments_workspace_id_workspaces_id_fk",
"tableFrom": "project_environments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30582,12 +28785,8 @@
"name": "project_environments_added_by_user_id_users_id_fk",
"tableFrom": "project_environments",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -30595,14 +28794,8 @@
"name": "project_environments_default_instance_fk",
"tableFrom": "project_environments",
"tableTo": "environment_instances",
- "columnsFrom": [
- "environment_id",
- "default_instance_id"
- ],
- "columnsTo": [
- "environment_id",
- "id"
- ],
+ "columnsFrom": ["environment_id", "default_instance_id"],
+ "columnsTo": ["environment_id", "id"],
"onDelete": "restrict",
"onUpdate": "no action"
}
@@ -30740,12 +28933,8 @@
"name": "project_members_project_id_projects_id_fk",
"tableFrom": "project_members",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30753,12 +28942,8 @@
"name": "project_members_user_id_users_id_fk",
"tableFrom": "project_members",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30766,12 +28951,8 @@
"name": "project_members_added_by_user_id_users_id_fk",
"tableFrom": "project_members",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -30887,12 +29068,8 @@
"name": "project_sites_project_id_projects_id_fk",
"tableFrom": "project_sites",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30900,12 +29077,8 @@
"name": "project_sites_workspace_id_workspaces_id_fk",
"tableFrom": "project_sites",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -30913,12 +29086,8 @@
"name": "project_sites_created_by_user_id_users_id_fk",
"tableFrom": "project_sites",
"tableTo": "users",
- "columnsFrom": [
- "created_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -30926,12 +29095,8 @@
"name": "project_sites_acceptance_id_acceptances_id_fk",
"tableFrom": "project_sites",
"tableTo": "acceptances",
- "columnsFrom": [
- "acceptance_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -31094,12 +29259,8 @@
"name": "project_works_project_id_projects_id_fk",
"tableFrom": "project_works",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31107,12 +29268,8 @@
"name": "project_works_work_id_works_id_fk",
"tableFrom": "project_works",
"tableTo": "works",
- "columnsFrom": [
- "work_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["work_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31120,12 +29277,8 @@
"name": "project_works_added_by_user_id_users_id_fk",
"tableFrom": "project_works",
"tableTo": "users",
- "columnsFrom": [
- "added_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -31133,12 +29286,8 @@
"name": "project_works_workspace_id_workspaces_id_fk",
"tableFrom": "project_works",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31308,12 +29457,8 @@
"name": "push_live_activities_user_id_users_id_fk",
"tableFrom": "push_live_activities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31461,12 +29606,8 @@
"name": "push_tokens_user_id_users_id_fk",
"tableFrom": "push_tokens",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31621,12 +29762,8 @@
"name": "chunks_user_id_users_id_fk",
"tableFrom": "chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31634,12 +29771,8 @@
"name": "chunks_workspace_id_workspaces_id_fk",
"tableFrom": "chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31759,12 +29892,8 @@
"name": "document_chunks_document_id_documents_id_fk",
"tableFrom": "document_chunks",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31772,12 +29901,8 @@
"name": "document_chunks_chunk_id_chunks_id_fk",
"tableFrom": "document_chunks",
"tableTo": "chunks",
- "columnsFrom": [
- "chunk_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31785,12 +29910,8 @@
"name": "document_chunks_user_id_users_id_fk",
"tableFrom": "document_chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31798,12 +29919,8 @@
"name": "document_chunks_workspace_id_workspaces_id_fk",
"tableFrom": "document_chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31811,10 +29928,7 @@
"compositePrimaryKeys": {
"document_chunks_document_id_chunk_id_pk": {
"name": "document_chunks_document_id_chunk_id_pk",
- "columns": [
- "document_id",
- "chunk_id"
- ]
+ "columns": ["document_id", "chunk_id"]
}
},
"uniqueConstraints": {},
@@ -31943,12 +30057,8 @@
"name": "embeddings_chunk_id_chunks_id_fk",
"tableFrom": "embeddings",
"tableTo": "chunks",
- "columnsFrom": [
- "chunk_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31956,12 +30066,8 @@
"name": "embeddings_user_id_users_id_fk",
"tableFrom": "embeddings",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -31969,12 +30075,8 @@
"name": "embeddings_workspace_id_workspaces_id_fk",
"tableFrom": "embeddings",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -31984,9 +30086,7 @@
"embeddings_chunk_id_unique": {
"name": "embeddings_chunk_id_unique",
"nullsNotDistinct": false,
- "columns": [
- "chunk_id"
- ]
+ "columns": ["chunk_id"]
}
},
"policies": {},
@@ -32174,12 +30274,8 @@
"name": "unstructured_chunks_composite_id_chunks_id_fk",
"tableFrom": "unstructured_chunks",
"tableTo": "chunks",
- "columnsFrom": [
- "composite_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["composite_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32187,12 +30283,8 @@
"name": "unstructured_chunks_user_id_users_id_fk",
"tableFrom": "unstructured_chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32200,12 +30292,8 @@
"name": "unstructured_chunks_workspace_id_workspaces_id_fk",
"tableFrom": "unstructured_chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32213,12 +30301,8 @@
"name": "unstructured_chunks_file_id_files_id_fk",
"tableFrom": "unstructured_chunks",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -32340,12 +30424,8 @@
"name": "rag_eval_dataset_records_dataset_id_rag_eval_datasets_id_fk",
"tableFrom": "rag_eval_dataset_records",
"tableTo": "rag_eval_datasets",
- "columnsFrom": [
- "dataset_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32353,12 +30433,8 @@
"name": "rag_eval_dataset_records_user_id_users_id_fk",
"tableFrom": "rag_eval_dataset_records",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32366,12 +30442,8 @@
"name": "rag_eval_dataset_records_workspace_id_workspaces_id_fk",
"tableFrom": "rag_eval_dataset_records",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -32481,12 +30553,8 @@
"name": "rag_eval_datasets_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "rag_eval_datasets",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32494,12 +30562,8 @@
"name": "rag_eval_datasets_user_id_users_id_fk",
"tableFrom": "rag_eval_datasets",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32507,12 +30571,8 @@
"name": "rag_eval_datasets_workspace_id_workspaces_id_fk",
"tableFrom": "rag_eval_datasets",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -32658,12 +30718,8 @@
"name": "rag_eval_evaluations_dataset_id_rag_eval_datasets_id_fk",
"tableFrom": "rag_eval_evaluations",
"tableTo": "rag_eval_datasets",
- "columnsFrom": [
- "dataset_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32671,12 +30727,8 @@
"name": "rag_eval_evaluations_knowledge_base_id_knowledge_bases_id_fk",
"tableFrom": "rag_eval_evaluations",
"tableTo": "knowledge_bases",
- "columnsFrom": [
- "knowledge_base_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32684,12 +30736,8 @@
"name": "rag_eval_evaluations_user_id_users_id_fk",
"tableFrom": "rag_eval_evaluations",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32697,12 +30745,8 @@
"name": "rag_eval_evaluations_workspace_id_workspaces_id_fk",
"tableFrom": "rag_eval_evaluations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -32866,12 +30910,8 @@
"name": "rag_eval_evaluation_records_question_embedding_id_embeddings_id_fk",
"tableFrom": "rag_eval_evaluation_records",
"tableTo": "embeddings",
- "columnsFrom": [
- "question_embedding_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["question_embedding_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -32879,12 +30919,8 @@
"name": "rag_eval_evaluation_records_dataset_record_id_rag_eval_dataset_records_id_fk",
"tableFrom": "rag_eval_evaluation_records",
"tableTo": "rag_eval_dataset_records",
- "columnsFrom": [
- "dataset_record_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dataset_record_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32892,12 +30928,8 @@
"name": "rag_eval_evaluation_records_evaluation_id_rag_eval_evaluations_id_fk",
"tableFrom": "rag_eval_evaluation_records",
"tableTo": "rag_eval_evaluations",
- "columnsFrom": [
- "evaluation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["evaluation_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32905,12 +30937,8 @@
"name": "rag_eval_evaluation_records_user_id_users_id_fk",
"tableFrom": "rag_eval_evaluation_records",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -32918,12 +30946,8 @@
"name": "rag_eval_evaluation_records_workspace_id_workspaces_id_fk",
"tableFrom": "rag_eval_evaluation_records",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33004,9 +31028,7 @@
"rbac_permissions_code_unique": {
"name": "rbac_permissions_code_unique",
"nullsNotDistinct": false,
- "columns": [
- "code"
- ]
+ "columns": ["code"]
}
},
"policies": {},
@@ -33074,12 +31096,8 @@
"name": "rbac_role_permissions_role_id_rbac_roles_id_fk",
"tableFrom": "rbac_role_permissions",
"tableTo": "rbac_roles",
- "columnsFrom": [
- "role_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["role_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33087,12 +31105,8 @@
"name": "rbac_role_permissions_permission_id_rbac_permissions_id_fk",
"tableFrom": "rbac_role_permissions",
"tableTo": "rbac_permissions",
- "columnsFrom": [
- "permission_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["permission_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33100,10 +31114,7 @@
"compositePrimaryKeys": {
"rbac_role_permissions_role_id_permission_id_pk": {
"name": "rbac_role_permissions_role_id_permission_id_pk",
- "columns": [
- "role_id",
- "permission_id"
- ]
+ "columns": ["role_id", "permission_id"]
}
},
"uniqueConstraints": {},
@@ -33231,12 +31242,8 @@
"name": "rbac_roles_workspace_id_workspaces_id_fk",
"tableFrom": "rbac_roles",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33369,12 +31376,8 @@
"name": "rbac_user_roles_user_id_users_id_fk",
"tableFrom": "rbac_user_roles",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33382,12 +31385,8 @@
"name": "rbac_user_roles_role_id_rbac_roles_id_fk",
"tableFrom": "rbac_user_roles",
"tableTo": "rbac_roles",
- "columnsFrom": [
- "role_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["role_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33395,12 +31394,8 @@
"name": "rbac_user_roles_workspace_id_workspaces_id_fk",
"tableFrom": "rbac_user_roles",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33507,12 +31502,8 @@
"name": "agents_to_sessions_agent_id_agents_id_fk",
"tableFrom": "agents_to_sessions",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33520,12 +31511,8 @@
"name": "agents_to_sessions_session_id_sessions_id_fk",
"tableFrom": "agents_to_sessions",
"tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33533,12 +31520,8 @@
"name": "agents_to_sessions_user_id_users_id_fk",
"tableFrom": "agents_to_sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33546,12 +31529,8 @@
"name": "agents_to_sessions_workspace_id_workspaces_id_fk",
"tableFrom": "agents_to_sessions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33559,10 +31538,7 @@
"compositePrimaryKeys": {
"agents_to_sessions_agent_id_session_id_pk": {
"name": "agents_to_sessions_agent_id_session_id_pk",
- "columns": [
- "agent_id",
- "session_id"
- ]
+ "columns": ["agent_id", "session_id"]
}
},
"uniqueConstraints": {},
@@ -33673,12 +31649,8 @@
"name": "file_chunks_file_id_files_id_fk",
"tableFrom": "file_chunks",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33686,12 +31658,8 @@
"name": "file_chunks_chunk_id_chunks_id_fk",
"tableFrom": "file_chunks",
"tableTo": "chunks",
- "columnsFrom": [
- "chunk_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33699,12 +31667,8 @@
"name": "file_chunks_user_id_users_id_fk",
"tableFrom": "file_chunks",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33712,12 +31676,8 @@
"name": "file_chunks_workspace_id_workspaces_id_fk",
"tableFrom": "file_chunks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33725,10 +31685,7 @@
"compositePrimaryKeys": {
"file_chunks_file_id_chunk_id_pk": {
"name": "file_chunks_file_id_chunk_id_pk",
- "columns": [
- "file_id",
- "chunk_id"
- ]
+ "columns": ["file_id", "chunk_id"]
}
},
"uniqueConstraints": {},
@@ -33832,12 +31789,8 @@
"name": "files_to_sessions_file_id_files_id_fk",
"tableFrom": "files_to_sessions",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33845,12 +31798,8 @@
"name": "files_to_sessions_session_id_sessions_id_fk",
"tableFrom": "files_to_sessions",
"tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33858,12 +31807,8 @@
"name": "files_to_sessions_user_id_users_id_fk",
"tableFrom": "files_to_sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -33871,12 +31816,8 @@
"name": "files_to_sessions_workspace_id_workspaces_id_fk",
"tableFrom": "files_to_sessions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -33884,10 +31825,7 @@
"compositePrimaryKeys": {
"files_to_sessions_file_id_session_id_pk": {
"name": "files_to_sessions_file_id_session_id_pk",
- "columns": [
- "file_id",
- "session_id"
- ]
+ "columns": ["file_id", "session_id"]
}
},
"uniqueConstraints": {},
@@ -34120,12 +32058,8 @@
"name": "resource_permissions_workspace_id_workspaces_id_fk",
"tableFrom": "resource_permissions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -34133,12 +32067,8 @@
"name": "resource_permissions_user_id_users_id_fk",
"tableFrom": "resource_permissions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -34146,12 +32076,8 @@
"name": "resource_permissions_created_by_users_id_fk",
"tableFrom": "resource_permissions",
"tableTo": "users",
- "columnsFrom": [
- "created_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -34321,12 +32247,8 @@
"name": "resource_transfer_requests_workspace_id_workspaces_id_fk",
"tableFrom": "resource_transfer_requests",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -34334,12 +32256,8 @@
"name": "resource_transfer_requests_initiator_id_users_id_fk",
"tableFrom": "resource_transfer_requests",
"tableTo": "users",
- "columnsFrom": [
- "initiator_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["initiator_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34347,12 +32265,8 @@
"name": "resource_transfer_requests_recipient_id_users_id_fk",
"tableFrom": "resource_transfer_requests",
"tableTo": "users",
- "columnsFrom": [
- "recipient_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["recipient_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34360,12 +32274,8 @@
"name": "resource_transfer_requests_previous_owner_id_users_id_fk",
"tableFrom": "resource_transfer_requests",
"tableTo": "users",
- "columnsFrom": [
- "previous_owner_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["previous_owner_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -34760,12 +32670,8 @@
"name": "scm_change_requests_user_id_users_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -34773,12 +32679,8 @@
"name": "scm_change_requests_workspace_id_workspaces_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -34786,12 +32688,8 @@
"name": "scm_change_requests_installation_id_scm_installations_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "scm_installations",
- "columnsFrom": [
- "installation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["installation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34799,12 +32697,8 @@
"name": "scm_change_requests_acceptance_id_acceptances_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "acceptances",
- "columnsFrom": [
- "acceptance_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34812,12 +32706,8 @@
"name": "scm_change_requests_work_id_works_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "works",
- "columnsFrom": [
- "work_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["work_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34825,12 +32715,8 @@
"name": "scm_change_requests_topic_id_topics_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -34838,12 +32724,8 @@
"name": "scm_change_requests_task_id_tasks_id_fk",
"tableFrom": "scm_change_requests",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -34994,12 +32876,8 @@
"name": "scm_identities_user_id_users_id_fk",
"tableFrom": "scm_identities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -35208,12 +33086,8 @@
"name": "scm_installations_user_id_users_id_fk",
"tableFrom": "scm_installations",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -35221,12 +33095,8 @@
"name": "scm_installations_workspace_id_workspaces_id_fk",
"tableFrom": "scm_installations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -35527,12 +33397,8 @@
"name": "session_groups_user_id_users_id_fk",
"tableFrom": "session_groups",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -35540,12 +33406,8 @@
"name": "session_groups_workspace_id_workspaces_id_fk",
"tableFrom": "session_groups",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -35815,12 +33677,8 @@
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -35828,12 +33686,8 @@
"name": "sessions_group_id_session_groups_id_fk",
"tableFrom": "sessions",
"tableTo": "session_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -35841,12 +33695,8 @@
"name": "sessions_workspace_id_workspaces_id_fk",
"tableFrom": "sessions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -36124,12 +33974,8 @@
"name": "signals_user_id_users_id_fk",
"tableFrom": "signals",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36137,12 +33983,8 @@
"name": "signals_workspace_id_workspaces_id_fk",
"tableFrom": "signals",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36150,12 +33992,8 @@
"name": "signals_account_id_agent_accounts_id_fk",
"tableFrom": "signals",
"tableTo": "agent_accounts",
- "columnsFrom": [
- "account_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -36163,12 +34001,8 @@
"name": "signals_agent_id_agents_id_fk",
"tableFrom": "signals",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -36263,12 +34097,8 @@
"name": "signal_decision_labels_decision_id_signal_decisions_id_fk",
"tableFrom": "signal_decision_labels",
"tableTo": "signal_decisions",
- "columnsFrom": [
- "decision_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["decision_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -36482,12 +34312,8 @@
"name": "signal_decisions_signal_id_signals_id_fk",
"tableFrom": "signal_decisions",
"tableTo": "signals",
- "columnsFrom": [
- "signal_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["signal_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36495,12 +34321,8 @@
"name": "signal_decisions_agent_id_agents_id_fk",
"tableFrom": "signal_decisions",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -36508,12 +34330,8 @@
"name": "signal_decisions_user_id_users_id_fk",
"tableFrom": "signal_decisions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36521,12 +34339,8 @@
"name": "signal_decisions_workspace_id_workspaces_id_fk",
"tableFrom": "signal_decisions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36534,12 +34348,8 @@
"name": "signal_decisions_topic_id_topics_id_fk",
"tableFrom": "signal_decisions",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -36920,12 +34730,8 @@
"name": "briefs_user_id_users_id_fk",
"tableFrom": "briefs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36933,12 +34739,8 @@
"name": "briefs_workspace_id_workspaces_id_fk",
"tableFrom": "briefs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36946,12 +34748,8 @@
"name": "briefs_task_id_tasks_id_fk",
"tableFrom": "briefs",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -36959,12 +34757,8 @@
"name": "briefs_cron_job_id_agent_cron_jobs_id_fk",
"tableFrom": "briefs",
"tableTo": "agent_cron_jobs",
- "columnsFrom": [
- "cron_job_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cron_job_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -37122,12 +34916,8 @@
"name": "task_activities_task_id_tasks_id_fk",
"tableFrom": "task_activities",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37135,12 +34925,8 @@
"name": "task_activities_user_id_users_id_fk",
"tableFrom": "task_activities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37148,12 +34934,8 @@
"name": "task_activities_workspace_id_workspaces_id_fk",
"tableFrom": "task_activities",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37161,12 +34943,8 @@
"name": "task_activities_actor_user_id_users_id_fk",
"tableFrom": "task_activities",
"tableTo": "users",
- "columnsFrom": [
- "actor_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["actor_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -37174,12 +34952,8 @@
"name": "task_activities_actor_agent_id_agents_id_fk",
"tableFrom": "task_activities",
"tableTo": "agents",
- "columnsFrom": [
- "actor_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["actor_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -37422,12 +35196,8 @@
"name": "task_comments_task_id_tasks_id_fk",
"tableFrom": "task_comments",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37435,12 +35205,8 @@
"name": "task_comments_user_id_users_id_fk",
"tableFrom": "task_comments",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37448,12 +35214,8 @@
"name": "task_comments_workspace_id_workspaces_id_fk",
"tableFrom": "task_comments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37461,12 +35223,8 @@
"name": "task_comments_author_user_id_users_id_fk",
"tableFrom": "task_comments",
"tableTo": "users",
- "columnsFrom": [
- "author_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -37474,12 +35232,8 @@
"name": "task_comments_author_agent_id_agents_id_fk",
"tableFrom": "task_comments",
"tableTo": "agents",
- "columnsFrom": [
- "author_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -37487,12 +35241,8 @@
"name": "task_comments_brief_id_briefs_id_fk",
"tableFrom": "task_comments",
"tableTo": "briefs",
- "columnsFrom": [
- "brief_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["brief_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -37500,12 +35250,8 @@
"name": "task_comments_topic_id_topics_id_fk",
"tableFrom": "task_comments",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -37694,12 +35440,8 @@
"name": "task_dependencies_task_id_tasks_id_fk",
"tableFrom": "task_dependencies",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37707,12 +35449,8 @@
"name": "task_dependencies_depends_on_id_tasks_id_fk",
"tableFrom": "task_dependencies",
"tableTo": "tasks",
- "columnsFrom": [
- "depends_on_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["depends_on_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37720,12 +35458,8 @@
"name": "task_dependencies_user_id_users_id_fk",
"tableFrom": "task_dependencies",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37733,12 +35467,8 @@
"name": "task_dependencies_workspace_id_workspaces_id_fk",
"tableFrom": "task_dependencies",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -37921,12 +35651,8 @@
"name": "task_documents_task_id_tasks_id_fk",
"tableFrom": "task_documents",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37934,12 +35660,8 @@
"name": "task_documents_document_id_documents_id_fk",
"tableFrom": "task_documents",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37947,12 +35669,8 @@
"name": "task_documents_user_id_users_id_fk",
"tableFrom": "task_documents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -37960,12 +35678,8 @@
"name": "task_documents_workspace_id_workspaces_id_fk",
"tableFrom": "task_documents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -38237,12 +35951,8 @@
"name": "task_topics_task_id_tasks_id_fk",
"tableFrom": "task_topics",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -38250,12 +35960,8 @@
"name": "task_topics_topic_id_topics_id_fk",
"tableFrom": "task_topics",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -38263,12 +35969,8 @@
"name": "task_topics_user_id_users_id_fk",
"tableFrom": "task_topics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -38276,12 +35978,8 @@
"name": "task_topics_workspace_id_workspaces_id_fk",
"tableFrom": "task_topics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -38791,12 +36489,8 @@
"name": "tasks_created_by_user_id_users_id_fk",
"tableFrom": "tasks",
"tableTo": "users",
- "columnsFrom": [
- "created_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -38804,12 +36498,8 @@
"name": "tasks_workspace_id_workspaces_id_fk",
"tableFrom": "tasks",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -38817,12 +36507,8 @@
"name": "tasks_project_id_projects_id_fk",
"tableFrom": "tasks",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -38830,12 +36516,8 @@
"name": "tasks_created_by_agent_id_agents_id_fk",
"tableFrom": "tasks",
"tableTo": "agents",
- "columnsFrom": [
- "created_by_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -38843,12 +36525,8 @@
"name": "tasks_assignee_user_id_users_id_fk",
"tableFrom": "tasks",
"tableTo": "users",
- "columnsFrom": [
- "assignee_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["assignee_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -38856,12 +36534,8 @@
"name": "tasks_assignee_agent_id_agents_id_fk",
"tableFrom": "tasks",
"tableTo": "agents",
- "columnsFrom": [
- "assignee_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["assignee_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -38869,12 +36543,8 @@
"name": "tasks_current_topic_id_topics_id_fk",
"tableFrom": "tasks",
"tableTo": "topics",
- "columnsFrom": [
- "current_topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["current_topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -38882,12 +36552,8 @@
"name": "tasks_parent_task_id_tasks_id_fk",
"tableFrom": "tasks",
"tableTo": "tasks",
- "columnsFrom": [
- "parent_task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_task_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -39119,12 +36785,8 @@
"name": "task_external_links_task_id_tasks_id_fk",
"tableFrom": "task_external_links",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39132,12 +36794,8 @@
"name": "task_external_links_user_id_users_id_fk",
"tableFrom": "task_external_links",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39145,12 +36803,8 @@
"name": "task_external_links_workspace_id_workspaces_id_fk",
"tableFrom": "task_external_links",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -39277,12 +36931,8 @@
"name": "task_label_links_task_id_tasks_id_fk",
"tableFrom": "task_label_links",
"tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39290,12 +36940,8 @@
"name": "task_label_links_label_id_task_labels_id_fk",
"tableFrom": "task_label_links",
"tableTo": "task_labels",
- "columnsFrom": [
- "label_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["label_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39303,12 +36949,8 @@
"name": "task_label_links_user_id_users_id_fk",
"tableFrom": "task_label_links",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39316,12 +36958,8 @@
"name": "task_label_links_workspace_id_workspaces_id_fk",
"tableFrom": "task_label_links",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -39511,12 +37149,8 @@
"name": "task_labels_user_id_users_id_fk",
"tableFrom": "task_labels",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -39524,12 +37158,8 @@
"name": "task_labels_workspace_id_workspaces_id_fk",
"tableFrom": "task_labels",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39537,12 +37167,8 @@
"name": "task_labels_parent_id_task_labels_id_fk",
"tableFrom": "task_labels",
"tableTo": "task_labels",
- "columnsFrom": [
- "parent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -39821,12 +37447,8 @@
"name": "threads_topic_id_topics_id_fk",
"tableFrom": "threads",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39834,12 +37456,8 @@
"name": "threads_parent_thread_id_threads_id_fk",
"tableFrom": "threads",
"tableTo": "threads",
- "columnsFrom": [
- "parent_thread_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_thread_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -39847,12 +37465,8 @@
"name": "threads_agent_id_agents_id_fk",
"tableFrom": "threads",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39860,12 +37474,8 @@
"name": "threads_group_id_chat_groups_id_fk",
"tableFrom": "threads",
"tableTo": "chat_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39873,12 +37483,8 @@
"name": "threads_user_id_users_id_fk",
"tableFrom": "threads",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -39886,12 +37492,8 @@
"name": "threads_workspace_id_workspaces_id_fk",
"tableFrom": "threads",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -40005,12 +37607,8 @@
"name": "topic_documents_document_id_documents_id_fk",
"tableFrom": "topic_documents",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40018,12 +37616,8 @@
"name": "topic_documents_topic_id_topics_id_fk",
"tableFrom": "topic_documents",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40031,12 +37625,8 @@
"name": "topic_documents_user_id_users_id_fk",
"tableFrom": "topic_documents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40044,12 +37634,8 @@
"name": "topic_documents_workspace_id_workspaces_id_fk",
"tableFrom": "topic_documents",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -40057,10 +37643,7 @@
"compositePrimaryKeys": {
"topic_documents_document_id_topic_id_pk": {
"name": "topic_documents_document_id_topic_id_pk",
- "columns": [
- "document_id",
- "topic_id"
- ]
+ "columns": ["document_id", "topic_id"]
}
},
"uniqueConstraints": {},
@@ -40184,12 +37767,8 @@
"name": "topic_shares_topic_id_topics_id_fk",
"tableFrom": "topic_shares",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40197,12 +37776,8 @@
"name": "topic_shares_user_id_users_id_fk",
"tableFrom": "topic_shares",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40210,12 +37785,8 @@
"name": "topic_shares_workspace_id_workspaces_id_fk",
"tableFrom": "topic_shares",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -40721,12 +38292,8 @@
"name": "topics_session_id_sessions_id_fk",
"tableFrom": "topics",
"tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40734,12 +38301,8 @@
"name": "topics_agent_id_agents_id_fk",
"tableFrom": "topics",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40747,12 +38310,8 @@
"name": "topics_group_id_chat_groups_id_fk",
"tableFrom": "topics",
"tableTo": "chat_groups",
- "columnsFrom": [
- "group_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40760,12 +38319,8 @@
"name": "topics_project_id_projects_id_fk",
"tableFrom": "topics",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -40773,12 +38328,8 @@
"name": "topics_project_working_directory_id_project_working_directories_id_fk",
"tableFrom": "topics",
"tableTo": "project_working_directories",
- "columnsFrom": [
- "project_working_directory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_working_directory_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -40786,12 +38337,8 @@
"name": "topics_user_id_users_id_fk",
"tableFrom": "topics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -40799,12 +38346,8 @@
"name": "topics_workspace_id_workspaces_id_fk",
"tableFrom": "topics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -41084,12 +38627,8 @@
"name": "topic_analyses_topic_id_topics_id_fk",
"tableFrom": "topic_analyses",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41097,12 +38636,8 @@
"name": "topic_analyses_user_id_users_id_fk",
"tableFrom": "topic_analyses",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41110,12 +38645,8 @@
"name": "topic_analyses_workspace_id_workspaces_id_fk",
"tableFrom": "topic_analyses",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -41227,12 +38758,8 @@
"name": "topic_comment_mentions_comment_id_topic_comments_id_fk",
"tableFrom": "topic_comment_mentions",
"tableTo": "topic_comments",
- "columnsFrom": [
- "comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["comment_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41240,12 +38767,8 @@
"name": "topic_comment_mentions_mentioned_user_id_users_id_fk",
"tableFrom": "topic_comment_mentions",
"tableTo": "users",
- "columnsFrom": [
- "mentioned_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["mentioned_user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41253,12 +38776,8 @@
"name": "topic_comment_mentions_workspace_id_workspaces_id_fk",
"tableFrom": "topic_comment_mentions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -41556,12 +39075,8 @@
"name": "topic_comments_topic_id_topics_id_fk",
"tableFrom": "topic_comments",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41569,12 +39084,8 @@
"name": "topic_comments_message_id_messages_id_fk",
"tableFrom": "topic_comments",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -41582,12 +39093,8 @@
"name": "topic_comments_parent_comment_id_topic_comments_id_fk",
"tableFrom": "topic_comments",
"tableTo": "topic_comments",
- "columnsFrom": [
- "parent_comment_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_comment_id"],
+ "columnsTo": ["id"],
"onDelete": "no action",
"onUpdate": "no action"
},
@@ -41595,12 +39102,8 @@
"name": "topic_comments_author_user_id_users_id_fk",
"tableFrom": "topic_comments",
"tableTo": "users",
- "columnsFrom": [
- "author_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -41608,12 +39111,8 @@
"name": "topic_comments_workspace_id_workspaces_id_fk",
"tableFrom": "topic_comments",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41621,12 +39120,8 @@
"name": "topic_comments_moderated_by_user_id_users_id_fk",
"tableFrom": "topic_comments",
"tableTo": "users",
- "columnsFrom": [
- "moderated_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["moderated_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -41873,12 +39368,8 @@
"name": "trash_items_root_id_trash_items_id_fk",
"tableFrom": "trash_items",
"tableTo": "trash_items",
- "columnsFrom": [
- "root_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["root_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41886,12 +39377,8 @@
"name": "trash_items_user_id_users_id_fk",
"tableFrom": "trash_items",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41899,12 +39386,8 @@
"name": "trash_items_workspace_id_workspaces_id_fk",
"tableFrom": "trash_items",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -41912,12 +39395,8 @@
"name": "trash_items_deleted_by_user_id_users_id_fk",
"tableFrom": "trash_items",
"tableTo": "users",
- "columnsFrom": [
- "deleted_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["deleted_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -42017,12 +39496,8 @@
"name": "user_settings_id_users_id_fk",
"tableFrom": "user_settings",
"tableTo": "users",
- "columnsFrom": [
- "id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -42277,30 +39752,22 @@
"users_username_unique": {
"name": "users_username_unique",
"nullsNotDistinct": false,
- "columns": [
- "username"
- ]
+ "columns": ["username"]
},
"users_email_unique": {
"name": "users_email_unique",
"nullsNotDistinct": false,
- "columns": [
- "email"
- ]
+ "columns": ["email"]
},
"users_normalized_email_unique": {
"name": "users_normalized_email_unique",
"nullsNotDistinct": false,
- "columns": [
- "normalized_email"
- ]
+ "columns": ["normalized_email"]
},
"users_phone_unique": {
"name": "users_phone_unique",
"nullsNotDistinct": false,
- "columns": [
- "phone"
- ]
+ "columns": ["phone"]
}
},
"policies": {},
@@ -42577,12 +40044,8 @@
"name": "user_memories_activities_user_id_users_id_fk",
"tableFrom": "user_memories_activities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -42590,12 +40053,8 @@
"name": "user_memories_activities_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_activities",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -42603,12 +40062,8 @@
"name": "user_memories_activities_dossier_id_user_memories_dossiers_id_fk",
"tableFrom": "user_memories_activities",
"tableTo": "user_memories_dossiers",
- "columnsFrom": [
- "dossier_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["dossier_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -42822,12 +40277,8 @@
"name": "user_memories_user_id_users_id_fk",
"tableFrom": "user_memories",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -42973,12 +40424,8 @@
"name": "user_memories_context_projects_context_id_user_memories_contexts_id_fk",
"tableFrom": "user_memories_context_projects",
"tableTo": "user_memories_contexts",
- "columnsFrom": [
- "context_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["context_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -42986,12 +40433,8 @@
"name": "user_memories_context_projects_project_id_projects_id_fk",
"tableFrom": "user_memories_context_projects",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -42999,12 +40442,8 @@
"name": "user_memories_context_projects_user_id_users_id_fk",
"tableFrom": "user_memories_context_projects",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -43280,12 +40719,8 @@
"name": "user_memories_contexts_user_id_users_id_fk",
"tableFrom": "user_memories_contexts",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43293,12 +40728,8 @@
"name": "user_memories_contexts_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_contexts",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -43577,12 +41008,8 @@
"name": "user_memories_dossiers_context_id_user_memories_contexts_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "user_memories_contexts",
- "columnsFrom": [
- "context_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["context_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -43590,12 +41017,8 @@
"name": "user_memories_dossiers_user_id_users_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43603,12 +41026,8 @@
"name": "user_memories_dossiers_workspace_id_workspaces_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43616,12 +41035,8 @@
"name": "user_memories_dossiers_agent_id_agents_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43629,12 +41044,8 @@
"name": "user_memories_dossiers_project_id_projects_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43642,12 +41053,8 @@
"name": "user_memories_dossiers_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_dossiers",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -43831,12 +41238,8 @@
"name": "user_memories_edges_source_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_edges",
"tableTo": "user_memories",
- "columnsFrom": [
- "source_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43844,12 +41247,8 @@
"name": "user_memories_edges_target_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_edges",
"tableTo": "user_memories",
- "columnsFrom": [
- "target_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["target_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43857,12 +41256,8 @@
"name": "user_memories_edges_user_id_users_id_fk",
"tableFrom": "user_memories_edges",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -43870,12 +41265,8 @@
"name": "user_memories_edges_workspace_id_workspaces_id_fk",
"tableFrom": "user_memories_edges",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -44152,12 +41543,8 @@
"name": "user_memories_entities_parent_entity_id_user_memories_entities_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "user_memories_entities",
- "columnsFrom": [
- "parent_entity_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_entity_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -44165,12 +41552,8 @@
"name": "user_memories_entities_user_id_users_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44178,12 +41561,8 @@
"name": "user_memories_entities_workspace_id_workspaces_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44191,12 +41570,8 @@
"name": "user_memories_entities_agent_id_agents_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44204,12 +41579,8 @@
"name": "user_memories_entities_project_id_projects_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44217,12 +41588,8 @@
"name": "user_memories_entities_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_entities",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -44385,12 +41752,8 @@
"name": "user_memories_entity_names_entity_id_user_memories_entities_id_fk",
"tableFrom": "user_memories_entity_names",
"tableTo": "user_memories_entities",
- "columnsFrom": [
- "entity_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["entity_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44398,12 +41761,8 @@
"name": "user_memories_entity_names_user_id_users_id_fk",
"tableFrom": "user_memories_entity_names",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44411,12 +41770,8 @@
"name": "user_memories_entity_names_workspace_id_workspaces_id_fk",
"tableFrom": "user_memories_entity_names",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44424,12 +41779,8 @@
"name": "user_memories_entity_names_source_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_entity_names",
"tableTo": "user_memories",
- "columnsFrom": [
- "source_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -44664,12 +42015,8 @@
"name": "user_memories_experiences_user_id_users_id_fk",
"tableFrom": "user_memories_experiences",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44677,12 +42024,8 @@
"name": "user_memories_experiences_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_experiences",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -44881,12 +42224,8 @@
"name": "user_memories_identities_user_id_users_id_fk",
"tableFrom": "user_memories_identities",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44894,12 +42233,8 @@
"name": "user_memories_identities_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_identities",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -44907,12 +42242,8 @@
"name": "user_memories_identities_entity_id_user_memories_entities_id_fk",
"tableFrom": "user_memories_identities",
"tableTo": "user_memories_entities",
- "columnsFrom": [
- "entity_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["entity_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -45094,12 +42425,8 @@
"name": "user_memories_operations_user_id_users_id_fk",
"tableFrom": "user_memories_operations",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -45107,12 +42434,8 @@
"name": "user_memories_operations_workspace_id_workspaces_id_fk",
"tableFrom": "user_memories_operations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -45312,12 +42635,8 @@
"name": "user_memory_persona_document_histories_user_id_users_id_fk",
"tableFrom": "user_memory_persona_document_histories",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -45325,12 +42644,8 @@
"name": "user_memory_persona_document_histories_persona_id_user_memory_persona_documents_id_fk",
"tableFrom": "user_memory_persona_document_histories",
"tableTo": "user_memory_persona_documents",
- "columnsFrom": [
- "persona_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["persona_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -45473,12 +42788,8 @@
"name": "user_memory_persona_documents_user_id_users_id_fk",
"tableFrom": "user_memory_persona_documents",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -45703,12 +43014,8 @@
"name": "user_memories_preferences_user_id_users_id_fk",
"tableFrom": "user_memories_preferences",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -45716,12 +43023,8 @@
"name": "user_memories_preferences_user_memory_id_user_memories_id_fk",
"tableFrom": "user_memories_preferences",
"tableTo": "user_memories",
- "columnsFrom": [
- "user_memory_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -45729,12 +43032,8 @@
"name": "user_memories_preferences_holder_entity_id_user_memories_entities_id_fk",
"tableFrom": "user_memories_preferences",
"tableTo": "user_memories_entities",
- "columnsFrom": [
- "holder_entity_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["holder_entity_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -45742,12 +43041,8 @@
"name": "user_memories_preferences_applies_to_entity_id_user_memories_entities_id_fk",
"tableFrom": "user_memories_preferences",
"tableTo": "user_memories_entities",
- "columnsFrom": [
- "applies_to_entity_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["applies_to_entity_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -46037,12 +43332,8 @@
"name": "acceptances_user_id_users_id_fk",
"tableFrom": "acceptances",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46050,12 +43341,8 @@
"name": "acceptances_workspace_id_workspaces_id_fk",
"tableFrom": "acceptances",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46063,12 +43350,8 @@
"name": "acceptances_project_id_projects_id_fk",
"tableFrom": "acceptances",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -46455,12 +43738,8 @@
"name": "verify_check_results_verify_run_id_verify_runs_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "verify_runs",
- "columnsFrom": [
- "verify_run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["verify_run_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46468,12 +43747,8 @@
"name": "verify_check_results_operation_id_agent_operations_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46481,12 +43756,8 @@
"name": "verify_check_results_user_id_users_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46494,12 +43765,8 @@
"name": "verify_check_results_workspace_id_workspaces_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46507,12 +43774,8 @@
"name": "verify_check_results_source_criterion_id_verify_criteria_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "verify_criteria",
- "columnsFrom": [
- "source_criterion_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_criterion_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46520,12 +43783,8 @@
"name": "verify_check_results_verifier_operation_id_agent_operations_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "agent_operations",
- "columnsFrom": [
- "verifier_operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["verifier_operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46533,12 +43792,8 @@
"name": "verify_check_results_verifier_tracing_id_llm_generation_tracing_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "llm_generation_tracing",
- "columnsFrom": [
- "verifier_tracing_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["verifier_tracing_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46546,12 +43801,8 @@
"name": "verify_check_results_repair_operation_id_agent_operations_id_fk",
"tableFrom": "verify_check_results",
"tableTo": "agent_operations",
- "columnsFrom": [
- "repair_operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["repair_operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -46738,12 +43989,8 @@
"name": "verify_criteria_user_id_users_id_fk",
"tableFrom": "verify_criteria",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46751,12 +43998,8 @@
"name": "verify_criteria_document_id_documents_id_fk",
"tableFrom": "verify_criteria",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46764,12 +44007,8 @@
"name": "verify_criteria_workspace_id_workspaces_id_fk",
"tableFrom": "verify_criteria",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -46947,12 +44186,8 @@
"name": "verify_evidence_check_result_id_verify_check_results_id_fk",
"tableFrom": "verify_evidence",
"tableTo": "verify_check_results",
- "columnsFrom": [
- "check_result_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["check_result_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46960,12 +44195,8 @@
"name": "verify_evidence_document_id_documents_id_fk",
"tableFrom": "verify_evidence",
"tableTo": "documents",
- "columnsFrom": [
- "document_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46973,12 +44204,8 @@
"name": "verify_evidence_file_id_files_id_fk",
"tableFrom": "verify_evidence",
"tableTo": "files",
- "columnsFrom": [
- "file_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -46986,12 +44213,8 @@
"name": "verify_evidence_user_id_users_id_fk",
"tableFrom": "verify_evidence",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -46999,12 +44222,8 @@
"name": "verify_evidence_workspace_id_workspaces_id_fk",
"tableFrom": "verify_evidence",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -47194,12 +44413,8 @@
"name": "verify_reports_verify_run_id_verify_runs_id_fk",
"tableFrom": "verify_reports",
"tableTo": "verify_runs",
- "columnsFrom": [
- "verify_run_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["verify_run_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47207,12 +44422,8 @@
"name": "verify_reports_operation_id_agent_operations_id_fk",
"tableFrom": "verify_reports",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -47220,12 +44431,8 @@
"name": "verify_reports_user_id_users_id_fk",
"tableFrom": "verify_reports",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47233,12 +44440,8 @@
"name": "verify_reports_workspace_id_workspaces_id_fk",
"tableFrom": "verify_reports",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -47488,12 +44691,8 @@
"name": "verify_review_predictions_check_result_id_verify_check_results_id_fk",
"tableFrom": "verify_review_predictions",
"tableTo": "verify_check_results",
- "columnsFrom": [
- "check_result_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["check_result_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47501,12 +44700,8 @@
"name": "verify_review_predictions_user_id_users_id_fk",
"tableFrom": "verify_review_predictions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47514,12 +44709,8 @@
"name": "verify_review_predictions_workspace_id_workspaces_id_fk",
"tableFrom": "verify_review_predictions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -47629,12 +44820,8 @@
"name": "verify_rubric_criteria_rubric_id_verify_rubrics_id_fk",
"tableFrom": "verify_rubric_criteria",
"tableTo": "verify_rubrics",
- "columnsFrom": [
- "rubric_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["rubric_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47642,12 +44829,8 @@
"name": "verify_rubric_criteria_criterion_id_verify_criteria_id_fk",
"tableFrom": "verify_rubric_criteria",
"tableTo": "verify_criteria",
- "columnsFrom": [
- "criterion_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["criterion_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47655,12 +44838,8 @@
"name": "verify_rubric_criteria_user_id_users_id_fk",
"tableFrom": "verify_rubric_criteria",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47668,12 +44847,8 @@
"name": "verify_rubric_criteria_workspace_id_workspaces_id_fk",
"tableFrom": "verify_rubric_criteria",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -47681,10 +44856,7 @@
"compositePrimaryKeys": {
"verify_rubric_criteria_rubric_id_criterion_id_pk": {
"name": "verify_rubric_criteria_rubric_id_criterion_id_pk",
- "columns": [
- "rubric_id",
- "criterion_id"
- ]
+ "columns": ["rubric_id", "criterion_id"]
}
},
"uniqueConstraints": {},
@@ -47793,12 +44965,8 @@
"name": "verify_rubrics_user_id_users_id_fk",
"tableFrom": "verify_rubrics",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -47806,12 +44974,8 @@
"name": "verify_rubrics_workspace_id_workspaces_id_fk",
"tableFrom": "verify_rubrics",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -48083,12 +45247,8 @@
"name": "verify_runs_user_id_users_id_fk",
"tableFrom": "verify_runs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48096,12 +45256,8 @@
"name": "verify_runs_workspace_id_workspaces_id_fk",
"tableFrom": "verify_runs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48109,12 +45265,8 @@
"name": "verify_runs_acceptance_id_acceptances_id_fk",
"tableFrom": "verify_runs",
"tableTo": "acceptances",
- "columnsFrom": [
- "acceptance_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -48122,12 +45274,8 @@
"name": "verify_runs_operation_id_agent_operations_id_fk",
"tableFrom": "verify_runs",
"tableTo": "agent_operations",
- "columnsFrom": [
- "operation_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -48333,12 +45481,8 @@
"name": "widget_runs_widget_id_widgets_id_fk",
"tableFrom": "widget_runs",
"tableTo": "widgets",
- "columnsFrom": [
- "widget_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["widget_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48346,12 +45490,8 @@
"name": "widget_runs_version_id_widget_versions_id_fk",
"tableFrom": "widget_runs",
"tableTo": "widget_versions",
- "columnsFrom": [
- "version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["version_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48359,12 +45499,8 @@
"name": "widget_runs_user_id_users_id_fk",
"tableFrom": "widget_runs",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48372,12 +45508,8 @@
"name": "widget_runs_workspace_id_workspaces_id_fk",
"tableFrom": "widget_runs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -48638,12 +45770,8 @@
"name": "widget_versions_widget_id_widgets_id_fk",
"tableFrom": "widget_versions",
"tableTo": "widgets",
- "columnsFrom": [
- "widget_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["widget_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48651,12 +45779,8 @@
"name": "widget_versions_user_id_users_id_fk",
"tableFrom": "widget_versions",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48664,12 +45788,8 @@
"name": "widget_versions_workspace_id_workspaces_id_fk",
"tableFrom": "widget_versions",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -48677,12 +45797,8 @@
"name": "widget_versions_published_by_user_id_users_id_fk",
"tableFrom": "widget_versions",
"tableTo": "users",
- "columnsFrom": [
- "published_by_user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["published_by_user_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -48690,12 +45806,8 @@
"name": "widget_versions_source_agent_id_agents_id_fk",
"tableFrom": "widget_versions",
"tableTo": "agents",
- "columnsFrom": [
- "source_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -48703,12 +45815,8 @@
"name": "widget_versions_source_topic_id_topics_id_fk",
"tableFrom": "widget_versions",
"tableTo": "topics",
- "columnsFrom": [
- "source_topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["source_topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -48716,12 +45824,8 @@
"name": "widget_versions_parent_version_id_widget_versions_id_fk",
"tableFrom": "widget_versions",
"tableTo": "widget_versions",
- "columnsFrom": [
- "parent_version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["parent_version_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -49091,12 +46195,8 @@
"name": "widgets_user_id_users_id_fk",
"tableFrom": "widgets",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49104,12 +46204,8 @@
"name": "widgets_workspace_id_workspaces_id_fk",
"tableFrom": "widgets",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49117,12 +46213,8 @@
"name": "widgets_project_id_projects_id_fk",
"tableFrom": "widgets",
"tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49130,12 +46222,8 @@
"name": "widgets_agent_id_agents_id_fk",
"tableFrom": "widgets",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49143,12 +46231,8 @@
"name": "widgets_published_version_id_widget_versions_id_fk",
"tableFrom": "widgets",
"tableTo": "widget_versions",
- "columnsFrom": [
- "published_version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["published_version_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49156,12 +46240,8 @@
"name": "widgets_draft_version_id_widget_versions_id_fk",
"tableFrom": "widgets",
"tableTo": "widget_versions",
- "columnsFrom": [
- "draft_version_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["draft_version_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49169,12 +46249,8 @@
"name": "widgets_metric_id_metrics_id_fk",
"tableFrom": "widgets",
"tableTo": "metrics",
- "columnsFrom": [
- "metric_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["metric_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -49488,12 +46564,8 @@
"name": "work_versions_work_id_works_id_fk",
"tableFrom": "work_versions",
"tableTo": "works",
- "columnsFrom": [
- "work_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["work_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49501,12 +46573,8 @@
"name": "work_versions_topic_id_topics_id_fk",
"tableFrom": "work_versions",
"tableTo": "topics",
- "columnsFrom": [
- "topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49514,12 +46582,8 @@
"name": "work_versions_thread_id_threads_id_fk",
"tableFrom": "work_versions",
"tableTo": "threads",
- "columnsFrom": [
- "thread_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49527,12 +46591,8 @@
"name": "work_versions_message_id_messages_id_fk",
"tableFrom": "work_versions",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49540,12 +46600,8 @@
"name": "work_versions_agent_id_agents_id_fk",
"tableFrom": "work_versions",
"tableTo": "agents",
- "columnsFrom": [
- "agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -49934,12 +46990,8 @@
"name": "works_origin_topic_id_topics_id_fk",
"tableFrom": "works",
"tableTo": "topics",
- "columnsFrom": [
- "origin_topic_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["origin_topic_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49947,12 +46999,8 @@
"name": "works_origin_thread_id_threads_id_fk",
"tableFrom": "works",
"tableTo": "threads",
- "columnsFrom": [
- "origin_thread_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["origin_thread_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49960,12 +47008,8 @@
"name": "works_origin_agent_id_agents_id_fk",
"tableFrom": "works",
"tableTo": "agents",
- "columnsFrom": [
- "origin_agent_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["origin_agent_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
},
@@ -49973,12 +47017,8 @@
"name": "works_user_id_users_id_fk",
"tableFrom": "works",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -49986,12 +47026,8 @@
"name": "works_workspace_id_workspaces_id_fk",
"tableFrom": "works",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50115,12 +47151,8 @@
"name": "workspace_audit_logs_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_audit_logs",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50267,12 +47299,8 @@
"name": "workspace_invitations_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_invitations",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50280,12 +47308,8 @@
"name": "workspace_invitations_inviter_id_users_id_fk",
"tableFrom": "workspace_invitations",
"tableTo": "users",
- "columnsFrom": [
- "inviter_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["inviter_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50295,9 +47319,7 @@
"workspace_invitations_token_unique": {
"name": "workspace_invitations_token_unique",
"nullsNotDistinct": false,
- "columns": [
- "token"
- ]
+ "columns": ["token"]
}
},
"policies": {},
@@ -50398,12 +47420,8 @@
"name": "workspace_members_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_members",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50411,12 +47429,8 @@
"name": "workspace_members_user_id_users_id_fk",
"tableFrom": "workspace_members",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50424,10 +47438,7 @@
"compositePrimaryKeys": {
"workspace_members_workspace_id_user_id_pk": {
"name": "workspace_members_workspace_id_user_id_pk",
- "columns": [
- "workspace_id",
- "user_id"
- ]
+ "columns": ["workspace_id", "user_id"]
}
},
"uniqueConstraints": {},
@@ -50543,12 +47554,8 @@
"name": "workspace_team_members_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_team_members",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50556,12 +47563,8 @@
"name": "workspace_team_members_user_id_users_id_fk",
"tableFrom": "workspace_team_members",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50569,14 +47572,8 @@
"name": "workspace_team_members_team_workspace_fk",
"tableFrom": "workspace_team_members",
"tableTo": "workspace_teams",
- "columnsFrom": [
- "team_id",
- "workspace_id"
- ],
- "columnsTo": [
- "id",
- "workspace_id"
- ],
+ "columnsFrom": ["team_id", "workspace_id"],
+ "columnsTo": ["id", "workspace_id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50706,12 +47703,8 @@
"name": "workspace_teams_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_teams",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50719,12 +47712,8 @@
"name": "workspace_teams_created_by_users_id_fk",
"tableFrom": "workspace_teams",
"tableTo": "users",
- "columnsFrom": [
- "created_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["created_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -50734,10 +47723,7 @@
"workspace_teams_id_workspace_unique": {
"name": "workspace_teams_id_workspace_unique",
"nullsNotDistinct": false,
- "columns": [
- "id",
- "workspace_id"
- ]
+ "columns": ["id", "workspace_id"]
}
},
"policies": {},
@@ -50832,12 +47818,8 @@
"name": "workspace_user_settings_workspace_id_workspaces_id_fk",
"tableFrom": "workspace_user_settings",
"tableTo": "workspaces",
- "columnsFrom": [
- "workspace_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -50845,12 +47827,8 @@
"name": "workspace_user_settings_user_id_users_id_fk",
"tableFrom": "workspace_user_settings",
"tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50979,12 +47957,8 @@
"name": "workspaces_primary_owner_id_users_id_fk",
"tableFrom": "workspaces",
"tableTo": "users",
- "columnsFrom": [
- "primary_owner_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["primary_owner_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -50996,26 +47970,6 @@
"isRLSEnabled": false
}
},
- "enums": {},
- "schemas": {},
- "sequences": {
- "public.fts_search_sync_revision_seq": {
- "name": "fts_search_sync_revision_seq",
- "schema": "public",
- "increment": "1",
- "startWith": "1",
- "minValue": "1",
- "maxValue": "9223372036854775807",
- "cache": "1",
- "cycle": false
- }
- },
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
+ "version": "7",
+ "views": {}
+}
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx
index d03cde757ab..61f75cef006 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx
@@ -1,100 +1,76 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import type { AskUserQuestionItem } from './types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- // Codex-style flat summary: the question keeps the body text color and the
- // answer drops to tertiary — the exchange reads as a quiet process record,
- // not an interactive control. No chips, icons, or borders. Tertiary (not
- // secondary) so the question/answer hierarchy stays legible at a glance.
- answer: css`
- font-size: 14px;
- line-height: 1.5;
- color: ${cssVar.colorTextTertiary};
- overflow-wrap: anywhere;
- `,
- container: css`
- padding-block: 8px 4px;
- `,
- divider: css`
- align-self: stretch;
- height: 1px;
- margin-block: 4px;
- background: ${cssVar.colorFillSecondary};
- `,
- header: css`
- flex-shrink: 0;
-
- padding-inline: 8px;
- border-radius: 4px;
-
- font-size: 12px;
- font-weight: 400;
- line-height: 20px;
- color: ${cssVar.colorTextTertiary};
- white-space: nowrap;
-
- background: ${cssVar.colorFillQuaternary};
- `,
- ordinal: css`
- flex-shrink: 0;
-
- box-sizing: border-box;
- width: 28px;
- height: 20px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- line-height: 20px;
- color: ${cssVar.colorTextTertiary};
- text-align: center;
-
- background: ${cssVar.colorFillQuaternary};
- `,
- question: css`
- font-size: 14px;
- font-weight: 400;
- line-height: 1.5;
- color: ${cssVar.colorText};
- overflow-wrap: anywhere;
- `,
- questionContent: css`
- min-width: 0;
- `,
- // Mirrors OptionCard's recommended pill so the marker reads the same in the
- // form and in the completed summary.
- recommendedBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 11px;
- line-height: 18px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillSecondary};
- `,
- titleRow: css`
- display: flex;
- flex-wrap: wrap;
- gap: 8px;
- align-items: baseline;
- `,
- unanswered: css`
- font-size: 14px;
- line-height: 1.5;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ answer: {
+ fontSize: '14px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextTertiary,
+ overflowWrap: 'anywhere',
+ },
+ container: { paddingBlockStart: '8px', paddingBlockEnd: '4px' },
+ divider: {
+ alignSelf: 'stretch',
+ height: '1px',
+ marginBlock: '4px',
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ header: {
+ flexShrink: 0,
+ paddingInline: '8px',
+ borderRadius: '4px',
+ fontSize: '12px',
+ fontWeight: 400,
+ lineHeight: '20px',
+ color: cssVar.colorTextTertiary,
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ ordinal: {
+ flexShrink: 0,
+ boxSizing: 'border-box',
+ width: '28px',
+ height: '20px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: '20px',
+ color: cssVar.colorTextTertiary,
+ textAlign: 'center',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ question: {
+ fontSize: '14px',
+ fontWeight: 400,
+ lineHeight: 1.5,
+ color: cssVar.colorText,
+ overflowWrap: 'anywhere',
+ },
+ questionContent: { minWidth: '0' },
+ recommendedBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '11px',
+ lineHeight: '18px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ titleRow: { display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'baseline' },
+ unanswered: { fontSize: '14px', lineHeight: 1.5, color: cssVar.colorTextQuaternary },
+});
export interface AskUserQuestionResultLabels {
noAnswer: string;
@@ -120,23 +96,25 @@ const QuestionAnswer = memo<QuestionAnswerProps>(
return (
<Flexbox align="flex-start" gap={8} horizontal={!!index}>
- {!!index && <span className={styles.ordinal}>{`Q${index}`}</span>}
- <Flexbox className={styles.questionContent} flex={1} gap={4}>
- <div className={index ? styles.titleRow : undefined}>
- <span className={styles.question}>{question.question}</span>
- {!!index && question.header && <span className={styles.header}>{question.header}</span>}
+ {!!index && <span {...stylex.props(styles.ordinal)}>{`Q${index}`}</span>}
+ <Flexbox className={stylex.props(styles.questionContent).className} flex={1} gap={4}>
+ <div {...stylex.props(index ? styles.titleRow : undefined)}>
+ <span {...stylex.props(styles.question)}>{question.question}</span>
+ {!!index && question.header && (
+ <span {...stylex.props(styles.header)}>{question.header}</span>
+ )}
</div>
{labels.length > 0 ? (
labels.map((label) => (
<Flexbox horizontal align="center" gap={8} key={label}>
- <span className={styles.answer}>{label}</span>
+ <span {...stylex.props(styles.answer)}>{label}</span>
{isRecommended(label) && (
- <span className={styles.recommendedBadge}>{recommendedTag}</span>
+ <span {...stylex.props(styles.recommendedBadge)}>{recommendedTag}</span>
)}
</Flexbox>
))
) : (
- <span className={styles.unanswered}>{notAnswered}</span>
+ <span {...stylex.props(styles.unanswered)}>{notAnswered}</span>
)}
</Flexbox>
</Flexbox>
@@ -169,7 +147,7 @@ export const AskUserQuestionResult = memo<AskUserQuestionResultProps>(
if (freeformText) {
return (
- <Flexbox className={styles.container} gap={16}>
+ <Flexbox className={stylex.props(styles.container).className} gap={16}>
{questions.map((question, index) => (
<Flexbox
align="flex-start"
@@ -177,26 +155,26 @@ export const AskUserQuestionResult = memo<AskUserQuestionResultProps>(
horizontal={multiple}
key={`${question.question}-${index}`}
>
- {multiple && <span className={styles.ordinal}>{`Q${index + 1}`}</span>}
+ {multiple && <span {...stylex.props(styles.ordinal)}>{`Q${index + 1}`}</span>}
<div
- className={`${styles.questionContent} ${multiple ? styles.titleRow : ''}`.trim()}
+ className={`${stylex.props(styles.questionContent).className} ${multiple ? stylex.props(styles.titleRow).className : ''}`.trim()}
>
- <span className={styles.question}>{question.question}</span>
+ <span {...stylex.props(styles.question)}>{question.question}</span>
{multiple && question.header && (
- <span className={styles.header}>{question.header}</span>
+ <span {...stylex.props(styles.header)}>{question.header}</span>
)}
</div>
</Flexbox>
))}
- {multiple && <div className={styles.divider} />}
- <span className={styles.answer}>{freeformText}</span>
+ {multiple && <div {...stylex.props(styles.divider)} />}
+ <span {...stylex.props(styles.answer)}>{freeformText}</span>
{isError && <Text type="warning">{labels.noAnswer}</Text>}
</Flexbox>
);
}
return (
- <Flexbox className={styles.container} gap={16}>
+ <Flexbox className={stylex.props(styles.container).className} gap={16}>
{questions.map((question, index) => (
<QuestionAnswer
answer={answers?.[question.question]}
@@ -209,8 +187,8 @@ export const AskUserQuestionResult = memo<AskUserQuestionResultProps>(
))}
{supplementText && (
<Flexbox gap={4}>
- <span className={styles.header}>{labels.supplement}</span>
- <span className={styles.answer}>{supplementText}</span>
+ <span {...stylex.props(styles.header)}>{labels.supplement}</span>
+ <span {...stylex.props(styles.answer)}>{supplementText}</span>
</Flexbox>
)}
{isError && <Text type="warning">{labels.noAnswer}</Text>}
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
index 693b6001e32..f296beb2d80 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
@@ -1,45 +1,31 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Text, TextArea } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { Flexbox, Text, TextArea } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { OptionCard } from '../components';
import type { AskUserQuestionItem } from './types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- // Per-question "write your own" input — sits as the last row in the option
- // stack, carrying the next sequential number so it reads as one more choice
- // rather than a separate control.
- customRow: css`
- margin-block-start: 2px;
-
- /* Align the chip under the option number chips (OptionCard padding-inline);
- the input itself runs to the option cards' right edge, flush with the
- submit button below. */
- padding-inline-start: 12px;
- `,
- // Mirrors OptionCard's `optionIndex` chip so the free-text row's number reads
- // identically to the numbered options above it.
- index: css`
- flex-shrink: 0;
-
- box-sizing: border-box;
- width: 22px;
- height: 22px;
- border-radius: 6px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- font-weight: 600;
- line-height: 22px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ customRow: { marginBlockStart: '2px', paddingInlineStart: '12px' },
+ index: {
+ flexShrink: 0,
+ boxSizing: 'border-box',
+ width: '22px',
+ height: '22px',
+ borderRadius: '6px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ fontWeight: 600,
+ lineHeight: '22px',
+ color: cssVar.colorTextSecondary,
+ textAlign: 'center',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface QuestionPanelProps {
/** The picked option id(s), falling back to labels for legacy options. */
@@ -135,8 +121,13 @@ export const QuestionPanel = memo<QuestionPanelProps>(
})}
{/* Last item: let the user write their own answer for this question.
Numbered as the next option so it reads as one more choice. */}
- <Flexbox horizontal align="center" className={styles.customRow} gap={12}>
- <span className={styles.index}>{question.options.length + 1}</span>
+ <Flexbox
+ horizontal
+ align="center"
+ className={stylex.props(styles.customRow).className}
+ gap={12}
+ >
+ <span {...stylex.props(styles.index)}>{question.options.length + 1}</span>
<TextArea
autoSize={{ maxRows: 4, minRows: 1 }}
disabled={disabled}
diff --git a/packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx b/packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx
index 5fc6f5d9a6c..db7903aa4a5 100644
--- a/packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx
+++ b/packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx
@@ -2,9 +2,9 @@
import type { EditFileState } from '@lobechat/tool-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Minus, Plus } from 'lucide-react';
import type { ReactNode } from 'react';
import { memo } from 'react';
@@ -13,12 +13,9 @@ import { useTranslation } from 'react-i18next';
import { FilePathDisplay } from '../../components/FilePathDisplay';
import { inspectorTextStyles, shinyTextStyles } from '../../styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- separator: css`
- margin-inline: 2px;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+const styles = stylex.create({
+ separator: { marginInline: '2px', color: cssVar.colorTextQuaternary },
+});
interface EditFileArgs {
all?: boolean;
@@ -92,7 +89,7 @@ export const EditLocalFileInspector = memo<EditLocalFileInspectorProps>(
{' '}
{statsParts.map((part, index) => (
<span key={index}>
- {index > 0 && <span className={styles.separator}> / </span>}
+ {index > 0 && <span {...stylex.props(styles.separator)}> / </span>}
{part}
</span>
))}
diff --git a/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx b/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx
index 87e79cc8da0..23a4983afe1 100644
--- a/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx
+++ b/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx
@@ -2,34 +2,30 @@
import type { GlobFilesState } from '@lobechat/tool-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '../../styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- baseline: css`
- align-items: baseline;
- `,
- statusIcon: css`
- align-self: center;
- margin-inline-start: 4px;
- `,
- tag: css`
- margin-inline-start: 6px;
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ baseline: { alignItems: 'baseline' },
+ statusIcon: { alignSelf: 'center', marginInlineStart: '4px' },
+ tag: {
+ marginInlineStart: '6px',
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface GlobFilesArgs {
directory?: string;
@@ -52,9 +48,9 @@ export const createGlobLocalFilesInspector = (translationKey: string) => {
);
return (
- <div className={cx(inspectorTextStyles.root, styles.baseline)}>
+ <div className={cx(stylex.props(styles.baseline).className, inspectorTextStyles.root)}>
<span className={shinyTextStyles.shinyText}>{t(translationKey as any)}:</span>
- <span className={styles.tag}>{pattern}</span>
+ <span {...stylex.props(styles.tag)}>{pattern}</span>
</div>
);
}
@@ -62,16 +58,24 @@ export const createGlobLocalFilesInspector = (translationKey: string) => {
const hasFiles = (pluginState?.totalCount ?? 0) > 0;
return (
- <div className={cx(inspectorTextStyles.root, styles.baseline)}>
+ <div className={cx(stylex.props(styles.baseline).className, inspectorTextStyles.root)}>
<span className={cx(isLoading && shinyTextStyles.shinyText)}>
{t(translationKey as any)}:
</span>
- {pattern && <span className={styles.tag}>{pattern}</span>}
+ {pattern && <span {...stylex.props(styles.tag)}>{pattern}</span>}
{isLoading ? null : pluginState ? (
hasFiles ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
)
) : null}
</div>
diff --git a/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx b/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx
index de803b3d37b..64c8e7827b6 100644
--- a/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx
+++ b/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx
@@ -2,7 +2,9 @@
import type { RunCommandState } from '@lobechat/tool-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Target, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,34 +12,25 @@ import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '../../styles';
import { type GoalCommand, isGoalCommandFailed } from '../../utils/goalCommand';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- flex-shrink: 1;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- icon: css`
- flex-shrink: 0;
- margin-inline-end: 6px;
- color: ${cssVar.colorTextDescription};
- `,
- statusIcon: css`
- flex-shrink: 0;
- margin-inline-start: 4px;
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ flexShrink: 1,
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ icon: { flexShrink: 0, marginInlineEnd: '6px', color: cssVar.colorTextDescription },
+ statusIcon: { flexShrink: 0, marginInlineStart: '4px' },
+});
export interface GoalCommandInspectorProps extends BuiltinInspectorProps<
{ command?: string },
@@ -62,12 +55,18 @@ export const GoalCommandInspector = memo<GoalCommandInspectorProps>(
return (
<div className={inspectorTextStyles.root}>
- <Target className={styles.icon} size={14} />
+ <Target className={stylex.props(styles.icon).className} size={14} />
<span className={cx(inFlight && shinyTextStyles.shinyText)}>
{t(`builtins.goalCommand.${goalCommand.kind}.${status}` as any)}
</span>
- {title && <span className={styles.chip}>{title}</span>}
- {failed && <X className={styles.statusIcon} color={cssVar.colorError} size={14} />}
+ {title && <span {...stylex.props(styles.chip)}>{title}</span>}
+ {failed && (
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
+ )}
</div>
);
},
diff --git a/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx b/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx
index 22cd6c8db2d..5a03786764e 100644
--- a/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx
+++ b/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx
@@ -2,44 +2,37 @@
import type { GrepContentState } from '@lobechat/tool-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Fragment, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '../../styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- baseline: css`
- align-items: baseline;
- `,
- separator: css`
- margin-inline: 2px;
- color: ${cssVar.colorTextQuaternary};
- `,
- tag: css`
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 4px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
- tagsList: css`
- display: inline-flex;
- flex-shrink: 1;
- gap: 4px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
-
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ baseline: { alignItems: 'baseline' },
+ separator: { marginInline: '2px', color: cssVar.colorTextQuaternary },
+ tag: {
+ paddingBlock: '1px',
+ paddingInline: '6px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ tagsList: {
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '4px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ whiteSpace: 'nowrap',
+ },
+});
const splitPattern = (pattern: string): string[] =>
pattern
@@ -52,11 +45,11 @@ const PatternTags = memo<{ pattern: string }>(({ pattern }) => {
if (parts.length === 0) return null;
return (
- <span className={styles.tagsList}>
+ <span {...stylex.props(styles.tagsList)}>
{parts.map((part, index) => (
<Fragment key={`${index}-${part}`}>
- {index > 0 && <span className={styles.separator}>|</span>}
- <span className={styles.tag}>{part}</span>
+ {index > 0 && <span {...stylex.props(styles.separator)}>|</span>}
+ <span {...stylex.props(styles.tag)}>{part}</span>
</Fragment>
))}
</span>
@@ -94,7 +87,7 @@ export const createGrepContentInspector = ({
);
return (
- <div className={cx(inspectorTextStyles.root, styles.baseline)}>
+ <div className={cx(stylex.props(styles.baseline).className, inspectorTextStyles.root)}>
<span className={shinyTextStyles.shinyText}>{t(translationKey as any)}:</span>
<PatternTags pattern={pattern} />
</div>
@@ -105,7 +98,7 @@ export const createGrepContentInspector = ({
const hasResults = resultCount > 0;
return (
- <div className={cx(inspectorTextStyles.root, styles.baseline)}>
+ <div className={cx(stylex.props(styles.baseline).className, inspectorTextStyles.root)}>
<span className={cx(isLoading && shinyTextStyles.shinyText)}>
{t(translationKey as any)}:
</span>
diff --git a/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx b/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx
index 61690b240b3..c2bc46f17f3 100644
--- a/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx
+++ b/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx
@@ -2,7 +2,9 @@
import type { RunCommandState } from '@lobechat/tool-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check, SquareChevronRight, X } from 'lucide-react';
import { type ComponentType, memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,47 +12,34 @@ import { useTranslation } from 'react-i18next';
import { inspectorTextStyles, shinyTextStyles } from '../../styles';
import { getRunCommandDisplayCommand } from '../../utils/runCommand';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- overflow: hidden;
- display: inline-flex;
- flex-shrink: 1;
- gap: 6px;
- align-items: center;
-
- min-width: 0;
- margin-inline-start: 6px;
- padding-block: 2px;
- padding-inline: 10px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- command: css`
- overflow: hidden;
-
- min-width: 0;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- leadingIcon: css`
- flex-shrink: 0;
- margin-inline-end: 6px;
- color: ${cssVar.colorTextDescription};
- `,
- statusIcon: css`
- flex-shrink: 0;
- margin-inline-start: 4px;
- `,
- terminalIcon: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextDescription};
- `,
-}));
+const styles = stylex.create({
+ chip: {
+ overflow: 'hidden',
+ display: 'inline-flex',
+ flexShrink: 1,
+ gap: '6px',
+ alignItems: 'center',
+ minWidth: '0',
+ marginInlineStart: '6px',
+ paddingBlock: '2px',
+ paddingInline: '10px',
+ borderRadius: '999px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ command: {
+ overflow: 'hidden',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ leadingIcon: { flexShrink: 0, marginInlineEnd: '6px', color: cssVar.colorTextDescription },
+ statusIcon: { flexShrink: 0, marginInlineStart: '4px' },
+ terminalIcon: { flexShrink: 0, color: cssVar.colorTextDescription },
+});
interface RunCommandArgs {
background?: boolean;
@@ -89,9 +78,11 @@ export const RunCommandInspector = memo<RunCommandInspectorProps>(
const description = args?.description || partialArgs?.description || command;
// Brand icon leads the row (before the label); otherwise the terminal glyph sits in the chip.
- const leading = BrandIcon ? <BrandIcon className={styles.leadingIcon} size={14} /> : null;
+ const leading = BrandIcon ? (
+ <BrandIcon className={stylex.props(styles.leadingIcon).className} size={14} />
+ ) : null;
const chipIcon = BrandIcon ? null : (
- <SquareChevronRight className={styles.terminalIcon} size={14} />
+ <SquareChevronRight className={stylex.props(styles.terminalIcon).className} size={14} />
);
if (isArgumentsStreaming) {
@@ -107,9 +98,9 @@ export const RunCommandInspector = memo<RunCommandInspectorProps>(
<div className={inspectorTextStyles.root}>
{leading}
<span className={shinyTextStyles.shinyText}>{t(translationKey as any)}:</span>
- <span className={styles.chip}>
+ <span {...stylex.props(styles.chip)}>
{chipIcon}
- <span className={styles.command}>{description}</span>
+ <span {...stylex.props(styles.command)}>{description}</span>
</span>
</div>
);
@@ -124,16 +115,24 @@ export const RunCommandInspector = memo<RunCommandInspectorProps>(
{t(translationKey as any)}:
</span>
{description && (
- <span className={styles.chip}>
+ <span {...stylex.props(styles.chip)}>
{chipIcon}
- <span className={styles.command}>{description}</span>
+ <span {...stylex.props(styles.command)}>{description}</span>
</span>
)}
{isLoading ? null : pluginState?.success !== undefined ? (
isSuccess ? (
- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ <Check
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorSuccess}
+ size={14}
+ />
) : (
- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ <X
+ className={stylex.props(styles.statusIcon).className}
+ color={cssVar.colorError}
+ size={14}
+ />
)
) : null}
</div>
diff --git a/packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx b/packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx
index 1d82a7861b3..a0bcf6a31f0 100644
--- a/packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx
+++ b/packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx
@@ -1,28 +1,27 @@
'use client';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import Anser from 'anser';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
import { memo, useMemo } from 'react';
-const styles = createStaticStyles(({ css }) => ({
- pre: css`
- overflow: auto;
-
- max-height: 200px;
- margin: 0;
- padding: 8px;
- border-radius: 6px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- line-height: 1.6;
- color: ${cssVar.colorText};
- word-break: break-word;
- white-space: pre-wrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ pre: {
+ overflow: 'auto',
+ maxHeight: '200px',
+ margin: '0',
+ padding: '8px',
+ borderRadius: '6px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.6,
+ color: cssVar.colorText,
+ wordBreak: 'break-word',
+ whiteSpace: 'pre-wrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface AnsiOutputProps {
text: string;
@@ -40,7 +39,7 @@ const AnsiOutput = memo<AnsiOutputProps>(({ text }) => {
);
return (
- <pre className={styles.pre}>
+ <pre {...stylex.props(styles.pre)}>
{segments.map((seg, i) => {
const decorations = seg.decorations ?? [];
const isDim = decorations.includes('dim');
diff --git a/packages/shared-tool-ui/src/Render/RunCommand/index.tsx b/packages/shared-tool-ui/src/Render/RunCommand/index.tsx
index 9fabb9a7928..feb0c2c1d4e 100644
--- a/packages/shared-tool-ui/src/Render/RunCommand/index.tsx
+++ b/packages/shared-tool-ui/src/Render/RunCommand/index.tsx
@@ -3,18 +3,15 @@
import type { RunCommandState } from '@lobechat/tool-runtime';
import type { BuiltinRenderProps } from '@lobechat/types';
import { Block, Flexbox, Highlighter } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { getRunCommandDisplayCommand } from '../../utils/runCommand';
import AnsiOutput from './AnsiOutput';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
-}));
+const styles = stylex.create({
+ container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
+});
interface RunCommandArgs {
background?: boolean;
@@ -30,7 +27,7 @@ const RunCommand = memo<BuiltinRenderProps<RunCommandArgs, RunCommandState>>(
const command = getRunCommandDisplayCommand(args?.command);
return (
- <Flexbox className={styles.container} gap={8}>
+ <Flexbox className={stylex.props(styles.container).className} gap={8}>
<Block gap={8} padding={8} variant={'outlined'}>
<Highlighter
wrap
diff --git a/packages/shared-tool-ui/src/components/FilePathDisplay.tsx b/packages/shared-tool-ui/src/components/FilePathDisplay.tsx
index 22caeec4f98..77a9d5fd642 100644
--- a/packages/shared-tool-ui/src/components/FilePathDisplay.tsx
+++ b/packages/shared-tool-ui/src/components/FilePathDisplay.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Icon, MaterialFileTypeIcon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { Icon, MaterialFileTypeIcon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ImageIcon } from 'lucide-react';
import path from 'path-browserify-esm';
import { memo, useMemo } from 'react';
@@ -24,16 +24,10 @@ const IMAGE_EXTENSIONS = new Set([
'.webp',
]);
-const styles = createStaticStyles(({ css }) => ({
- icon: css`
- flex-shrink: 0;
- margin-inline-end: 4px;
- `,
- text: css`
- padding-block: 1px;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ icon: { flexShrink: 0, marginInlineEnd: '4px' },
+ text: { paddingBlock: '1px', color: cssVar.colorText },
+});
interface FilePathDisplayProps {
filePath: string;
@@ -65,10 +59,10 @@ export const FilePathDisplay = memo<FilePathDisplayProps>(({ filePath, isDirecto
<>
{name &&
(isImage && !isDirectory ? (
- <Icon className={styles.icon} icon={ImageIcon} size={16} />
+ <Icon className={stylex.props(styles.icon).className} icon={ImageIcon} size={16} />
) : (
<MaterialFileTypeIcon
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
fallbackUnknownType={false}
filename={name}
size={16}
@@ -78,7 +72,7 @@ export const FilePathDisplay = memo<FilePathDisplayProps>(({ filePath, isDirecto
))}
{displayPath && (
<Text
- className={styles.text}
+ className={stylex.props(styles.text).className}
ellipsis={{
tooltipWhenOverflow: true,
}}
diff --git a/packages/shared-tool-ui/src/components/OptionCard.tsx b/packages/shared-tool-ui/src/components/OptionCard.tsx
index 1920b9baa8b..4a4083986f3 100644
--- a/packages/shared-tool-ui/src/components/OptionCard.tsx
+++ b/packages/shared-tool-ui/src/components/OptionCard.tsx
@@ -1,93 +1,56 @@
'use client';
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles, cx } from '@lobehub/ui';
+import { cx, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- // Card sits inline with the chat — no surrounding panel chrome. Hover
- // tints the row so the stack reads as clickable; selection swaps to a
- // neutral filled row so the pick is visually weighty. We use `colorFill*`
- // rather than `colorPrimaryBg` because LobeHub's default primary is a
- // near-black neutral, which makes `colorPrimaryBg` render as a muddy black
- // block; the selection signal instead rides the filled row + the checkmark.
- option: css`
- cursor: pointer;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-radius: 8px;
-
- transition: background 0.12s ease;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
- `,
- optionCheck: css`
- flex-shrink: 0;
- color: ${cssVar.colorPrimary};
- `,
- optionDescription: css`
- font-size: 12px;
- line-height: 1.45;
- color: ${cssVar.colorTextSecondary};
- `,
- // Neutral 1/2/3/4 chip — stays the same colour whether selected or not so
- // the selection signal lives on the filled background + checkmark.
- optionIndex: css`
- flex-shrink: 0;
-
- box-sizing: border-box;
- width: 22px;
- height: 22px;
- border-radius: 6px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- font-weight: 600;
- line-height: 22px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
-
- background: ${cssVar.colorFillTertiary};
- `,
- // Keyboard cursor — a ring instead of a fill so it stays legible when
- // stacked on the hover tint or the selected fill.
- optionHighlighted: css`
- box-shadow: inset 0 0 0 1px ${cssVar.colorBorder};
- `,
- optionLabel: css`
- font-weight: 500;
- `,
- // One step above the hover tint is enough — the checkmark carries the
- // selection signal, so a heavy fill just reads as a muddy block. The hover
- // override repeats the same fill: it must outrank `.option:hover` (which
- // would otherwise drop the row to the lighter unselected tint), and no
- // darkening keeps the selected row flat — it's already "on".
- optionSelected: css`
- background: ${cssVar.colorFillTertiary};
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- recommendedBadge: css`
- flex-shrink: 0;
-
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 11px;
- line-height: 18px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillSecondary};
- `,
-}));
+const styles = stylex.create({
+ option: {
+ cursor: 'pointer',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderRadius: '8px',
+ transition: 'background 0.12s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ optionCheck: { flexShrink: 0, color: cssVar.colorPrimary },
+ optionDescription: { fontSize: '12px', lineHeight: 1.45, color: cssVar.colorTextSecondary },
+ optionIndex: {
+ flexShrink: 0,
+ boxSizing: 'border-box',
+ width: '22px',
+ height: '22px',
+ borderRadius: '6px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ fontWeight: 600,
+ lineHeight: '22px',
+ color: cssVar.colorTextSecondary,
+ textAlign: 'center',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ optionHighlighted: { boxShadow: `inset 0 0 0 1px ${cssVar.colorBorder}` },
+ optionLabel: { fontWeight: 500 },
+ optionSelected: {
+ backgroundColor: { 'default': cssVar.colorFillTertiary, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: 'none',
+ },
+ recommendedBadge: {
+ flexShrink: 0,
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontSize: '11px',
+ lineHeight: '18px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+});
export interface OptionCardProps {
description?: string;
@@ -121,23 +84,29 @@ export const OptionCard = memo<OptionCardProps>(
gap={12}
role="option"
className={cx(
- styles.option,
- selected && styles.optionSelected,
- highlighted && styles.optionHighlighted,
+ stylex.props(
+ styles.option,
+ selected && styles.optionSelected,
+ highlighted && styles.optionHighlighted,
+ ).className,
)}
onClick={() => {
if (!disabled) onToggle();
}}
>
- <span className={styles.optionIndex}>{index}</span>
+ <span {...stylex.props(styles.optionIndex)}>{index}</span>
<Flexbox flex={1} gap={2}>
<Flexbox horizontal align="center" gap={8}>
- <Text className={styles.optionLabel}>{label}</Text>
- {recommendedText && <span className={styles.recommendedBadge}>{recommendedText}</span>}
+ <Text className={stylex.props(styles.optionLabel).className}>{label}</Text>
+ {recommendedText && (
+ <span {...stylex.props(styles.recommendedBadge)}>{recommendedText}</span>
+ )}
</Flexbox>
- {description && <span className={styles.optionDescription}>{description}</span>}
+ {description && <span {...stylex.props(styles.optionDescription)}>{description}</span>}
</Flexbox>
- {selected && <Icon className={styles.optionCheck} icon={Check} size={16} />}
+ {selected && (
+ <Icon className={stylex.props(styles.optionCheck).className} icon={Check} size={16} />
+ )}
</Flexbox>
),
);
diff --git a/packages/shared-tool-ui/src/components/TodoProgress/index.tsx b/packages/shared-tool-ui/src/components/TodoProgress/index.tsx
index 3cffafb6517..2455323d2dc 100644
--- a/packages/shared-tool-ui/src/components/TodoProgress/index.tsx
+++ b/packages/shared-tool-ui/src/components/TodoProgress/index.tsx
@@ -1,7 +1,8 @@
'use client';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { cx, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleArrowRight, CircleCheckBig, ListTodo } from 'lucide-react';
import { memo } from 'react';
@@ -29,87 +30,70 @@ const RING_STROKE = 2;
const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;
const RING_CIRCUM = 2 * Math.PI * RING_RADIUS;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- countChip: css`
- flex-shrink: 0;
-
- margin-inline-end: 8px;
- padding-block: 1px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- headerCount: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- headerDetail: css`
- overflow: hidden;
- min-width: 0;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- `,
- headerLabel: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- gap: 0;
- align-items: center;
-
- min-width: 0;
-
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- ring: css`
- transform: rotate(-90deg);
- flex-shrink: 0;
- margin-inline-end: 6px;
- `,
- ringProgress: css`
- transition:
- stroke-dashoffset 240ms ease,
- stroke 240ms ease;
- `,
- ringTrack: css`
- stroke: ${cssVar.colorFillSecondary};
- `,
- summaryDetail: css`
- color: ${cssVar.colorText};
- `,
- summaryText: css`
- overflow: hidden;
- min-width: 0;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ countChip: {
+ flexShrink: 0,
+ marginInlineEnd: '8px',
+ paddingBlock: '1px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ header: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ headerCount: {
+ flexShrink: 0,
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderRadius: '999px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ headerDetail: {
+ overflow: 'hidden',
+ minWidth: '0',
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ },
+ headerLabel: {
+ overflow: 'hidden',
+ display: 'flex',
+ flex: '1',
+ gap: '0',
+ alignItems: 'center',
+ minWidth: '0',
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ ring: { transform: 'rotate(-90deg)', flexShrink: 0, marginInlineEnd: '6px' },
+ ringProgress: { transition: 'stroke-dashoffset 240ms ease,\n stroke 240ms ease' },
+ ringTrack: { stroke: cssVar.colorFillSecondary },
+ summaryDetail: { color: cssVar.colorText },
+ summaryText: {
+ overflow: 'hidden',
+ minWidth: '0',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
const STATE_ICONS = {
allDone: CircleCheckBig,
@@ -143,9 +127,9 @@ export const TodoProgressRing = memo<TodoProgressRingProps>(({ completed, total
const color = allDone ? cssVar.colorSuccess : cssVar.colorInfo;
return (
- <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>
+ <svg {...stylex.props(styles.ring)} height={RING_SIZE} width={RING_SIZE}>
<circle
- className={styles.ringTrack}
+ {...stylex.props(styles.ringTrack)}
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
fill="none"
@@ -153,7 +137,7 @@ export const TodoProgressRing = memo<TodoProgressRingProps>(({ completed, total
strokeWidth={RING_STROKE}
/>
<circle
- className={styles.ringProgress}
+ {...stylex.props(styles.ringProgress)}
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
fill="none"
@@ -187,16 +171,16 @@ export const TodoInspectorSummary = memo<TodoSummaryContentProps>(({ label, shin
<>
{total > 0 && <TodoProgressRing completed={completed} total={total} />}
{total > 0 && state !== 'allDone' && (
- <span className={styles.countChip}>
+ <span {...stylex.props(styles.countChip)}>
{completed}/{total}
</span>
)}
- <span className={styles.summaryText}>
+ <span {...stylex.props(styles.summaryText)}>
<span className={cx(shiny && shinyTextStyles.shinyText)}>{label}</span>
{detail && (
<>
{': '}
- <span className={styles.summaryDetail}>{detail}</span>
+ <span {...stylex.props(styles.summaryDetail)}>{detail}</span>
</>
)}
</span>
@@ -214,22 +198,22 @@ export const TodoPanelHeader = memo<TodoSummaryContentProps>(({ label, summary }
const { completed, detail, state, total } = summary;
return (
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<Icon
icon={STATE_ICONS[state]}
size={16}
style={{ color: stateColor(state), flexShrink: 0 }}
/>
- <div className={styles.headerLabel}>
+ <div {...stylex.props(styles.headerLabel)}>
<span>{label}</span>
{detail && (
<>
<span>{': '}</span>
- <span className={styles.headerDetail}>{detail}</span>
+ <span {...stylex.props(styles.headerDetail)}>{detail}</span>
</>
)}
</div>
- <span className={styles.headerCount}>
+ <span {...stylex.props(styles.headerCount)}>
{completed}/{total}
</span>
</div>
diff --git a/packages/shared-tool-ui/vitest.config.mts b/packages/shared-tool-ui/vitest.config.mts
index 4ac6027d578..2ed9e161674 100644
--- a/packages/shared-tool-ui/vitest.config.mts
+++ b/packages/shared-tool-ui/vitest.config.mts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vitest/config';
+import { stylexPluginForVitest } from '../../plugins/vite/stylex';
+
export default defineConfig({
+ plugins: [stylexPluginForVitest()],
test: {
environment: 'node',
},
diff --git a/packages/style-equivalence/.gitignore b/packages/style-equivalence/.gitignore
new file mode 100644
index 00000000000..d639912e80e
--- /dev/null
+++ b/packages/style-equivalence/.gitignore
@@ -0,0 +1 @@
+ui/dist
diff --git a/packages/style-equivalence/package.json b/packages/style-equivalence/package.json
new file mode 100644
index 00000000000..b9d5a97456d
--- /dev/null
+++ b/packages/style-equivalence/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@lobechat/style-equivalence",
+ "version": "0.0.1",
+ "private": true,
+ "description": "Style migration equivalence verifier: synthetic per-element comparison with an evidence report",
+ "type": "module",
+ "exports": {
+ "./capture/snapshot": "./src/capture/snapshot.ts",
+ "./capture/conditionPartitions": "./src/capture/conditionPartitions.ts"
+ },
+ "scripts": {
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@lobehub/ui": "^6.13.1",
+ "@playwright/test": "^1.62.1",
+ "@stylexjs/stylex": "0.19.1",
+ "@vitejs/plugin-react": "^6.0.5",
+ "lucide-react": "^1.31.0",
+ "motion": "^14.1.0",
+ "postcss": "8.5.23",
+ "postcss-selector-parser": "7.1.7",
+ "react": "19.2.7",
+ "react-dom": "19.2.7",
+ "typescript": "6.0.3",
+ "vite": "8.0.16"
+ }
+}
diff --git a/packages/style-equivalence/report.vite.config.ts b/packages/style-equivalence/report.vite.config.ts
new file mode 100644
index 00000000000..c577939e436
--- /dev/null
+++ b/packages/style-equivalence/report.vite.config.ts
@@ -0,0 +1,13 @@
+import path from 'node:path';
+
+import react from '@vitejs/plugin-react';
+import { defineConfig } from 'vite';
+
+import { stylexPlugin } from '../../plugins/vite/stylex';
+
+export default defineConfig({
+ base: './',
+ build: { emptyOutDir: true, outDir: path.resolve(import.meta.dirname, 'ui/dist') },
+ plugins: [react(), stylexPlugin()],
+ root: path.resolve(import.meta.dirname, 'src/report'),
+});
diff --git a/packages/style-equivalence/src/analyze/analyze.test.ts b/packages/style-equivalence/src/analyze/analyze.test.ts
new file mode 100644
index 00000000000..4671f76e97d
--- /dev/null
+++ b/packages/style-equivalence/src/analyze/analyze.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ type CaseResult,
+ confirmDifferences,
+ DIFFERENCE_NOT_REPRODUCED,
+ mergeRetry,
+ ownDifferences,
+ rootCausesOf,
+} from './diff';
+
+const diff = (property: string, before: string, after: string, key = 'root.0') => ({
+ after,
+ before,
+ key,
+ property,
+});
+
+describe('rootCausesOf', () => {
+ it('folds layout side effects into the declared property that caused them', () => {
+ expect(
+ rootCausesOf([
+ diff('width', '14px', '16px'),
+ diff('inline-size', '14px', '16px'),
+ diff('transform-origin', '7px 7px', '8px 7px'),
+ diff('perspective-origin', '7px 7px', '8px 7px'),
+ diff('box', '[0,0,14,14]', '[0,0,16,14]'),
+ diff('box', '[14,0,10,14]', '[16,0,10,14]', 'root.1'),
+ ]),
+ ).toEqual([{ after: '16px', before: '14px', key: 'root.0', property: 'inline-size' }]);
+ });
+
+ it('folds properties that mirror color into color', () => {
+ expect(
+ rootCausesOf([
+ diff('color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)'),
+ diff('caret-color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)'),
+ diff('-webkit-text-fill-color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)'),
+ diff('outline-color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)'),
+ ]),
+ ).toEqual([diff('color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)')]);
+ });
+
+ it('keeps a mirrored color property that diverges from color', () => {
+ expect(
+ rootCausesOf([diff('color', 'red', 'red'), diff('outline-color', 'red', 'blue')].slice(1)),
+ ).toEqual([diff('outline-color', 'red', 'blue')]);
+ });
+
+ it('keeps a geometry change that no style property explains', () => {
+ expect(rootCausesOf([diff('box', '[0,0,10,10]', '[0,0,12,10]', 'root.0.0')])).toEqual([
+ diff('box', '[0,0,10,10]', '[0,0,12,10]', 'root.0.0'),
+ ]);
+ });
+});
+
+describe('ownDifferences', () => {
+ it('keeps only what happens at or under the target element', () => {
+ expect(
+ ownDifferences(
+ [
+ diff('padding-block-start', '8px', '10px', 'root.0'),
+ diff('box', '[8,8,100,20]', '[8,10,100,20]', 'root.0.0'),
+ diff('color', 'red', 'blue', 'root.0.0.0'),
+ diff('content', 'none', '"x"', 'root.0.0::before'),
+ ],
+ 'root.0.0',
+ ),
+ ).toEqual([
+ diff('color', 'red', 'blue', 'root.0.0.0'),
+ diff('content', 'none', '"x"', 'root.0.0::before'),
+ ]);
+ });
+
+ it('keeps a size change of the target even though its position is ignored', () => {
+ expect(
+ ownDifferences([diff('box', '[8,8,100,20]', '[8,10,120,20]', 'root.0.0')], 'root.0.0'),
+ ).toEqual([diff('box', '[8,8,100,20]', '[8,10,120,20]', 'root.0.0')]);
+ });
+});
+
+const result = (overrides: Partial<CaseResult>): CaseResult => ({
+ comboDifferences: [],
+ differingConditions: [],
+ errors: [],
+ gaps: [],
+ key: 'a|A#0',
+ rootCauses: [],
+ status: 'equal',
+ unstableConditions: [],
+ ...overrides,
+});
+
+describe('mergeRetry', () => {
+ it('keeps a condition unstable only when the retry is unstable too, and takes the retry differences', () => {
+ const cause = diff('color', 'red', 'blue');
+ const merged = mergeRetry(
+ result({
+ differingConditions: ['light/375/default'],
+ status: 'unstable',
+ unstableConditions: ['light/600/force:active', 'dark/600/default'],
+ }),
+ result({
+ comboDifferences: [
+ { combo: 0, condition: 'dark/600/default', differences: [cause], rootCauses: [cause] },
+ ],
+ differingConditions: ['dark/600/default'],
+ rootCauses: [cause],
+ status: 'difference',
+ }),
+ );
+ expect(merged).toMatchObject({
+ differingConditions: ['light/375/default', 'dark/600/default'],
+ rootCauses: [cause],
+ status: 'difference',
+ unstableConditions: [],
+ });
+ expect(
+ mergeRetry(
+ result({ status: 'unstable', unstableConditions: ['x'] }),
+ result({ status: 'unstable', unstableConditions: ['x'] }),
+ ).status,
+ ).toBe('unstable');
+ });
+});
+
+describe('mergeRetry over differing conditions', () => {
+ const kept = diff('color', 'red', 'blue');
+ const flake = diff('opacity', '1', '0');
+ const at = (condition: string, cause: typeof kept) => ({
+ combo: 0,
+ condition,
+ differences: [cause],
+ rootCauses: [cause],
+ });
+ const original = result({
+ comboDifferences: [at('light/375/hover-target', kept), at('dark/796/focus-visible', flake)],
+ differingConditions: ['light/375/hover-target', 'dark/796/focus-visible'],
+ rootCauses: [kept, flake],
+ status: 'difference',
+ });
+
+ it('keeps only the differences the retry reproduces', () => {
+ const merged = mergeRetry(
+ original,
+ result({
+ comboDifferences: [at('light/375/hover-target', kept)],
+ differingConditions: ['light/375/hover-target'],
+ rootCauses: [kept],
+ status: 'difference',
+ }),
+ original.differingConditions,
+ );
+ expect(merged).toMatchObject({
+ differingConditions: ['light/375/hover-target'],
+ rootCauses: [kept],
+ status: 'difference',
+ });
+ });
+
+ it('is equal when the retry reproduces none of them', () => {
+ expect(mergeRetry(original, result({}), original.differingConditions)).toMatchObject({
+ comboDifferences: [],
+ differingConditions: [],
+ rootCauses: [],
+ status: 'equal',
+ });
+ });
+});
+
+describe('confirmDifferences', () => {
+ const cause = diff('opacity', '1', '0');
+ const seen = result({
+ comboDifferences: [
+ { combo: 0, condition: 'dark/796/focus-visible', differences: [cause], rootCauses: [cause] },
+ ],
+ differingConditions: ['dark/796/focus-visible'],
+ rootCauses: [cause],
+ status: 'difference',
+ });
+
+ it('keeps a difference the retry did not reproduce as a gap, so the case needs sign-off', () => {
+ expect(confirmDifferences(seen, result({}), seen.differingConditions)).toMatchObject({
+ differingConditions: [],
+ gaps: [DIFFERENCE_NOT_REPRODUCED],
+ status: 'equal',
+ });
+ });
+
+ it('adds no gap when every difference reproduces', () => {
+ expect(confirmDifferences(seen, seen, seen.differingConditions).gaps).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/analyze/diff.ts b/packages/style-equivalence/src/analyze/diff.ts
new file mode 100644
index 00000000000..5a40f3fa7c0
--- /dev/null
+++ b/packages/style-equivalence/src/analyze/diff.ts
@@ -0,0 +1,271 @@
+import type { ConditionCapture, RunCapture, SectionSnapshot } from '../capture/runner';
+import { compareSnapshots, type StyleDifference, type StyleSnapshot } from '../capture/snapshot';
+
+const LOGICAL: Record<string, string> = {
+ 'border-bottom-left-radius': 'border-end-start-radius',
+ 'border-bottom-right-radius': 'border-end-end-radius',
+ 'border-top-left-radius': 'border-start-start-radius',
+ 'border-top-right-radius': 'border-start-end-radius',
+ 'bottom': 'inset-block-end',
+ 'height': 'block-size',
+ 'left': 'inset-inline-start',
+ 'margin-bottom': 'margin-block-end',
+ 'margin-left': 'margin-inline-start',
+ 'margin-right': 'margin-inline-end',
+ 'margin-top': 'margin-block-start',
+ 'max-height': 'max-block-size',
+ 'max-width': 'max-inline-size',
+ 'min-height': 'min-block-size',
+ 'min-width': 'min-inline-size',
+ 'overflow-x': 'overflow-inline',
+ 'overflow-y': 'overflow-block',
+ 'padding-bottom': 'padding-block-end',
+ 'padding-left': 'padding-inline-start',
+ 'padding-right': 'padding-inline-end',
+ 'padding-top': 'padding-block-start',
+ 'right': 'inset-inline-end',
+ 'top': 'inset-block-start',
+ 'width': 'inline-size',
+};
+
+const COLOR_MIRRORS = new Set([
+ '-webkit-text-fill-color',
+ '-webkit-text-stroke-color',
+ 'caret-color',
+ 'column-rule-color',
+ 'outline-color',
+ 'row-rule-color',
+ 'text-decoration-color',
+ 'text-emphasis-color',
+]);
+
+const ORIGIN_DERIVED = new Set(['perspective-origin', 'transform-origin']);
+const GEOMETRY = new Set(['box', 'scroll']);
+
+export const rootCausesOf = (differences: StyleDifference[]) => {
+ const at = (key: string, property: string) =>
+ differences.find((item) => item.key === key && item.property === property);
+ const hasStyleCause = differences.some(
+ (item) => !GEOMETRY.has(item.property) && !ORIGIN_DERIVED.has(item.property),
+ );
+ return differences.filter((item) => {
+ if (GEOMETRY.has(item.property)) return !hasStyleCause;
+ if (ORIGIN_DERIVED.has(item.property))
+ return !differences.some(
+ (other) =>
+ other.key === item.key &&
+ !GEOMETRY.has(other.property) &&
+ !ORIGIN_DERIVED.has(other.property),
+ );
+ const logical = LOGICAL[item.property];
+ if (logical && at(item.key, logical)) return false;
+ if (COLOR_MIRRORS.has(item.property)) {
+ const color = at(item.key, 'color');
+ if (color && color.before === item.before && color.after === item.after) return false;
+ }
+ return true;
+ });
+};
+
+const isOwned = (key: string, target: string) =>
+ key === target || key.startsWith(`${target}.`) || key.startsWith(`${target}::`);
+
+const sameSize = (before?: string, after?: string) => {
+ try {
+ const [left, right] = [JSON.parse(before ?? '[]'), JSON.parse(after ?? '[]')] as number[][];
+ return Math.abs(left[2] - right[2]) <= 0.05 && Math.abs(left[3] - right[3]) <= 0.05;
+ } catch {
+ return false;
+ }
+};
+
+export const ownDifferences = (differences: StyleDifference[], targetKey: string) =>
+ differences.filter(
+ (item) =>
+ isOwned(item.key, targetKey) &&
+ !(item.property === 'box' && sameSize(item.before, item.after)),
+ );
+
+export type CaseStatus = 'difference' | 'equal' | 'error' | 'unstable';
+
+export interface ComboDifference {
+ combo: number;
+ condition: string;
+ differences: StyleDifference[];
+ rootCauses: StyleDifference[];
+}
+
+export interface CaseResult {
+ comboDifferences: ComboDifference[];
+ differingConditions: string[];
+ errors: string[];
+ gaps: string[];
+ key: string;
+ rootCauses: StyleDifference[];
+ status: CaseStatus;
+ unstableConditions: string[];
+}
+
+const isSnapshot = (
+ value: SectionSnapshot | undefined,
+): value is StyleSnapshot & { targetKey?: string } => Boolean(value && !('error' in value));
+
+const meaningful = (before: StyleSnapshot, after: StyleSnapshot) =>
+ compareSnapshots(before, after).filter((item) => !item.diagnosticReason);
+
+export const createRunAnalyzer = () => {
+ const results = new Map<string, CaseResult>();
+ const resultFor = (key: string) => {
+ const existing = results.get(key);
+ if (existing) return existing;
+ const created: CaseResult = {
+ comboDifferences: [],
+ differingConditions: [],
+ errors: [],
+ gaps: [],
+ key,
+ rootCauses: [],
+ status: 'equal',
+ unstableConditions: [],
+ };
+ results.set(key, created);
+ return created;
+ };
+ const add = (condition: ConditionCapture) => {
+ for (const section of condition.identical ?? [])
+ resultFor(section.slice(0, section.lastIndexOf('|')));
+ for (const [section, base] of Object.entries(condition.base)) {
+ const separator = section.lastIndexOf('|');
+ const result = resultFor(section.slice(0, separator));
+ const combo = Number(section.slice(separator + 1));
+ const control = condition.baseAgain[section];
+ const head = condition.head[section];
+ if (!isSnapshot(base) || !isSnapshot(head)) {
+ const message = !isSnapshot(base)
+ ? `base:${base.error}`
+ : `head:${head ? (head as { error: string }).error : 'missing'}`;
+ if (!result.errors.includes(message)) result.errors.push(message);
+ continue;
+ }
+ if (
+ !isSnapshot(control) ||
+ ownDifferences(meaningful(base, control), base.targetKey ?? 'root').length
+ ) {
+ if (!result.unstableConditions.includes(condition.condition))
+ result.unstableConditions.push(condition.condition);
+ continue;
+ }
+ const differences = ownDifferences(meaningful(base, head), base.targetKey ?? 'root');
+ const causes = rootCausesOf(differences);
+ if (!causes.length) continue;
+ result.comboDifferences.push({
+ combo,
+ condition: condition.condition,
+ differences,
+ rootCauses: causes,
+ });
+ if (!result.differingConditions.includes(condition.condition))
+ result.differingConditions.push(condition.condition);
+ for (const cause of causes)
+ if (
+ !result.rootCauses.some(
+ (item) =>
+ item.key === cause.key &&
+ item.property === cause.property &&
+ item.before === cause.before &&
+ item.after === cause.after,
+ )
+ )
+ result.rootCauses.push(cause);
+ }
+ };
+ const finish = (caseGaps: Record<string, string[]> = {}) => {
+ for (const result of results.values()) {
+ result.gaps = caseGaps[result.key] ?? [];
+ result.status = result.errors.length
+ ? 'error'
+ : result.unstableConditions.length
+ ? 'unstable'
+ : result.differingConditions.length
+ ? 'difference'
+ : 'equal';
+ }
+ return [...results.values()];
+ };
+ return { add, finish };
+};
+
+export const analyzeRun = (capture: RunCapture): CaseResult[] => {
+ const analyzer = createRunAnalyzer();
+ capture.conditions.forEach(analyzer.add);
+ return analyzer.finish(capture.caseGaps);
+};
+
+const statusOf = (result: CaseResult): CaseStatus =>
+ result.errors.length
+ ? 'error'
+ : result.unstableConditions.length
+ ? 'unstable'
+ : result.differingConditions.length
+ ? 'difference'
+ : 'equal';
+
+export const mergeRetry = (
+ original: CaseResult,
+ retry: CaseResult,
+ conditions: string[] = original.unstableConditions,
+): CaseResult => {
+ const retried = new Set(conditions);
+ const comboDifferences = [
+ ...original.comboDifferences.filter((item) => !retried.has(item.condition)),
+ ...retry.comboDifferences.filter((item) => retried.has(item.condition)),
+ ];
+ const rootCauses: CaseResult['rootCauses'] = [];
+ for (const cause of comboDifferences.flatMap((item) => item.rootCauses))
+ if (
+ !rootCauses.some(
+ (item) =>
+ item.key === cause.key &&
+ item.property === cause.property &&
+ item.before === cause.before &&
+ item.after === cause.after,
+ )
+ )
+ rootCauses.push(cause);
+ const merged: CaseResult = {
+ ...original,
+ comboDifferences,
+ differingConditions: [
+ ...new Set([
+ ...original.differingConditions.filter((condition) => !retried.has(condition)),
+ ...retry.differingConditions.filter((condition) => retried.has(condition)),
+ ]),
+ ],
+ errors: [...new Set([...original.errors, ...retry.errors])],
+ rootCauses,
+ unstableConditions: [
+ ...original.unstableConditions.filter((condition) => !retried.has(condition)),
+ ...retry.unstableConditions.filter((condition) => retried.has(condition)),
+ ],
+ };
+ merged.status = statusOf(merged);
+ return merged;
+};
+
+export const DIFFERENCE_NOT_REPRODUCED = 'DIFFERENCE_NOT_REPRODUCED';
+
+export const confirmDifferences = (
+ original: CaseResult,
+ retry: CaseResult,
+ conditions: string[],
+): CaseResult => {
+ const merged = mergeRetry(original, retry, conditions);
+ const dropped = conditions.some(
+ (condition) =>
+ original.differingConditions.includes(condition) &&
+ !merged.differingConditions.includes(condition),
+ );
+ return dropped && !merged.gaps.includes(DIFFERENCE_NOT_REPRODUCED)
+ ? { ...merged, gaps: [...merged.gaps, DIFFERENCE_NOT_REPRODUCED] }
+ : merged;
+};
diff --git a/packages/style-equivalence/src/build/build.test.ts b/packages/style-equivalence/src/build/build.test.ts
new file mode 100644
index 00000000000..cd72c0e948d
--- /dev/null
+++ b/packages/style-equivalence/src/build/build.test.ts
@@ -0,0 +1,72 @@
+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, describe, expect, it } from 'vitest';
+
+import { generateHost, HOST_HTML } from '../generate/host';
+import { buildSide } from './viteBuild';
+
+const fixture = path.resolve(import.meta.dirname, '../../test/fixtures/mini-project');
+const runtime = path.resolve(import.meta.dirname, '../generate/hostRuntime.tsx');
+let outDir: string;
+
+afterAll(() => rm(outDir, { force: true, recursive: true }));
+
+describe('buildSide', () => {
+ it('builds the generated host with the revision config and emits the case module', async () => {
+ outDir = await mkdtemp(path.join(tmpdir(), 'style-eq-build-'));
+ const hostDir = path.join(fixture, '.stylex-synthetic-test');
+ await mkdir(hostDir, { recursive: true });
+ const moduleFile = path.join(hostDir, 'case.tsx');
+ await writeFile(
+ moduleFile,
+ 'export const cases = { \'a.tsx|A#0\': () => <span className="marker-from-case">x</span> };\n',
+ );
+ await writeFile(path.join(hostDir, 'plan.json'), JSON.stringify([]));
+ await writeFile(path.join(hostDir, 'index.html'), HOST_HTML);
+ await writeFile(
+ path.join(hostDir, 'entry.tsx'),
+ generateHost({
+ hostWrapper: path.join(fixture, 'host.tsx'),
+ modules: [{ file: 'a.tsx', specifier: moduleFile }],
+ runtime,
+ themeAttribute: 'data-theme',
+ }),
+ );
+ try {
+ const result = await buildSide({
+ configFile: path.join(fixture, 'style-equivalence.config.ts'),
+ hostDir,
+ outDir,
+ root: fixture,
+ });
+ expect(result.dist).toBe(outDir);
+ const assets = await readdir(path.join(outDir, 'assets'));
+ const js = await Promise.all(
+ assets
+ .filter((name) => name.endsWith('.js'))
+ .map((name) => readFile(path.join(outDir, 'assets', name), 'utf8')),
+ );
+ expect(js.join('\n')).toContain('marker-from-case');
+ expect(assets.some((name) => name.endsWith('.css'))).toBe(true);
+ } finally {
+ await rm(hostDir, { force: true, recursive: true });
+ }
+ });
+
+ it('reports the build log when the build fails', async () => {
+ const hostDir = await mkdtemp(path.join(tmpdir(), 'style-eq-bad-'));
+ await writeFile(path.join(hostDir, 'index.html'), HOST_HTML);
+ await writeFile(path.join(hostDir, 'entry.tsx'), "import './missing-module';\n");
+ await expect(
+ buildSide({
+ configFile: path.join(fixture, 'style-equivalence.config.ts'),
+ hostDir,
+ outDir: path.join(hostDir, 'dist'),
+ root: fixture,
+ }),
+ ).rejects.toThrow(/BUILD_FAILED[\s\S]*missing-module/);
+ await rm(hostDir, { force: true, recursive: true });
+ });
+});
diff --git a/packages/style-equivalence/src/build/stubs.test.ts b/packages/style-equivalence/src/build/stubs.test.ts
new file mode 100644
index 00000000000..80a4aee699a
--- /dev/null
+++ b/packages/style-equivalence/src/build/stubs.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { failingModules, stubModule } from './stubs';
+
+const written = ['/wt/src/a/__style_equivalence__A.tsx', '/wt/src/b/__style_equivalence__B.tsx'];
+
+describe('failingModules', () => {
+ it('finds the synthetic modules a build error names', () => {
+ const message = `BUILD_FAILED
+[plugin @stylexjs/unplugin] /wt/src/b/__style_equivalence__B.tsx
+TypeError: /wt/src/b/__style_equivalence__B.tsx: undefined is not an object`;
+ expect(failingModules(message, written)).toEqual(['/wt/src/b/__style_equivalence__B.tsx']);
+ });
+
+ it('finds none when the error is outside the synthetic modules', () => {
+ expect(failingModules('BUILD_FAILED\n[UNLOADABLE_DEPENDENCY] src/x', written)).toEqual([]);
+ });
+});
+
+describe('stubModule', () => {
+ it('exports no cases and the error the host renders for each of them', () => {
+ const code = stubModule('TypeError: undefined is not an object\n at x');
+ expect(code).toContain('export const cases = {};');
+ expect(code).toContain(
+ 'export const error = "SYNTHETIC_BUILD_FAILED: TypeError: undefined is not an object";',
+ );
+ });
+});
diff --git a/packages/style-equivalence/src/build/stubs.ts b/packages/style-equivalence/src/build/stubs.ts
new file mode 100644
index 00000000000..86c0ee3321f
--- /dev/null
+++ b/packages/style-equivalence/src/build/stubs.ts
@@ -0,0 +1,35 @@
+import { writeFile } from 'node:fs/promises';
+
+import { type BuildOptions, buildSide } from './viteBuild';
+
+export const failingModules = (message: string, written: string[]) =>
+ written.filter((file) => message.includes(file));
+
+export const stubModule = (reason: string) =>
+ [
+ 'export const cases = {};',
+ `export const error = ${JSON.stringify(`SYNTHETIC_BUILD_FAILED: ${reason.split('\n')[0]}`)};`,
+ '',
+ ].join('\n');
+
+const reasonFor = (message: string, file: string) => {
+ const line = message.split('\n').find((text) => text.includes(`${file}: `));
+ return line ? line.slice(line.indexOf(`${file}: `) + file.length + 2) : 'build error';
+};
+
+export const buildWithStubs = async (options: BuildOptions, written: string[]) => {
+ const stubbed = new Set<string>();
+ for (;;) {
+ try {
+ return { output: await buildSide(options), stubbed: [...stubbed] };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ const failing = failingModules(message, written).filter((file) => !stubbed.has(file));
+ if (!failing.length) throw error;
+ for (const file of failing) {
+ await writeFile(file, stubModule(reasonFor(message, file)));
+ stubbed.add(file);
+ }
+ }
+ }
+};
diff --git a/packages/style-equivalence/src/build/viteBuild.ts b/packages/style-equivalence/src/build/viteBuild.ts
new file mode 100644
index 00000000000..e41cc341bd8
--- /dev/null
+++ b/packages/style-equivalence/src/build/viteBuild.ts
@@ -0,0 +1,39 @@
+import { spawn } from 'node:child_process';
+import { writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+export interface BuildOptions {
+ configFile: string;
+ hostDir: string;
+ logFile?: string;
+ outDir: string;
+ root: string;
+}
+
+const WORKER = path.join(import.meta.dirname, 'worker.ts');
+
+export const buildSide = async ({ configFile, hostDir, logFile, outDir, root }: BuildOptions) => {
+ const started = performance.now();
+ const log = await new Promise<string>((resolve, reject) => {
+ const child = spawn(
+ process.env.STYLE_EQ_BUN ?? 'bun',
+ [WORKER, configFile, root, hostDir, outDir],
+ { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] },
+ );
+ let output = '';
+ child.stdout.on('data', (chunk) => (output += chunk));
+ child.stderr.on('data', (chunk) => (output += chunk));
+ child.on('error', reject);
+ child.on('exit', (code) =>
+ code === 0
+ ? resolve(output)
+ : reject(
+ new Error(
+ `BUILD_FAILED\n${output.length > 8000 ? `${output.slice(0, 4000)}\n…\n${output.slice(-4000)}` : output}`,
+ ),
+ ),
+ );
+ });
+ if (logFile) await writeFile(logFile, log);
+ return { dist: outDir, durationMs: Math.round(performance.now() - started) };
+};
diff --git a/packages/style-equivalence/src/build/worker.ts b/packages/style-equivalence/src/build/worker.ts
new file mode 100644
index 00000000000..9ebde8085be
--- /dev/null
+++ b/packages/style-equivalence/src/build/worker.ts
@@ -0,0 +1,31 @@
+import { pathToFileURL } from 'node:url';
+
+import { build } from 'vite';
+
+import type { ProjectConfig } from '../config';
+
+const [configFile, root, hostDir, outDir] = process.argv.slice(2);
+if (!configFile || !root || !hostDir || !outDir)
+ throw new Error('Usage: worker <configFile> <root> <hostDir> <outDir>');
+
+const config = (await import(pathToFileURL(configFile).href)).default as ProjectConfig;
+const setup = await config.vite(root);
+
+await build({
+ base: './',
+ build: {
+ chunkSizeWarningLimit: 100_000,
+ cssMinify: false,
+ emptyOutDir: true,
+ minify: false,
+ outDir,
+ reportCompressedSize: false,
+ },
+ configFile: false,
+ define: setup.define,
+ logLevel: 'error',
+ plugins: setup.plugins,
+ publicDir: false,
+ resolve: { alias: setup.alias, dedupe: setup.dedupe, tsconfigPaths: setup.tsconfigPaths },
+ root: hostDir,
+});
diff --git a/packages/style-equivalence/src/calibration/calibration.test.ts b/packages/style-equivalence/src/calibration/calibration.test.ts
new file mode 100644
index 00000000000..1b9e368374b
--- /dev/null
+++ b/packages/style-equivalence/src/calibration/calibration.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { calibrate } from './index';
+
+const record = (key: string, category: 'difference' | 'equal' | 'needs-signoff') => ({
+ category,
+ key,
+ plan: { file: key.split('|')[0] },
+});
+
+const adapter = (verdicts: Record<string, 'difference' | 'equal' | 'inconclusive'>) => ({
+ fixturesFor: (files: string[]) =>
+ files.flatMap((file) => (file === 'src/Group.tsx' ? [{ file, id: 'GroupFixture' }] : [])),
+ run: async ({ fixtureId }: { fixtureId: string }) => ({
+ detail: 'exit code',
+ verdict: verdicts[fixtureId],
+ }),
+});
+
+const run = {
+ base: 'b',
+ cases: [record('src/Group.tsx|Group#0', 'equal'), record('src/Other.tsx|Other#0', 'difference')],
+ head: 'h',
+ repo: '/repo',
+ runDir: '/run',
+};
+
+describe('calibrate', () => {
+ it('blocks when the real mount sees a difference the synthetic run called equal', async () => {
+ expect(await calibrate(run, adapter({ GroupFixture: 'difference' }))).toEqual([
+ {
+ detail: 'exit code',
+ file: 'src/Group.tsx',
+ fixtureId: 'GroupFixture',
+ fixture: 'difference',
+ status: 'mismatch',
+ synthetic: 'equal',
+ },
+ ]);
+ });
+
+ it('agrees when both say equal, and only reports an inconclusive real mount', async () => {
+ const [agree] = await calibrate(run, adapter({ GroupFixture: 'equal' }));
+ expect(agree.status).toBe('agree');
+ const [unknown] = await calibrate(run, adapter({ GroupFixture: 'inconclusive' }));
+ expect(unknown.status).toBe('inconclusive');
+ });
+
+ it('runs nothing without an adapter', async () => {
+ expect(await calibrate(run, undefined)).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/calibration/index.ts b/packages/style-equivalence/src/calibration/index.ts
new file mode 100644
index 00000000000..5cd5aea26d9
--- /dev/null
+++ b/packages/style-equivalence/src/calibration/index.ts
@@ -0,0 +1,64 @@
+import type { CaseCategory } from '../verdict/categorize';
+
+export type CalibrationVerdict = 'difference' | 'equal' | 'inconclusive';
+
+export interface CalibrationAdapter {
+ fixturesFor: (files: string[]) => Array<{ file: string; id: string }>;
+ run: (input: {
+ base: string;
+ fixtureId: string;
+ head: string;
+ repo: string;
+ runDir: string;
+ }) => Promise<{ detail: string; verdict: CalibrationVerdict }>;
+}
+
+export interface CalibrationResult {
+ detail: string;
+ file: string;
+ fixture: CalibrationVerdict;
+ fixtureId: string;
+ status: 'agree' | 'inconclusive' | 'mismatch';
+ synthetic: 'difference' | 'equal';
+}
+
+export interface CalibrationRun {
+ base: string;
+ cases: Array<{ category: CaseCategory; key: string; plan: { file: string } }>;
+ head: string;
+ repo: string;
+ runDir: string;
+}
+
+export const calibrate = async (
+ run: CalibrationRun,
+ adapter: CalibrationAdapter | undefined,
+): Promise<CalibrationResult[]> => {
+ if (!adapter) return [];
+ const files = [...new Set(run.cases.map((entry) => entry.plan.file))];
+ const results: CalibrationResult[] = [];
+ for (const { file, id } of adapter.fixturesFor(files)) {
+ const synthetic = run.cases.some(
+ (entry) => entry.plan.file === file && entry.category === 'difference',
+ )
+ ? 'difference'
+ : 'equal';
+ const { detail, verdict } = await adapter.run({
+ base: run.base,
+ fixtureId: id,
+ head: run.head,
+ repo: run.repo,
+ runDir: run.runDir,
+ });
+ results.push({
+ detail,
+ file,
+ fixture: verdict,
+ fixtureId: id,
+ status:
+ verdict === 'inconclusive' ? 'inconclusive' : verdict === synthetic ? 'agree' : 'mismatch',
+ synthetic,
+ });
+ }
+ return results;
+};
diff --git a/packages/style-equivalence/src/capture/browser.ts b/packages/style-equivalence/src/capture/browser.ts
new file mode 100644
index 00000000000..e2d3b3f8dd8
--- /dev/null
+++ b/packages/style-equivalence/src/capture/browser.ts
@@ -0,0 +1,22 @@
+import { existsSync, readdirSync } from 'node:fs';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import { chromium } from '@playwright/test';
+
+const CACHE = path.join(homedir(), 'Library/Caches/ms-playwright');
+const SHELL = 'chrome-headless-shell-mac-arm64/chrome-headless-shell';
+
+export const resolveBrowserExecutable = () => {
+ if (process.env.STYLE_EQ_BROWSER) return process.env.STYLE_EQ_BROWSER;
+ if (!existsSync(CACHE)) return undefined;
+ const shells = readdirSync(CACHE)
+ .filter((name) => name.startsWith('chromium_headless_shell-'))
+ .sort((a, b) => Number(b.split('-')[1]) - Number(a.split('-')[1]))
+ .map((name) => path.join(CACHE, name, SHELL))
+ .filter((file) => existsSync(file));
+ return shells[0];
+};
+
+export const launchBrowser = () =>
+ chromium.launch({ executablePath: resolveBrowserExecutable(), headless: true });
diff --git a/packages/style-equivalence/src/capture/colors.test.ts b/packages/style-equivalence/src/capture/colors.test.ts
new file mode 100644
index 00000000000..ce8f492643c
--- /dev/null
+++ b/packages/style-equivalence/src/capture/colors.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { sameStyleValue } from './colors';
+
+describe('computed color values serialized two ways', () => {
+ it('treats color(srgb …) and rgba(…) of the same color as equal', () => {
+ expect(sameStyleValue('color(srgb 0.1 0.2 0.3 / 0.5)', 'rgba(26, 51, 77, 0.5)')).toBe(true);
+ expect(sameStyleValue('color(srgb 1 1 1)', 'rgb(255, 255, 255)')).toBe(true);
+ expect(
+ sameStyleValue('0px 1px 2px color(srgb 0 0 0 / 0.06)', '0px 1px 2px rgba(0, 0, 0, 0.06)'),
+ ).toBe(true);
+ });
+
+ it('still tells different colors and different surroundings apart', () => {
+ expect(sameStyleValue('color(srgb 0.1 0.2 0.3 / 0.5)', 'rgba(26, 51, 77, 0.6)')).toBe(false);
+ expect(sameStyleValue('color(srgb 0.1 0.2 0.3)', 'rgb(30, 51, 77)')).toBe(false);
+ expect(
+ sameStyleValue('0px 1px 2px rgba(0, 0, 0, 0.06)', '0px 2px 2px rgba(0, 0, 0, 0.06)'),
+ ).toBe(false);
+ expect(sameStyleValue('12px', '13px')).toBe(false);
+ });
+});
diff --git a/packages/style-equivalence/src/capture/colors.ts b/packages/style-equivalence/src/capture/colors.ts
new file mode 100644
index 00000000000..32aefd9aacc
--- /dev/null
+++ b/packages/style-equivalence/src/capture/colors.ts
@@ -0,0 +1,48 @@
+const COLOR = /color\(srgb\s+([^)]*)\)|rgba?\(([^)]*)\)/g;
+
+interface Rgba {
+ alpha: number;
+ channels: number[];
+}
+
+const parse = (match: RegExpMatchArray): Rgba | undefined => {
+ const srgb = match[1] !== undefined;
+ const body = (srgb ? match[1] : match[2]).trim();
+ const [color, alpha] = body.includes('/') ? body.split('/') : [body, undefined];
+ const parts = color.split(/[\s,]+/).filter(Boolean);
+ const rest = srgb ? alpha : parts.length === 4 ? parts.pop() : alpha;
+ const values = parts.map(Number);
+ if (values.length !== 3 || values.some(Number.isNaN)) return undefined;
+ const a =
+ rest === undefined
+ ? 1
+ : Number(rest.trim().replace(/%$/, '')) / (rest.trim().endsWith('%') ? 100 : 1);
+ if (Number.isNaN(a)) return undefined;
+ return { alpha: a, channels: srgb ? values.map((value) => value * 255) : values };
+};
+
+const split = (value: string) => {
+ const colors: Rgba[] = [];
+ let failed = false;
+ const skeleton = value.replaceAll(COLOR, (...args) => {
+ const color = parse(args as unknown as RegExpMatchArray);
+ if (!color) failed = true;
+ else colors.push(color);
+ return '<color>';
+ });
+ return failed ? undefined : { colors, skeleton };
+};
+
+export const sameStyleValue = (before: string | undefined, after: string | undefined) => {
+ if (before === after) return true;
+ if (before === undefined || after === undefined) return false;
+ const [left, right] = [split(before), split(after)];
+ if (!left || !right || !left.colors.length || left.skeleton !== right.skeleton) return false;
+ return left.colors.every((color, index) => {
+ const other = right.colors[index];
+ return (
+ Math.abs(color.alpha - other.alpha) <= 0.01 &&
+ color.channels.every((channel, at) => Math.abs(channel - other.channels[at]) <= 1)
+ );
+ });
+};
diff --git a/scripts/stylexMigration/verification/analysis/conditionPartitions.test.ts b/packages/style-equivalence/src/capture/conditionPartitions.test.ts
similarity index 100%
rename from scripts/stylexMigration/verification/analysis/conditionPartitions.test.ts
rename to packages/style-equivalence/src/capture/conditionPartitions.test.ts
diff --git a/scripts/stylexMigration/verification/analysis/conditionPartitions.ts b/packages/style-equivalence/src/capture/conditionPartitions.ts
similarity index 100%
rename from scripts/stylexMigration/verification/analysis/conditionPartitions.ts
rename to packages/style-equivalence/src/capture/conditionPartitions.ts
diff --git a/packages/style-equivalence/src/capture/gaps.test.ts b/packages/style-equivalence/src/capture/gaps.test.ts
new file mode 100644
index 00000000000..b1af9b42a23
--- /dev/null
+++ b/packages/style-equivalence/src/capture/gaps.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { caseGapsOf } from './gaps';
+
+const containerRule = 'CONTAINER_UNMODELED|@container (width < 300px) { .item { color: red; } }';
+
+describe('caseGapsOf', () => {
+ it('reports nothing when both sides carry the same unmodeled rules', () => {
+ expect(caseGapsOf({ 'a|A#0|0': [containerRule] }, { 'a|A#0|0': [containerRule] })).toEqual({});
+ });
+
+ it('reports each unmodeled kind whose rules differ between the sides', () => {
+ expect(
+ caseGapsOf(
+ { 'a|A#0|0': [containerRule, 'MEDIA_UNMODELED|@media (hover: hover) { .a:hover {} }'] },
+ { 'a|A#0|1': ['MEDIA_UNMODELED|@media (hover: hover) { .b:hover {} }'] },
+ ),
+ ).toEqual({ 'a|A#0': ['CONTAINER_UNMODELED', 'MEDIA_UNMODELED'] });
+ });
+});
diff --git a/packages/style-equivalence/src/capture/gaps.ts b/packages/style-equivalence/src/capture/gaps.ts
new file mode 100644
index 00000000000..bd8dd56a98a
--- /dev/null
+++ b/packages/style-equivalence/src/capture/gaps.ts
@@ -0,0 +1,32 @@
+const kindOf = (entry: string) => entry.slice(0, entry.indexOf('|'));
+
+const caseOf = (section: string) => section.slice(0, section.lastIndexOf('|'));
+
+const byCase = (sections: Record<string, string[]>) => {
+ const cases = new Map<string, Map<string, string[]>>();
+ for (const [section, entries] of Object.entries(sections)) {
+ const kinds = cases.get(caseOf(section)) ?? new Map<string, string[]>();
+ cases.set(caseOf(section), kinds);
+ for (const entry of entries) {
+ const kind = kindOf(entry);
+ kinds.set(kind, [...(kinds.get(kind) ?? []), entry.slice(entry.indexOf('|') + 1)]);
+ }
+ }
+ return cases;
+};
+
+export const caseGapsOf = (base: Record<string, string[]>, head: Record<string, string[]>) => {
+ const [left, right] = [byCase(base), byCase(head)];
+ const gaps: Record<string, string[]> = {};
+ for (const key of new Set([...left.keys(), ...right.keys()])) {
+ const kinds = new Set([...(left.get(key)?.keys() ?? []), ...(right.get(key)?.keys() ?? [])]);
+ const differing = [...kinds].filter((kind) => {
+ const [a, b] = [left.get(key)?.get(kind) ?? [], right.get(key)?.get(kind) ?? []].map((list) =>
+ [...new Set(list)].sort().join('\n'),
+ );
+ return a !== b;
+ });
+ if (differing.length) gaps[key] = differing.sort();
+ }
+ return gaps;
+};
diff --git a/packages/style-equivalence/src/capture/inspect.ts b/packages/style-equivalence/src/capture/inspect.ts
new file mode 100644
index 00000000000..c3fc20aeb4e
--- /dev/null
+++ b/packages/style-equivalence/src/capture/inspect.ts
@@ -0,0 +1,256 @@
+import type { Page } from '@playwright/test';
+
+export interface RuleInspection {
+ containers: number;
+ media: string[];
+ pseudoRules: Record<string, string[]>;
+ rules: string[];
+ sectionRules?: Record<string, string[]>;
+ unmodeled: Record<string, number[]>;
+ unparsed: string[];
+}
+
+export const FORCEABLE = ['active', 'focus', 'focus-visible', 'focus-within', 'hover'];
+export const MODELED_PSEUDO_ELEMENTS = ['after', 'before', 'marker', 'placeholder'];
+export const STATIC_PSEUDO_CLASSES = [
+ 'after',
+ 'any-link',
+ 'before',
+ 'defined',
+ 'dir',
+ 'empty',
+ 'first-child',
+ 'first-letter',
+ 'first-line',
+ 'first-of-type',
+ 'has',
+ 'host',
+ 'host-context',
+ 'is',
+ 'lang',
+ 'last-child',
+ 'last-of-type',
+ 'link',
+ 'not',
+ 'nth-child',
+ 'nth-last-child',
+ 'nth-last-of-type',
+ 'nth-of-type',
+ 'only-child',
+ 'only-of-type',
+ 'root',
+ 'scope',
+ 'where',
+];
+
+export const inspectRules = (page: Page): Promise<RuleInspection> =>
+ page.evaluate(
+ ({ forceable, pseudoElements, staticClasses }) => {
+ const sections = [...document.querySelectorAll('[data-case]')];
+ const root = document.querySelector('[data-synthetic-cases]') ?? document.body;
+ const selectorList = (selector: string) => {
+ const parts: string[] = [];
+ let depth = 0;
+ let start = 0;
+ for (let index = 0; index < selector.length; index++) {
+ const char = selector[index];
+ if (char === '\\') index++;
+ else if (char === '(' || char === '[') depth++;
+ else if (char === ')' || char === ']') depth--;
+ else if (char === ',' && depth === 0) {
+ parts.push(selector.slice(start, index));
+ start = index + 1;
+ }
+ }
+ parts.push(selector.slice(start));
+ return parts;
+ };
+ const unparsed = new Set<string>();
+ const broaden = (selector: string) => {
+ let text = '';
+ for (let index = 0; index < selector.length; index++) {
+ const char = selector[index];
+ if (char === '\\') {
+ text += selector.slice(index, index + 2);
+ index++;
+ continue;
+ }
+ if (char !== ':') {
+ text += char;
+ continue;
+ }
+ while (selector[index + 1] === ':') index++;
+ while (/[\w-]/.test(selector[index + 1] ?? '')) index++;
+ if (selector[index + 1] !== '(') continue;
+ let depth = 0;
+ for (index++; index < selector.length; index++) {
+ if (selector[index] === '(') depth++;
+ if (selector[index] === ')' && --depth === 0) break;
+ }
+ }
+ const filled = text
+ .replaceAll(/([>+~])\s*(?=[>+~]|$)/g, '$1 *')
+ .replace(/^\s*([>+~])/, '* $1')
+ .trim();
+ return filled || '*';
+ };
+ const styleParent = (rule: CSSRule) => {
+ let parent = rule.parentRule;
+ while (parent && !(parent instanceof CSSStyleRule)) parent = parent.parentRule;
+ return parent as CSSStyleRule | null;
+ };
+ const resolve = (rule: CSSStyleRule): string => {
+ const parent = styleParent(rule);
+ if (!parent) return rule.selectorText;
+ const outer = resolve(parent);
+ return rule.selectorText.includes('&')
+ ? rule.selectorText.replaceAll('&', `:is(${outer})`)
+ : `:is(${outer}) ${rule.selectorText}`;
+ };
+ const selectorsUnder = (rule: CSSRule): string[] => {
+ if (rule instanceof CSSStyleRule) return [resolve(rule)];
+ const inner = 'cssRules' in rule ? [...(rule as CSSGroupingRule).cssRules] : [];
+ const nested = inner.flatMap(selectorsUnder);
+ if (nested.length) return nested;
+ const parent = styleParent(rule);
+ return parent ? [resolve(parent)] : [];
+ };
+ const hits = (selector: string, scope: Element) =>
+ selectorList(selector).some((part) => {
+ try {
+ const broad = broaden(part);
+ if (broad === '*') return false;
+ return scope.matches(broad) || scope.querySelector(broad) !== null;
+ } catch {
+ unparsed.add(part.trim());
+ return false;
+ }
+ });
+ const touching = (rule: CSSRule, scope: Element) =>
+ selectorsUnder(rule).some((selector) => hits(selector, scope));
+ const widthFeatures = new Set(['max-width', 'min-width', 'width']);
+ const ignored = new Set(['all', 'and', 'only', 'screen']);
+ const modeledMedia = (condition: string) => {
+ const text = condition.toLowerCase().trim();
+ if (/^\(?\s*prefers-reduced-motion(\s*:\s*(reduce|no-preference))?\s*\)?$/.test(text))
+ return true;
+ const words = (text.match(/[a-z][a-z-]*/g) ?? []).filter(
+ (word) => !ignored.has(word) && !/^(px|em|rem|vw|vh|ch|ex)$/.test(word),
+ );
+ return words.length > 0 && words.every((word) => widthFeatures.has(word));
+ };
+ const media: string[] = [];
+ const pseudoRules: Record<string, string[]> = {};
+ const rules: string[] = [];
+ const candidates: CSSRule[] = [];
+ let containers = 0;
+ const visit = (list: CSSRuleList) => {
+ for (const rule of list) {
+ if (rule instanceof CSSMediaRule && touching(rule, root)) {
+ media.push(rule.conditionText);
+ if (!modeledMedia(rule.conditionText)) {
+ candidates.push(rule);
+ rules.push(`MEDIA_UNMODELED|${rule.cssText}`);
+ }
+ }
+ if (
+ typeof CSSContainerRule !== 'undefined' &&
+ rule instanceof CSSContainerRule &&
+ touching(rule, root)
+ ) {
+ containers++;
+ candidates.push(rule);
+ rules.push(`CONTAINER_UNMODELED|${rule.cssText}`);
+ }
+ if (
+ rule instanceof CSSStyleRule &&
+ rule.selectorText.includes(':') &&
+ touching(rule, root)
+ ) {
+ const elements = [...rule.selectorText.matchAll(/::([a-z-]+)/gi)].map(
+ (match) => match[1],
+ );
+ if (elements.some((name) => !pseudoElements.includes(name))) {
+ candidates.push(rule);
+ rules.push(`PSEUDO_UNMODELED|${rule.cssText}`);
+ }
+ const classes = [
+ ...rule.selectorText
+ .replaceAll(/\\./g, '')
+ .replaceAll(/\[[^\]]*\]/g, '')
+ .matchAll(/(?<!:):([a-z-]+)/gi),
+ ].map((match) => match[1].toLowerCase());
+ if (
+ classes.some((name) => !forceable.includes(name) && !staticClasses.includes(name))
+ ) {
+ candidates.push(rule);
+ rules.push(`STATE_UNMODELED|${rule.cssText}`);
+ }
+ for (const part of selectorList(rule.selectorText)) {
+ const compounds = part.trim().split(/\s*[\s>+~]\s*/);
+ compounds.forEach((compound, index) => {
+ const states = [...compound.matchAll(/:([a-z-]+)/gi)]
+ .map((match) => match[1])
+ .filter((name) => forceable.includes(name));
+ if (!states.length) return;
+ const key = [...new Set(states)].sort().join('+');
+ const scoped = index < compounds.length - 1 ? `chain:${key}` : key;
+ (pseudoRules[scoped] ??= []).push(rule.cssText);
+ });
+ }
+ }
+ if ('cssRules' in rule) visit((rule as CSSGroupingRule).cssRules);
+ }
+ };
+ for (const sheet of document.styleSheets) {
+ try {
+ visit(sheet.cssRules);
+ } catch {
+ continue;
+ }
+ }
+ const unmodeled: Record<string, number[]> = {};
+ const sectionRules: Record<string, string[]> = {};
+ 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')!;
+ for (const name of element.classList)
+ owners.set(name, owners.has(name) && owners.get(name) !== id ? null : id);
+ }
+ return [...owners].filter((entry): entry is [string, string] => entry[1] !== null);
+ };
+ const escape = (text: string) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+ for (const section of sections) {
+ const found = candidates.flatMap((rule, index) => (touching(rule, section) ? [index] : []));
+ if (!found.length) continue;
+ const key = section.getAttribute('data-case')!;
+ unmodeled[key] = found;
+ const owned = hostClasses(section);
+ sectionRules[key] = found.map((index) =>
+ owned.reduce(
+ (text, [name, id]) =>
+ text.replaceAll(
+ new RegExp(`\\.${escape(name)}(?![\\w-])`, 'g'),
+ `[data-synthetic-element="${id}"]`,
+ ),
+ rules[index],
+ ),
+ );
+ }
+ return {
+ containers,
+ media: [...new Set(media)],
+ pseudoRules,
+ rules,
+ sectionRules,
+ unmodeled,
+ unparsed: [...unparsed],
+ };
+ },
+ {
+ forceable: FORCEABLE,
+ pseudoElements: MODELED_PSEUDO_ELEMENTS,
+ staticClasses: STATIC_PSEUDO_CLASSES,
+ },
+ );
diff --git a/packages/style-equivalence/src/capture/runner.test.ts b/packages/style-equivalence/src/capture/runner.test.ts
new file mode 100644
index 00000000000..e1668126746
--- /dev/null
+++ b/packages/style-equivalence/src/capture/runner.test.ts
@@ -0,0 +1,340 @@
+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 { analyzeRun, createRunAnalyzer } from '../analyze/diff';
+import { launchBrowser } from './browser';
+import {
+ capturePage,
+ captureRun,
+ captureSections,
+ conditionFromLabel,
+ inspectCaseGaps,
+} from './runner';
+import type { StyleSnapshot } from './snapshot';
+import { serveDirectories } from './staticServer';
+
+let root: string;
+let server: Awaited<ReturnType<typeof serveDirectories>>;
+let browser: Awaited<ReturnType<typeof launchBrowser>>;
+
+const page = (css: string, extraScript = '') => `<!doctype html><html><head><style>
+body { margin: 0; font: 14px Arial; }
+${css}
+</style></head><body><div id="app" data-synthetic-ready="true">
+<main data-synthetic-cases="">
+<section data-case="a.tsx|A#0|0" style="width:360px;padding:8px"><div data-synthetic-element="A#0" class="row"><span data-synthetic-element="A#1" class="t">Text</span></div></section>
+</main></div>
+<script>const theme = new URLSearchParams(location.search).get('theme'); if (theme) document.documentElement.setAttribute('data-theme', theme); ${extraScript}</script>
+</body></html>`;
+
+const write = async (name: string, html: string) => {
+ await mkdir(path.join(root, name), { recursive: true });
+ await writeFile(path.join(root, name, 'index.html'), html);
+};
+
+beforeAll(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-capture-'));
+ const scrollbar = (name: string, width: string) =>
+ page(`.${name} ::-webkit-scrollbar { width: ${width}; }`).replace(
+ 'class="row"',
+ `class="${name}"`,
+ );
+ await write('base-scrollbar', scrollbar('lobe-share-7976-preview', '4px'));
+ await write('head-scrollbar', scrollbar('css-1x2y3z', '4px'));
+ await write('head-scrollbar-wide', scrollbar('css-1x2y3z', '8px'));
+ await write(
+ 'base-elsewhere-container',
+ page(
+ '.t { color: black; } @container grid (min-width: 560px) { .elsewhere > :nth-child(n+3) { display: flex; } } .elsewhere:has(> :where(button, a):active) { color: red; }',
+ ),
+ );
+ await write(
+ 'base-document-pseudo',
+ page('.t { color: black; } ::view-transition-old(panel) { animation-duration: 240ms; }'),
+ );
+ await write(
+ 'base-ancestor-not',
+ page(
+ '.t { color: black; } @media (hover: hover) and (pointer: fine) { .x1a2b3c.x1a2b3c.x1a2b3c:where(.lhewz77w:not(:hover, :focus-within) *) { opacity: 0; } }',
+ ),
+ );
+ await write(
+ 'base-unparsable',
+ page(
+ '.t { color: black; }',
+ "const sheet = document.createElement('style'); sheet.textContent = '@namespace svg url(http://www.w3.org/2000/svg); @media (hover: hover) { svg|a { color: red; } }'; document.head.prepend(sheet);",
+ ),
+ );
+ await write('base-hover', page('.t { color: black; } .t:hover { color: red; }'));
+ await write('head-hover', page('.t { color: black; }'));
+ await write(
+ 'base-media',
+ page('.t { color: black; } @media (max-width: 600px) { .t { color: red; } }'),
+ );
+ await write('head-media', page('.t { color: black; }'));
+ await write(
+ 'unrelated-media',
+ page('.t { color: black; } @media (max-width: 900px) { .elsewhere { color: red; } }'),
+ );
+ await write('base-dark', page('.t { color: black; } [data-theme="dark"] .t { color: white; }'));
+ await write('head-dark', page('.t { color: black; }'));
+ await write(
+ 'base-ancestor-focus',
+ page('.t { color: black; } .row:focus-visible .t { color: red; }'),
+ );
+ await write('head-ancestor-focus', page('.t { color: black; }'));
+ await write('base-checked', page('.t { color: black; } .t:checked { background-color: red; }'));
+ await write('head-checked', page('.t { color: black; } .t:checked { background-color: blue; }'));
+ await write(
+ 'static-pseudo',
+ page('.t { color: black; } .t:first-child:not(:empty) { color: black; }'),
+ );
+ const pair = (css: string) => `<!doctype html><html><head><style>
+body { margin: 0; font: 14px Arial; }
+${css}
+</style></head><body><div id="app" data-synthetic-ready="true"><main data-synthetic-cases="">
+<section data-case="a.tsx|A#0|0"><div data-synthetic-element="A#0" class="same">Same</div></section>
+<section data-case="b.tsx|B#0|0"><div data-synthetic-element="B#0" class="moved">Moved</div></section>
+</main></div></body></html>`;
+ await write('base-pair', pair('.same { color: black; --tone: 1; } .moved { color: red; }'));
+ await write('head-pair', pair('.same { color: black; --tone: 2; } .moved { color: blue; }'));
+ await write(
+ 'noisy',
+ page(
+ '.t { color: black; }',
+ "document.querySelector('.t').style.width = Math.random() * 100 + 'px';",
+ ),
+ );
+ const fade = (name: string) =>
+ page(
+ `.t { color: black; animation: ${name} 1ms; } @keyframes ${name} { from { opacity: 0; } to { opacity: 1; } }`,
+ );
+ await write('base-fade', fade('enter'));
+ await write('head-fade', fade('lobe-x-enter'));
+ server = await serveDirectories(root);
+ browser = await launchBrowser();
+}, 60_000);
+
+afterAll(async () => {
+ await browser?.close();
+ await server?.close();
+ await rm(root, { force: true, recursive: true });
+});
+
+const run = async (base: string, head: string, widths = [1280]) =>
+ analyzeRun(
+ await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light', 'dark'], widths },
+ urls: { base: `${server.url}/${base}/`, head: `${server.url}/${head}/` },
+ }),
+ );
+
+describe('captureRun + analyzeRun', () => {
+ it('reports a hover-only difference only under hover states', async () => {
+ const [result] = await run('base-hover', 'head-hover');
+ expect(result.status).toBe('difference');
+ expect(result.differingConditions.sort()).toEqual([
+ 'dark/1280/hover-chain',
+ 'dark/1280/hover-target',
+ 'light/1280/hover-chain',
+ 'light/1280/hover-target',
+ ]);
+ });
+
+ it('adds the width partition a media query creates and reports only there', async () => {
+ const [result] = await run('base-media', 'head-media');
+ expect(result.differingConditions.every((condition) => !condition.includes('/1280/'))).toBe(
+ true,
+ );
+ expect(result.differingConditions).toContain('light/600/default');
+ });
+
+ it('ignores media rules that match nothing inside a case', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ states: ['default'],
+ urls: { base: `${server.url}/unrelated-media/`, head: `${server.url}/head-media/` },
+ });
+ expect(capture.widths).toEqual([1280]);
+ });
+
+ it('forces a non-hover state on the ancestor chain when only an ancestor carries it', async () => {
+ const [result] = await run('base-ancestor-focus', 'head-ancestor-focus');
+ expect(result.status).toBe('difference');
+ expect(result.differingConditions).toContain('light/1280/force-chain:focus-visible');
+ });
+
+ it('flags a case whose state-dependent pseudo-class rules differ as a coverage gap', async () => {
+ const [result] = await run('base-checked', 'head-checked');
+ expect(result).toMatchObject({ gaps: ['STATE_UNMODELED'], status: 'equal' });
+ });
+
+ it('reports state gaps between any two pages, such as an original head and its mutant', async () => {
+ const gaps = await inspectCaseGaps(
+ browser,
+ { base: `${server.url}/base-checked/`, head: `${server.url}/head-checked/` },
+ conditionFromLabel('light/1280/hover-target'),
+ [],
+ );
+ expect(gaps).toEqual({ 'a.tsx|A#0': ['STATE_UNMODELED'] });
+ });
+
+ 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([]);
+ const [changed] = await run('base-scrollbar', 'head-scrollbar-wide');
+ expect(changed.gaps).toEqual(['PSEUDO_UNMODELED']);
+ });
+
+ it('does not pin a rule on a case when only its pseudo parts were stripped', async () => {
+ const [result] = await run('base-elsewhere-container', 'head-media');
+ expect(result.gaps).toEqual([]);
+ });
+
+ it('does not pin a document-level pseudo rule on every case', async () => {
+ const [result] = await run('base-document-pseudo', 'head-media');
+ expect(result.gaps).toEqual([]);
+ });
+
+ it('keeps a rule whose functional pseudo nests a comma off cases that do not carry its class', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ urls: { base: `${server.url}/base-ancestor-not/`, head: `${server.url}/head-media/` },
+ });
+ expect(capture.caseGaps).toEqual({});
+ expect(capture.unparsedSelectors).toEqual([]);
+ });
+
+ it('reports a selector the page cannot evaluate instead of pinning it on every case', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ urls: { base: `${server.url}/base-unparsable/`, head: `${server.url}/head-media/` },
+ });
+ expect(capture.caseGaps).toEqual({});
+ expect(capture.unparsedSelectors).toEqual(['svg|a']);
+ });
+
+ it('does not flag structural pseudo-classes the default capture already evaluates', async () => {
+ const [result] = await run('static-pseudo', 'head-media');
+ expect(result.gaps).toEqual([]);
+ });
+
+ it('reports a theme-only difference only in that theme', async () => {
+ const [result] = await run('base-dark', 'head-dark');
+ expect(result.differingConditions.every((condition) => condition.startsWith('dark/'))).toBe(
+ true,
+ );
+ expect(result.rootCauses).toEqual([
+ expect.objectContaining({
+ after: 'rgb(0, 0, 0)',
+ before: 'rgb(255, 255, 255)',
+ property: 'color',
+ }),
+ ]);
+ });
+
+ it('marks a case whose base disagrees with itself as unstable', async () => {
+ const [result] = await run('noisy', 'head-hover');
+ expect(result.status).toBe('unstable');
+ });
+
+ 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' });
+ });
+
+ it('streams conditions to an analyzer without keeping their snapshots', async () => {
+ const analyzer = createRunAnalyzer();
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light', 'dark'], widths: [1280] },
+ onCondition: analyzer.add,
+ urls: { base: `${server.url}/base-dark/`, head: `${server.url}/head-dark/` },
+ });
+ expect(capture.conditions.every((condition) => !Object.keys(condition.head).length)).toBe(true);
+ const [result] = analyzer.finish(capture.caseGaps);
+ expect(result.differingConditions).toEqual([
+ 'dark/1280/default',
+ 'dark/1280/hover-chain',
+ 'dark/1280/hover-target',
+ 'dark/1280/focus-visible',
+ ]);
+ });
+
+ it('captures exactly the conditions of a fixed plan', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ plan: [conditionFromLabel('dark/375/hover-target')],
+ urls: { base: `${server.url}/base-dark/`, head: `${server.url}/head-dark/` },
+ });
+ expect(capture.conditions.map((condition) => condition.condition)).toEqual([
+ 'dark/375/hover-target',
+ ]);
+ expect(analyzeRun(capture)[0].differingConditions).toEqual(['dark/375/hover-target']);
+ });
+
+ it('transfers full snapshots only for sections whose loads differ beyond custom properties', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ states: ['default'],
+ urls: { base: `${server.url}/base-pair/`, head: `${server.url}/head-pair/` },
+ });
+ const condition = capture.conditions.find((item) => item.condition === 'light/1280/default')!;
+ expect(condition.identical).toEqual(['a.tsx|A#0|0']);
+ expect(Object.keys(condition.head)).toEqual(['b.tsx|B#0|0']);
+ expect(
+ Object.fromEntries(analyzeRun(capture).map((result) => [result.key, result.status])),
+ ).toEqual({ 'a.tsx|A#0': 'equal', 'b.tsx|B#0': 'difference' });
+ });
+
+ it('transfers differing sections with the same styles a direct capture reads', async () => {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ plan: [conditionFromLabel('light/1280/default')],
+ urls: { base: `${server.url}/base-pair/`, head: `${server.url}/head-pair/` },
+ });
+ const { page, snapshots } = await capturePage(
+ browser,
+ `${server.url}/head-pair/`,
+ conditionFromLabel('light/1280/default'),
+ [],
+ );
+ await page.close();
+ const direct = snapshots['b.tsx|B#0|0'] as StyleSnapshot;
+ const transferred = capture.conditions[0].head['b.tsx|B#0|0'] as StyleSnapshot;
+ const standard = (style: Record<string, string>) =>
+ Object.fromEntries(Object.entries(style).filter(([name]) => !name.startsWith('--')));
+ expect(transferred.styles).toEqual(direct.styles.map(standard));
+ expect(transferred.nodes).toEqual(direct.nodes);
+ });
+
+ it('compares any number of pages and transfers only sections that differ among them', async () => {
+ const { identical, snapshots } = await captureSections(
+ browser,
+ [`${server.url}/base-pair/`, `${server.url}/base-pair/`, `${server.url}/head-pair/`],
+ conditionFromLabel('light/1280/default'),
+ [],
+ );
+ expect(identical).toEqual(['a.tsx|A#0|0']);
+ expect(snapshots.map((item) => Object.keys(item))).toEqual([
+ ['b.tsx|B#0|0'],
+ ['b.tsx|B#0|0'],
+ ['b.tsx|B#0|0'],
+ ]);
+ });
+
+ it('reports equal pages as equal', async () => {
+ const [result] = await run('head-hover', 'head-media');
+ expect(result).toMatchObject({ differingConditions: [], status: 'equal' });
+ });
+});
diff --git a/packages/style-equivalence/src/capture/runner.ts b/packages/style-equivalence/src/capture/runner.ts
new file mode 100644
index 00000000000..fe4ac794ef1
--- /dev/null
+++ b/packages/style-equivalence/src/capture/runner.ts
@@ -0,0 +1,475 @@
+import { availableParallelism } from 'node:os';
+
+import type { Browser, Page } from '@playwright/test';
+
+import type { ConditionConfig, ConditionVariant } from '../config';
+import type { Side } from '../plan/planFile';
+import { caseGapsOf } from './gaps';
+import { inspectRules, type RuleInspection } from './inspect';
+import { captureInPage, type StyleSnapshot } from './snapshot';
+import { applyState, type CaptureState, planStates } from './states';
+import { planWidths } from './widths';
+
+export const DEFAULT_VARIANTS: ConditionVariant[] = ['rtl', 'reduced-motion'];
+
+export type SectionSnapshot = (StyleSnapshot & { targetKey?: string }) | { error: string };
+export type SectionSnapshots = Record<string, SectionSnapshot>;
+
+export interface ConditionCapture {
+ base: SectionSnapshots;
+ baseAgain: SectionSnapshots;
+ condition: string;
+ head: SectionSnapshots;
+ identical?: string[];
+ state: CaptureState;
+ theme: string;
+ variant?: ConditionVariant;
+ width: number;
+}
+
+export interface RunCapture {
+ caseGaps?: Record<string, string[]>;
+ conditions: ConditionCapture[];
+ containerRules: number;
+ pageErrors: string[];
+ states?: CaptureState[];
+ unparsedMedia: number;
+ unparsedSelectors: string[];
+ widths: number[];
+}
+
+export interface CaptureOptions {
+ browser: Browser;
+ conditions: ConditionConfig;
+ onCondition?: (condition: ConditionCapture) => void;
+ plan?: PageCondition[];
+ states?: readonly CaptureState[];
+ urls: Record<Side, string>;
+}
+
+const COLLECT = `
+ const __name = (target) => target;
+ const capture = ${captureInPage.toString()};
+ const result = {};
+ for (const section of document.querySelectorAll('[data-case]')) {
+ const key = section.getAttribute('data-case');
+ const failure = section.querySelector('[data-synthetic-error]');
+ if (failure) { result[key] = { error: failure.getAttribute('data-synthetic-error') }; continue; }
+ const skip = (element) => ['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName);
+ const keyOf = (target) => {
+ const path = [];
+ for (let node = target; node && node !== section; node = node.parentElement)
+ path.unshift([...node.parentElement.children].filter((child) => !skip(child)).indexOf(node));
+ return ['root', ...path].join('.');
+ };
+ const marked = section.querySelector('[data-synthetic-target]');
+ const targets = marked ? [marked] : [...section.querySelectorAll('[data-synthetic-element]')].filter((node) => !node.querySelector('[data-synthetic-element]'));
+ try { result[key] = { ...capture({ selector: '[data-case="' + CSS.escape(key) + '"]' }), targetKey: targets[0] ? keyOf(targets[0]) : 'root' }; }
+ catch (error) { result[key] = { error: String((error && error.message) || error) }; }
+ }
+`;
+
+const CAPTURE_ALL = `(() => {${COLLECT} return result; })()`;
+
+// Custom-property differences are always diagnostic in compareSnapshots, so they carry no verdict weight here.
+const CAPTURE_DIGESTS = `(() => {${COLLECT}
+ const hash = (text, seed) => {
+ let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
+ for (let index = 0; index < text.length; index++) {
+ const code = text.charCodeAt(index);
+ h1 = Math.imul(h1 ^ code, 2654435761);
+ h2 = Math.imul(h2 ^ code, 1597334677);
+ }
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
+ };
+ for (const value of Object.values(result)) {
+ if ('error' in value) continue;
+ value.styles = value.styles.map((style) => {
+ const kept = {};
+ for (const name in style) if (!name.startsWith('--')) kept[name] = style[name];
+ return kept;
+ });
+ }
+ window.__styleEquivalence = result;
+ const digests = {};
+ for (const [key, value] of Object.entries(result)) {
+ if ('error' in value) { digests[key] = value; continue; }
+ const text = JSON.stringify({ ...value, durationMs: 0 });
+ digests[key] = { digest: hash(text, 1) + ':' + hash(text, 2) + ':' + text.length };
+ }
+ return digests;
+})()`;
+
+export const CONDITION_CONCURRENCY = Math.max(
+ 1,
+ Math.min(4, Math.floor(availableParallelism() / 4)),
+);
+
+type Digest = { digest: string } | { error: string };
+
+export interface PageCondition {
+ state: CaptureState;
+ theme: string;
+ variant?: ConditionVariant;
+ width: number;
+}
+
+const urlFor = (url: string, { theme, variant }: PageCondition) => {
+ const target = new URL(url);
+ target.searchParams.set('theme', theme);
+ if (variant === 'rtl') target.searchParams.set('dir', 'rtl');
+ return target.toString();
+};
+
+export const conditionLabel = ({ state, theme, variant, width }: PageCondition) =>
+ [theme, width, state, variant].filter((part) => part !== undefined).join('/');
+
+const openPage = async (
+ browser: Browser,
+ url: string,
+ options: PageCondition,
+ pageErrors: string[],
+) => {
+ const page = await browser.newPage({
+ reducedMotion: options.variant === 'reduced-motion' ? 'reduce' : 'no-preference',
+ viewport: { height: 900, width: options.width },
+ });
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ try {
+ await page.goto(urlFor(url, options));
+ await page.waitForSelector('[data-synthetic-ready]', { state: 'attached', timeout: 30_000 });
+ await page.evaluate(() => document.fonts.ready);
+ await applyState(page, options.state);
+ await page.evaluate(
+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
+ );
+ return page;
+ } catch (error) {
+ await page.close();
+ throw error;
+ }
+};
+
+const evaluateOpen = async <T>(
+ browser: Browser,
+ url: string,
+ options: PageCondition,
+ pageErrors: string[],
+ script: string,
+) => {
+ const page = await openPage(browser, url, options, pageErrors);
+ try {
+ return { page, value: (await page.evaluate(script)) as T };
+ } catch (error) {
+ await page.close();
+ throw error;
+ }
+};
+
+export const capturePage = async (
+ browser: Browser,
+ url: string,
+ options: PageCondition,
+ pageErrors: string[],
+) => {
+ const { page, value } = await evaluateOpen<SectionSnapshots>(
+ browser,
+ url,
+ options,
+ pageErrors,
+ CAPTURE_ALL,
+ );
+ return { page, snapshots: value };
+};
+
+const sameDigest = (left?: Digest, right?: Digest) =>
+ Boolean(left && right && 'digest' in left && 'digest' in right && left.digest === right.digest);
+
+interface DeltaSnapshots {
+ reference: Record<string, string>;
+ sections: Record<string, SectionSnapshot & { deltas?: Array<Record<string, string | null>> }>;
+}
+
+const expand = ({ reference, sections }: DeltaSnapshots): SectionSnapshots =>
+ Object.fromEntries(
+ Object.entries(sections).map(([key, section]) => {
+ if (!('deltas' in section) || !section.deltas) return [key, section];
+ const { deltas, ...rest } = section;
+ const styles = deltas.map((delta) => {
+ const style: Record<string, string> = {};
+ for (const name in reference)
+ if (!(name in delta)) style[name] = reference[name];
+ else if (delta[name] !== null) style[name] = delta[name]!;
+ for (const name in delta)
+ if (!(name in reference) && delta[name] !== null) style[name] = delta[name]!;
+ return style;
+ });
+ return [key, { ...rest, styles }];
+ }),
+ );
+
+const snapshotsOf = async (page: Page, keys: string[]): Promise<SectionSnapshots> => {
+ if (!keys.length) return {};
+ const delta = await page.evaluate((wanted) => {
+ const stored = (
+ window as unknown as {
+ __styleEquivalence: Record<string, { error?: string; styles?: Record<string, string>[] }>;
+ }
+ ).__styleEquivalence;
+ const present = wanted.filter((key) => key in stored);
+ const counts = new Map<string, Map<string, number>>();
+ for (const key of present)
+ for (const style of stored[key].styles ?? [])
+ for (const name in style) {
+ const values = counts.get(name) ?? new Map<string, number>();
+ values.set(style[name], (values.get(style[name]) ?? 0) + 1);
+ counts.set(name, values);
+ }
+ const reference: Record<string, string> = {};
+ for (const [name, values] of counts) {
+ let best = '';
+ let most = 0;
+ for (const [value, count] of values)
+ if (count > most) {
+ best = value;
+ most = count;
+ }
+ reference[name] = best;
+ }
+ const sections: Record<string, unknown> = {};
+ for (const key of present) {
+ const { styles, ...rest } = stored[key];
+ if (!styles) {
+ sections[key] = stored[key];
+ continue;
+ }
+ sections[key] = {
+ ...rest,
+ deltas: styles.map((style) => {
+ const changed: Record<string, string | null> = {};
+ for (const name in reference)
+ if (!(name in style)) changed[name] = null;
+ else if (style[name] !== reference[name]) changed[name] = style[name];
+ return changed;
+ }),
+ };
+ }
+ return { reference, sections };
+ }, keys);
+ return expand(delta as DeltaSnapshots);
+};
+
+const withDigests = async <T>(
+ browser: Browser,
+ urls: string[],
+ options: PageCondition,
+ pageErrors: string[],
+ use: (loads: Array<{ page: Page; value: Record<string, Digest> }>) => Promise<T>,
+) => {
+ const settled = await Promise.allSettled(
+ urls.map((url) =>
+ evaluateOpen<Record<string, Digest>>(browser, url, options, pageErrors, CAPTURE_DIGESTS),
+ ),
+ );
+ const loads = settled.flatMap((item) => (item.status === 'fulfilled' ? [item.value] : []));
+ try {
+ const failed = settled.find((item) => item.status === 'rejected');
+ if (failed) throw failed.reason;
+ return await use(loads);
+ } finally {
+ await Promise.all(loads.map(({ page }) => page.close()));
+ }
+};
+
+const splitIdentical = (digests: Array<Record<string, Digest>>) => {
+ const keys = [...new Set(digests.flatMap((value) => Object.keys(value)))];
+ const identical = keys.filter((key) =>
+ digests.every((value) => sameDigest(digests[0][key], value[key])),
+ );
+ const skipped = new Set(identical);
+ return { identical, rest: keys.filter((key) => !skipped.has(key)) };
+};
+
+export const captureSections = (
+ browser: Browser,
+ urls: string[],
+ options: PageCondition,
+ pageErrors: string[],
+) =>
+ withDigests(browser, urls, options, pageErrors, async (loads) => {
+ const { identical, rest } = splitIdentical(loads.map(({ value }) => value));
+ const snapshots = await Promise.all(loads.map(({ page }) => snapshotsOf(page, rest)));
+ return { identical, snapshots };
+ });
+
+const captureCondition = (
+ browser: Browser,
+ urls: Record<Side, string>,
+ options: PageCondition,
+ pageErrors: string[],
+): Promise<ConditionCapture> =>
+ withDigests(browser, [urls.base, urls.base, urls.head], options, pageErrors, async (loads) => {
+ const [base, again, head] = loads;
+ const { identical, rest } = splitIdentical([base.value, again.value, head.value]);
+ const unstable = rest.filter((key) => !sameDigest(base.value[key], again.value[key]));
+ const [baseSnapshots, unstableSnapshots, headSnapshots] = await Promise.all([
+ snapshotsOf(base.page, rest),
+ snapshotsOf(again.page, unstable),
+ snapshotsOf(head.page, rest),
+ ]);
+ const againSnapshots: SectionSnapshots = {};
+ for (const key of rest)
+ if (key in unstableSnapshots) againSnapshots[key] = unstableSnapshots[key];
+ else if (key in baseSnapshots && key in again.value) againSnapshots[key] = baseSnapshots[key];
+ return {
+ base: baseSnapshots,
+ baseAgain: againSnapshots,
+ condition: conditionLabel(options),
+ head: headSnapshots,
+ identical,
+ ...options,
+ };
+ });
+
+export const conditionFromLabel = (label: string): PageCondition => {
+ const [theme, width, state, variant] = label.split('/');
+ return {
+ state: state as CaptureState,
+ theme,
+ variant: variant as ConditionVariant | undefined,
+ width: Number(width),
+ };
+};
+
+const captureConditions = async ({
+ browser,
+ onCondition,
+ plan,
+ urls,
+}: Pick<CaptureOptions, 'browser' | 'onCondition' | 'urls'> & {
+ plan: PageCondition[];
+}): Promise<RunCapture> => {
+ const pageErrors: string[] = [];
+ const captures: ConditionCapture[] = [];
+ const pending: Array<Promise<ConditionCapture> | undefined> = [];
+ const start = () => {
+ const index = pending.length;
+ if (index >= plan.length) return;
+ const task = captureCondition(browser, urls, plan[index], pageErrors);
+ task.catch(() => undefined);
+ pending.push(task);
+ };
+ for (let slot = 0; slot < CONDITION_CONCURRENCY; slot++) start();
+ for (let index = 0; index < plan.length; index++) {
+ const captured = await pending[index]!;
+ pending[index] = undefined;
+ start();
+ if (!onCondition) {
+ captures.push(captured);
+ continue;
+ }
+ onCondition(captured);
+ captures.push({ ...captured, base: {}, baseAgain: {}, head: {}, identical: [] });
+ }
+ return {
+ conditions: captures,
+ containerRules: 0,
+ pageErrors,
+ unparsedMedia: 0,
+ unparsedSelectors: [],
+ widths: [...new Set(plan.map((item) => item.width))],
+ };
+};
+
+const unmodeledRules = (found: RuleInspection) =>
+ Object.fromEntries(
+ Object.entries(found.unmodeled).map(([section, indices]) => [
+ section,
+ found.sectionRules?.[section] ?? indices.map((index) => found.rules[index]),
+ ]),
+ );
+
+export const inspectCaseGaps = async (
+ browser: Browser,
+ urls: Record<Side, string>,
+ options: PageCondition,
+ pageErrors: string[],
+) => {
+ const [base, head] = await Promise.all(
+ [urls.base, urls.head].map(async (url) => {
+ const page = await openPage(browser, url, { ...options, state: 'default' }, pageErrors);
+ try {
+ return unmodeledRules(await inspectRules(page));
+ } finally {
+ await page.close();
+ }
+ }),
+ );
+ return caseGapsOf(base, head);
+};
+
+export const captureRun = async ({
+ browser,
+ conditions,
+ onCondition,
+ plan: fixedPlan,
+ states,
+ urls,
+}: CaptureOptions): Promise<RunCapture> => {
+ if (fixedPlan) return captureConditions({ browser, onCondition, plan: fixedPlan, urls });
+ const pageErrors: string[] = [];
+ const media: string[] = [];
+ const pseudoRules: Partial<Record<Side, Record<string, string[]>>> = {};
+ const unmodeled: Partial<Record<Side, Record<string, string[]>>> = {};
+ let containerRules = 0;
+ const unparsedSelectors = new Set<string>();
+ for (const side of ['base', 'head'] as const) {
+ const page = await openPage(
+ browser,
+ urls[side],
+ { state: 'default', theme: conditions.themes[0], width: conditions.widths[0] },
+ pageErrors,
+ );
+ const found = await inspectRules(page);
+ media.push(...found.media);
+ pseudoRules[side] = found.pseudoRules;
+ unmodeled[side] = unmodeledRules(found);
+ containerRules += found.containers;
+ for (const selector of found.unparsed) unparsedSelectors.add(selector);
+ await page.close();
+ }
+ const { unparsed, widths } = planWidths(media, conditions.widths);
+ const plannedStates = states
+ ? [...states]
+ : planStates(pseudoRules.base ?? {}, pseudoRules.head ?? {});
+ const plan: PageCondition[] = [];
+ for (const theme of conditions.themes)
+ for (const width of widths)
+ for (const state of plannedStates) plan.push({ state, theme, width });
+ for (const variant of conditions.variants ?? DEFAULT_VARIANTS)
+ plan.push({
+ state: 'default',
+ theme: conditions.themes[0],
+ variant,
+ width: conditions.widths.at(-1)!,
+ });
+ const { conditions: captures, pageErrors: capturedErrors } = await captureConditions({
+ browser,
+ onCondition,
+ plan,
+ urls,
+ });
+ pageErrors.push(...capturedErrors);
+ return {
+ caseGaps: caseGapsOf(unmodeled.base ?? {}, unmodeled.head ?? {}),
+ conditions: captures,
+ containerRules,
+ pageErrors,
+ states: plannedStates,
+ unparsedMedia: unparsed,
+ unparsedSelectors: [...unparsedSelectors].sort(),
+ widths,
+ };
+};
diff --git a/scripts/stylexMigration/verification/browser/snapshot.test.ts b/packages/style-equivalence/src/capture/snapshot.test.ts
similarity index 100%
rename from scripts/stylexMigration/verification/browser/snapshot.test.ts
rename to packages/style-equivalence/src/capture/snapshot.test.ts
diff --git a/scripts/stylexMigration/verification/browser/snapshot.ts b/packages/style-equivalence/src/capture/snapshot.ts
similarity index 89%
rename from scripts/stylexMigration/verification/browser/snapshot.ts
rename to packages/style-equivalence/src/capture/snapshot.ts
index 79a5c053aee..0375a1f8b6a 100644
--- a/scripts/stylexMigration/verification/browser/snapshot.ts
+++ b/packages/style-equivalence/src/capture/snapshot.ts
@@ -1,3 +1,5 @@
+import { sameStyleValue } from './colors';
+
export interface SnapshotNode {
box: number[];
key: string;
@@ -29,6 +31,8 @@ export const captureInPage = (
geometry?: boolean;
properties?: string[];
selector?: string;
+ keyPrefix?: string;
+ originSelector?: string;
styleKeys?: string[];
} = {},
): StyleSnapshot => {
@@ -38,7 +42,7 @@ export const captureInPage = (
const elements = [root, ...root.querySelectorAll('*')].filter(
(element) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName),
);
- if (elements.length < 2) throw new Error('The component has not mounted');
+ if (elements.length < 2 && !options.keyPrefix) throw new Error('The component has not mounted');
const keys = new Map<Element, string>();
const walk = (element: Element, key: string) => {
keys.set(element, key);
@@ -46,15 +50,42 @@ export const captureInPage = (
.filter((child) => elements.includes(child))
.forEach((child, index) => walk(child, `${key}.${index}`));
};
- walk(root, 'root');
+ walk(root, `${options.keyPrefix ?? ''}root`);
if (options.collectMetadata)
elements.forEach((element, index) =>
- element.setAttribute('data-experiment-node', String(index)),
+ element.setAttribute('data-experiment-node', `${options.keyPrefix ?? ''}${index}`),
);
root.getBoundingClientRect();
const canonical = (value: Record<string, unknown>) =>
Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
const animationNames = new Map<string, string>();
+ const keyframeRules = new Map<string, string>();
+ const collectKeyframes = (rules: CSSRuleList) => {
+ for (const rule of rules) {
+ if (rule instanceof CSSKeyframesRule)
+ keyframeRules.set(
+ rule.name,
+ `keyframes:${[...rule.cssRules]
+ .map((frame) => {
+ const style = (frame as CSSKeyframeRule).style;
+ const body = [...style]
+ .sort()
+ .map((property) => `${property}:${style.getPropertyValue(property)}`)
+ .join(';');
+ return `${(frame as CSSKeyframeRule).keyText}{${body}}`;
+ })
+ .join('')}`,
+ );
+ else if ('cssRules' in rule) collectKeyframes((rule as CSSGroupingRule).cssRules);
+ }
+ };
+ for (const sheet of document.styleSheets) {
+ try {
+ collectKeyframes(sheet.cssRules);
+ } catch {
+ continue;
+ }
+ }
const animations: StyleSnapshot['animations'] = [];
for (const animation of document.getAnimations()) {
const effect = animation.effect;
@@ -103,7 +134,9 @@ export const captureInPage = (
}
}
}
- const origin = root.getBoundingClientRect();
+ const originRoot = options.originSelector ? document.querySelector(options.originSelector) : root;
+ if (!originRoot) throw new Error('CAPTURE_ORIGIN_MISSING');
+ const origin = originRoot.getBoundingClientRect();
const rounded = (value: number) => Math.round(value * 1000) / 1000;
const styles: StyleSnapshot['styles'] = [];
const interned = new Map<string, number>();
@@ -124,7 +157,12 @@ export const captureInPage = (
if (property === 'animation-name' && value !== 'none')
value = value
.split(',')
- .map((name) => animationNames.get(name.trim()) ?? `unresolved:${name.trim()}`)
+ .map(
+ (name) =>
+ keyframeRules.get(name.trim()) ??
+ animationNames.get(name.trim()) ??
+ `unresolved:${name.trim()}`,
+ )
.join(',');
values[property] = value;
propertyReads++;
@@ -181,7 +219,12 @@ export const captureInPage = (
attributes: [...element.attributes]
.filter(
(attribute) =>
- !['class', 'style', 'data-experiment-node'].includes(attribute.name),
+ ![
+ 'class',
+ 'style',
+ 'data-experiment-node',
+ 'data-stylex-verification-surface',
+ ].includes(attribute.name),
)
.map((attribute): [string, string] => [attribute.name, attribute.value])
.sort(([a], [b]) => (a < b ? -1 : 1)),
@@ -362,7 +405,7 @@ export const compareSnapshots = (
const oldStyle = before.styles[oldNode.style];
const newStyle = after.styles[newNode.style];
for (const property of new Set([...Object.keys(oldStyle), ...Object.keys(newStyle)])) {
- if (oldStyle[property] !== newStyle[property])
+ if (!sameStyleValue(oldStyle[property], newStyle[property]))
differences.push({ after: newStyle[property], before: oldStyle[property], key, property });
}
}
diff --git a/packages/style-equivalence/src/capture/states.ts b/packages/style-equivalence/src/capture/states.ts
new file mode 100644
index 00000000000..5ccd4af7e03
--- /dev/null
+++ b/packages/style-equivalence/src/capture/states.ts
@@ -0,0 +1,48 @@
+import type { Page } from '@playwright/test';
+
+export const STATES = ['default', 'hover-chain', 'hover-target', 'focus-visible'] as const;
+export type CaptureState = (typeof STATES)[number] | `force-chain:${string}` | `force:${string}`;
+
+const TARGETS = '[data-case] [data-synthetic-element]:not(:has([data-synthetic-element]))';
+const CHAIN = '[data-case] [data-synthetic-element]';
+
+const forcing = (state: Exclude<CaptureState, 'default'>) => {
+ if (state === 'hover-chain') return { pseudos: ['hover'], selector: CHAIN };
+ if (state === 'hover-target') return { pseudos: ['hover'], selector: TARGETS };
+ if (state === 'focus-visible') return { pseudos: ['focus-visible'], selector: TARGETS };
+ const [mode, list] = state.split(':');
+ return { pseudos: list.split('+'), selector: mode === 'force-chain' ? CHAIN : TARGETS };
+};
+
+const differs = (left: string[] = [], right: string[] = []) =>
+ [...new Set(left)].sort().join('\n') !== [...new Set(right)].sort().join('\n');
+
+export const planStates = (
+ base: Record<string, string[]>,
+ head: Record<string, string[]>,
+): CaptureState[] => {
+ const extra = new Set<CaptureState>();
+ for (const key of new Set([...Object.keys(base), ...Object.keys(head)])) {
+ if (!differs(base[key], head[key])) continue;
+ if (key.startsWith('chain:')) {
+ const states = key.slice('chain:'.length);
+ if (states !== 'hover') extra.add(`force-chain:${states}`);
+ continue;
+ }
+ if (key === 'hover' || key === 'focus-visible') continue;
+ extra.add(key === 'focus-within' ? 'force-chain:focus-within' : `force:${key}`);
+ }
+ return [...STATES, ...[...extra].sort()];
+};
+
+export const applyState = async (page: Page, state: CaptureState) => {
+ if (state === 'default') return;
+ const { pseudos, selector } = forcing(state);
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('DOM.enable');
+ await cdp.send('CSS.enable');
+ const { root } = await cdp.send('DOM.getDocument', { depth: -1 });
+ const { nodeIds } = await cdp.send('DOM.querySelectorAll', { nodeId: root.nodeId, selector });
+ for (const nodeId of nodeIds)
+ await cdp.send('CSS.forcePseudoState', { forcedPseudoClasses: pseudos, nodeId });
+};
diff --git a/packages/style-equivalence/src/capture/staticServer.ts b/packages/style-equivalence/src/capture/staticServer.ts
new file mode 100644
index 00000000000..34d9ce92f5a
--- /dev/null
+++ b/packages/style-equivalence/src/capture/staticServer.ts
@@ -0,0 +1,53 @@
+import { createReadStream } from 'node:fs';
+import { realpath, stat } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import path from 'node:path';
+
+const TYPES: Record<string, string> = {
+ '.css': 'text/css',
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript',
+ '.json': 'application/json',
+ '.svg': 'image/svg+xml',
+ '.woff2': 'font/woff2',
+};
+
+export const resolveInside = async (root: string, requestPath: string) => {
+ const base = await realpath(root);
+ let decoded: string;
+ try {
+ decoded = decodeURIComponent(requestPath);
+ } catch {
+ return undefined;
+ }
+ const candidate = path.resolve(base, `.${path.posix.normalize(`/${decoded}`)}`);
+ let file = candidate;
+ try {
+ if ((await stat(candidate)).isDirectory()) file = path.join(candidate, 'index.html');
+ file = await realpath(file);
+ } catch {
+ return undefined;
+ }
+ return file === base || file.startsWith(base + path.sep) ? file : undefined;
+};
+
+export const serveDirectories = async (root: string) => {
+ const server = createServer(async (request, response) => {
+ const file = await resolveInside(root, new URL(request.url ?? '/', 'http://x').pathname);
+ if (!file) {
+ response.writeHead(404).end();
+ return;
+ }
+ response.writeHead(200, {
+ 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream',
+ });
+ createReadStream(file).pipe(response);
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+ return {
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ url: `http://127.0.0.1:${port}`,
+ };
+};
diff --git a/packages/style-equivalence/src/capture/widths.test.ts b/packages/style-equivalence/src/capture/widths.test.ts
new file mode 100644
index 00000000000..f00544a132a
--- /dev/null
+++ b/packages/style-equivalence/src/capture/widths.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { planWidths } from './widths';
+
+describe('planWidths', () => {
+ it('probes integer widths on both sides of a fractional boundary', () => {
+ expect(planWidths(['(max-width: 479.98px)'], [1280]).widths).toEqual([400, 479, 480, 1280]);
+ });
+
+ it('probes the last matching and first non-matching width of each bound', () => {
+ expect(planWidths(['(width < 600px)'], [1280]).widths).toEqual([460, 599, 600, 1280]);
+ expect(planWidths(['(max-width: 600px)'], [1280]).widths).toEqual([460, 600, 601, 1280]);
+ expect(planWidths(['(min-width: 600px)'], [1280]).widths).toEqual([460, 599, 600, 1280]);
+ });
+});
diff --git a/packages/style-equivalence/src/capture/widths.ts b/packages/style-equivalence/src/capture/widths.ts
new file mode 100644
index 00000000000..d6b941869df
--- /dev/null
+++ b/packages/style-equivalence/src/capture/widths.ts
@@ -0,0 +1,35 @@
+import { parseWidthCondition, type WidthCondition } from './conditionPartitions';
+
+export const WIDTH_DOMAIN = [320, 1920] as const;
+
+const probesAround = ({ operator, value }: WidthCondition['bounds'][number]) => {
+ if (operator === '<' || operator === '>=') return [Math.ceil(value) - 1, Math.ceil(value)];
+ if (operator === '<=' || operator === '>') return [Math.floor(value), Math.floor(value) + 1];
+ return Number.isInteger(value)
+ ? [value - 1, value, value + 1]
+ : [Math.floor(value), Math.ceil(value)];
+};
+
+export const planWidths = (media: string[], preferred: number[]) => {
+ const conditions = media.map(parseWidthCondition).filter(Boolean) as WidthCondition[];
+ const [minimum, maximum] = WIDTH_DOMAIN;
+ const probes = [
+ ...new Set(
+ conditions
+ .flatMap((condition) => condition.bounds)
+ .filter(({ value }) => value > minimum && value < maximum)
+ .flatMap(probesAround),
+ ),
+ ].sort((a, b) => a - b);
+ const edges = [minimum, ...probes, maximum];
+ const widths = new Set([...preferred, ...probes]);
+ for (let index = 1; index < edges.length; index++) {
+ const [low, high] = [edges[index - 1], edges[index]];
+ if (![...widths].some((width) => width > low && width < high))
+ widths.add(Math.round((low + high) / 2));
+ }
+ return {
+ unparsed: media.length - conditions.length,
+ widths: [...widths].sort((a, b) => a - b),
+ };
+};
diff --git a/packages/style-equivalence/src/cli/index.ts b/packages/style-equivalence/src/cli/index.ts
new file mode 100644
index 00000000000..6c4fac05220
--- /dev/null
+++ b/packages/style-equivalence/src/cli/index.ts
@@ -0,0 +1,249 @@
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { parseArgs, promisify } from 'node:util';
+
+import { loadConfig, runComparison } from '../run';
+import { runSelfTest } from '../selftest';
+import { formatSelfTest } from '../selftest/run';
+import { saveSelfTest } from '../selftest/store';
+import { DEFAULT_UI_DIR, startServer } from '../server';
+import { loadRun } from '../server/api';
+import { runStack } from '../stack';
+import { annotateList, applyNotes, latestRunForPr, type NoteInput, reworkList } from './review';
+import { formatStack, formatSummary } from './summary';
+import { uiBuildStale } from './uiBuild';
+
+const run = promisify(execFile);
+
+const HELP = `style-equivalence — compare styled elements between two revisions
+
+ bun run style-eq --pr <number>
+ bun run style-eq --base <ref> --head <ref>
+ bun run style-eq --stack [--stack-base <branch>]
+ bun run style-eq self-test
+ bun run style-eq serve <run-id|run-dir> [--port <n>] [--pin]
+ bun run style-eq rework <run-id|run-dir|--pr <number>> [--json]
+ bun run style-eq annotate <run-id|run-dir> [--json] [--apply <notes.json>]
+
+Options:
+ --config <file> project config (default scripts/stylexMigration/style-equivalence.config.ts)
+ --records <dir> evidence directory (default .records/style-equivalence)
+ --keep-worktrees keep base/head worktrees for debugging
+ --skip-calibration do not run the project's real-mount calibration
+ --mutations <n> mutants to sample from equal cases (default 10, 0 turns it off)
+ --pin serve exactly this run instead of following newer runs on the same base
+`;
+
+const DEFAULT_STACK_BASE = 'test/stylex-migration-stack';
+
+const revParse = async (repo: string, ref: string) =>
+ (await run('git', ['-C', repo, 'rev-parse', '--verify', `${ref}^{commit}`])).stdout.trim();
+
+const ensureObject = async (repo: string, sha: string) => {
+ try {
+ await run('git', ['-C', repo, 'cat-file', '-e', `${sha}^{commit}`]);
+ } catch {
+ await run('git', ['-C', repo, 'fetch', '--quiet', 'origin', sha]);
+ }
+};
+
+const resolvePullRequest = async (repo: string, pr: string) => {
+ if (!/^[1-9]\d*$/.test(pr)) throw new Error('INVALID_PR_NUMBER');
+ const { stdout } = await run(
+ 'gh',
+ ['pr', 'view', pr, '--json', 'baseRefOid,headRefOid,headRefName,number,title'],
+ { cwd: repo },
+ );
+ const { baseRefOid, headRefName, headRefOid, number, title } = JSON.parse(stdout) as {
+ baseRefOid: string;
+ headRefName: string;
+ headRefOid: string;
+ number: number;
+ title: string;
+ };
+ await ensureObject(repo, baseRefOid);
+ await ensureObject(repo, headRefOid);
+ return { base: baseRefOid, head: headRefOid, pr: { branch: headRefName, number, title } };
+};
+
+const main = async () => {
+ const { positionals, values } = parseArgs({
+ allowPositionals: true,
+ options: {
+ 'apply': { type: 'string' },
+ 'base': { type: 'string' },
+ 'config': { type: 'string' },
+ 'head': { type: 'string' },
+ 'help': { short: 'h', type: 'boolean' },
+ 'json': { type: 'boolean' },
+ 'keep-worktrees': { type: 'boolean' },
+ 'mutations': { type: 'string' },
+ 'pin': { type: 'boolean' },
+ 'port': { type: 'string' },
+ 'pr': { type: 'string' },
+ 'records': { type: 'string' },
+ 'skip-calibration': { type: 'boolean' },
+ 'stack': { type: 'boolean' },
+ 'stack-base': { type: 'string' },
+ },
+ });
+ if (values.help) return void console.log(HELP);
+ const repo = process.cwd();
+ const configFile = path.resolve(
+ values.config ?? 'scripts/stylexMigration/style-equivalence.config.ts',
+ );
+ const recordsDir = path.resolve(values.records ?? '.records/style-equivalence');
+ if (positionals[0] === 'self-test') {
+ const report = await runSelfTest({ configFile, recordsDir, repo });
+ await saveSelfTest(recordsDir, report, new Date().toISOString());
+ console.log(formatSelfTest(report));
+ process.exitCode = report.passed ? 0 : 1;
+ return;
+ }
+ const runDirOf = async (target: string | undefined) => {
+ if (!target && values.pr) return latestRunForPr(recordsDir, Number(values.pr));
+ if (!target) throw new Error('Specify a run id, a run directory or --pr <number>');
+ const dir = existsSync(path.resolve(target))
+ ? path.resolve(target)
+ : path.join(recordsDir, target);
+ if (!existsSync(path.join(dir, 'run.json'))) throw new Error(`No stored run at ${dir}`);
+ return dir;
+ };
+ if (positionals[0] === 'rework') {
+ const stored = await loadRun(await runDirOf(positionals[1]));
+ console.log(await reworkList(stored, values.json ? 'json' : 'text'));
+ return;
+ }
+ if (positionals[0] === 'annotate') {
+ const stored = await loadRun(await runDirOf(positionals[1]));
+ if (values.apply) {
+ const notes = JSON.parse(await readFile(path.resolve(values.apply), 'utf8')) as NoteInput[];
+ await applyNotes(stored, notes);
+ console.log(`Stored ${notes.length} notes.`);
+ return;
+ }
+ const list = await annotateList(stored);
+ if (values.json) return void console.log(JSON.stringify(list, null, 2));
+ if (!list.length) return void console.log('没有需要 agent 读码的项。');
+ for (const entry of list)
+ console.log(
+ [
+ `- ${entry.key} [${entry.state}]`,
+ ` ${entry.ask}`,
+ ` ${entry.source.base}`,
+ ` ${entry.source.head}`,
+ ].join('\n'),
+ );
+ return;
+ }
+ if (positionals[0] === 'serve') {
+ const target = positionals[1];
+ if (!target) throw new Error('serve takes a run id or run directory');
+ const runDir = existsSync(path.resolve(target))
+ ? path.resolve(target)
+ : path.join(recordsDir, target);
+ if (!existsSync(path.join(runDir, 'run.json'))) throw new Error(`No stored run at ${runDir}`);
+ const packageDir = path.resolve(import.meta.dirname, '../..');
+ const uiSources = [
+ path.join(packageDir, 'src'),
+ path.join(packageDir, 'report.vite.config.ts'),
+ ];
+ if (await uiBuildStale(DEFAULT_UI_DIR, uiSources)) {
+ console.log('Building the report UI…');
+ await run('bunx', ['vite', 'build', '--config', 'report.vite.config.ts'], {
+ cwd: packageDir,
+ maxBuffer: 64 * 1024 ** 2,
+ });
+ }
+ const layoutComponents = await loadConfig(configFile).then(
+ (config) => config.layoutComponents,
+ (): string[] => [],
+ );
+ const server = await startServer({
+ layoutComponents,
+ pin: values.pin ?? false,
+ port: Number(values.port ?? 0),
+ recordsDir,
+ runDir,
+ });
+ console.log(`Report: ${server.url}`);
+ await new Promise<void>((resolve) => {
+ process.once('SIGINT', resolve);
+ process.once('SIGTERM', resolve);
+ });
+ await server.stop();
+ return;
+ }
+ if (positionals.length) throw new Error(`Unknown command ${positionals[0]}`);
+ if (values.mutations !== undefined && !/^\d+$/.test(values.mutations))
+ throw new Error('--mutations takes a non-negative integer');
+ const mutations = values.mutations === undefined ? undefined : Number(values.mutations);
+ if (values.stack) {
+ const stackBase = values['stack-base'] ?? DEFAULT_STACK_BASE;
+ const { stdout } = await run(
+ 'gh',
+ [
+ 'pr',
+ 'list',
+ '--base',
+ stackBase,
+ '--state',
+ 'open',
+ '--limit',
+ '200',
+ '--json',
+ 'number,headRefOid',
+ ],
+ { cwd: repo },
+ );
+ const heads = (JSON.parse(stdout) as Array<{ headRefOid: string; number: number }>)
+ .sort((a, b) => a.number - b.number)
+ .map((pr) => ({ id: String(pr.number), sha: pr.headRefOid }));
+ await ensureObject(repo, await revParse(repo, stackBase));
+ for (const head of heads) await ensureObject(repo, head.sha);
+ const result = await runStack({
+ base: stackBase,
+ configFile,
+ heads,
+ mutations,
+ recordsDir,
+ repo,
+ });
+ console.log(formatStack(result));
+ process.exitCode = result.mergeable ? 0 : result.conflicts.length ? 3 : 1;
+ return;
+ }
+ const revisions = values.pr
+ ? await resolvePullRequest(repo, values.pr)
+ : values.base && values.head
+ ? { base: values.base, head: values.head }
+ : undefined;
+ if (!revisions) throw new Error('Specify --pr <number>, --stack or both --base and --head');
+ const result = await runComparison({
+ ...revisions,
+ calibrate: !values['skip-calibration'],
+ configFile,
+ keepWorktrees: values['keep-worktrees'],
+ mutations,
+ recordsDir,
+ repo,
+ });
+ console.log(formatSummary(result));
+ const open = (category: string) =>
+ result.verdict.items.some((item) => item.category === category && item.signoff !== 'valid');
+ const mismatch = result.calibration.some((entry) => entry.status === 'mismatch');
+ process.exitCode = result.verdict.mergeable
+ ? 0
+ : open('blocking') || !result.mutation.passed || mismatch
+ ? 3
+ : open('difference')
+ ? 1
+ : 2;
+};
+
+main().catch((error) => {
+ console.error(error);
+ process.exitCode = 3;
+});
diff --git a/packages/style-equivalence/src/cli/review.ts b/packages/style-equivalence/src/cli/review.ts
new file mode 100644
index 00000000000..a0de2c59f7a
--- /dev/null
+++ b/packages/style-equivalence/src/cli/review.ts
@@ -0,0 +1,102 @@
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { writeReviews } from '../review/store';
+import type { StoredRun } from '../server/api';
+import { reviewPayload, reviewState } from '../server/review';
+
+const shortKey = (key: string) => key.slice(key.indexOf('|') + 1);
+
+const header = (stored: StoredRun) => {
+ const pr = stored.run.pr as { branch?: string; number?: number; title?: string } | undefined;
+ const range = `${String(stored.run.base ?? '').slice(0, 7)}..${String(stored.run.head ?? '').slice(0, 7)}`;
+ return pr?.number ? `#${pr.number} ${pr.title ?? ''}(${pr.branch ?? ''})${range}` : range;
+};
+
+export const reworkList = async (stored: StoredRun, format: 'json' | 'text' = 'text') => {
+ const payload = await reviewPayload(stored);
+ const open = payload.items.filter((item) => item.state === 'reworked' && item.rework);
+ if (format === 'json')
+ return JSON.stringify({ items: open, pr: payload.pr, run: payload.run }, null, 2);
+ if (!open.length) return `${header(stored)}\n没有未处理的打回。`;
+ return [
+ header(stored),
+ ...open.map((item) =>
+ [
+ `- ${shortKey(item.key)}(${item.title})`,
+ ` 文件:${item.file}`,
+ ` 原因:${item.rework!.note}`,
+ ...(item.summary.length ? [` 工具看到:${item.summary.join(';')}`] : []),
+ ...(item.differingConditions.length
+ ? [` 不一致的条件:${item.differingConditions.slice(0, 6).join(', ')}`]
+ : []),
+ ].join('\n'),
+ ),
+ ].join('\n');
+};
+
+export 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,
+ }));
+};
+
+export interface NoteInput {
+ finding: string;
+ key: string;
+ suggestion: 'pass' | 'rework';
+}
+
+export const applyNotes = async (stored: StoredRun, notes: NoteInput[]) => {
+ const { items } = await reviewState(stored);
+ const now = new Date().toISOString();
+ for (const note of notes) {
+ const item = items.find((entry) => entry.key === note.key);
+ if (!item) throw new Error(`UNKNOWN_CASE:${note.key}`);
+ 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}`);
+ await writeReviews(stored.recordsDir, item.file, {
+ notes: [
+ {
+ at: now,
+ finding: note.finding.trim(),
+ hash: item.hash,
+ key: item.key,
+ suggestion: note.suggestion,
+ },
+ ],
+ });
+ }
+};
+
+export const latestRunForPr = async (recordsDir: string, pr: number) => {
+ const runs = (await readdir(recordsDir, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && /^\d{4}-/.test(entry.name))
+ .map((entry) => entry.name)
+ .sort()
+ .reverse();
+ for (const run of runs) {
+ try {
+ const meta = JSON.parse(await readFile(path.join(recordsDir, run, 'run.json'), 'utf8'));
+ if (meta.pr?.number === pr) return path.join(recordsDir, run);
+ } catch {
+ continue;
+ }
+ }
+ throw new Error(`NO_RUN_FOR_PR:${pr}`);
+};
diff --git a/packages/style-equivalence/src/cli/summary.test.ts b/packages/style-equivalence/src/cli/summary.test.ts
new file mode 100644
index 00000000000..6e9b26949f7
--- /dev/null
+++ b/packages/style-equivalence/src/cli/summary.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatStack, formatSummary } from './summary';
+
+describe('formatSummary', () => {
+ it('prints the counts, the top root causes and where the evidence is', () => {
+ const text = formatSummary({
+ base: '60dee1474d670923619b9243e7863b3de82dcb3c',
+ calibration: [
+ {
+ detail: '',
+ file: 'src/Controls.tsx',
+ fixture: 'difference',
+ fixtureId: 'Controls',
+ status: 'agree',
+ synthetic: 'difference',
+ },
+ {
+ detail: 'exit 3',
+ file: 'src/A.tsx',
+ fixture: 'inconclusive',
+ fixtureId: 'A',
+ status: 'inconclusive',
+ synthetic: 'equal',
+ },
+ ],
+ cases: [
+ {
+ category: 'difference',
+ key: 'src/Controls.tsx|SectionHeader#0',
+ result: {
+ differingConditions: ['light/375/default', 'dark/375/default'],
+ rootCauses: [
+ {
+ after: 'normal',
+ before: '"cv01", "kern", "tnum"',
+ key: 'root.0',
+ property: 'font-feature-settings',
+ },
+ ],
+ },
+ },
+ {
+ category: 'needs-signoff',
+ key: 'src/Controls.tsx|ControlLabel#0',
+ result: { differingConditions: [], rootCauses: [] },
+ },
+ {
+ category: 'equal',
+ key: 'src/A.tsx|A#0',
+ result: { differingConditions: [], rootCauses: [] },
+ },
+ {
+ category: 'blocking',
+ key: 'src/B.tsx|B#0',
+ result: { differingConditions: [], rootCauses: [] },
+ },
+ ],
+ comparisons: 96,
+ durationMs: 81_500,
+ files: ['src/Controls.tsx', 'src/A.tsx', 'src/B.tsx'],
+ head: 'f0a8fd0ce5202864e5c6f8c81dceabaafb7978a3',
+ mutation: {
+ caught: 9,
+ equivalent: 2,
+ evaluated: 9,
+ mutants: [],
+ passed: true,
+ requested: 10,
+ },
+ runDir: '/repo/.records/style-equivalence/run-1',
+ verdict: {
+ items: [
+ { category: 'difference', key: 'src/Controls.tsx|SectionHeader#0' },
+ { category: 'needs-signoff', key: 'src/Controls.tsx|ControlLabel#0' },
+ { category: 'needs-signoff', key: 'src/A.tsx|file' },
+ { category: 'equal', key: 'src/A.tsx|A#0' },
+ { category: 'blocking', key: 'src/B.tsx|B#0' },
+ { category: 'unpaired', key: 'src/B.tsx|unpaired:base:B#1' },
+ { category: 'unpaired', key: 'src/B.tsx|unpaired:base:B#2' },
+ { category: 'unpaired', key: 'src/B.tsx|unpaired:head:B#3' },
+ ],
+ mergeable: false,
+ reasons: ['blocking 1', 'difference 1', 'needs sign-off 2', 'unpaired 3'],
+ },
+ });
+ expect(text.split('\n')).toEqual([
+ 'verdict not mergeable: blocking 1 · difference 1 · needs sign-off 2 · unpaired 3',
+ 'style-equivalence 60dee14..f0a8fd0 · 3 files · 4 cases · 96 comparisons · 82s',
+ 'difference 1 · needs sign-off 2 (1 cases · 1 files) · unpaired 3 · blocking 1 · equal 1',
+ 'mutation 9/9 caught · 2 equivalent dropped (requested 10)',
+ 'calibration 1 agree · 0 mismatch · 1 inconclusive',
+ 'Top root causes:',
+ ' src/Controls.tsx|SectionHeader#0 font-feature-settings: "cv01", "kern", "tnum" → normal (2 conditions)',
+ 'Evidence: /repo/.records/style-equivalence/run-1',
+ ]);
+ });
+
+ it('names the missed mutants when mutation testing fails', () => {
+ const text = formatSummary({
+ base: 'a'.repeat(40),
+ calibration: [
+ {
+ detail: '',
+ file: 'src/B.tsx',
+ fixture: 'difference',
+ fixtureId: 'B',
+ status: 'mismatch',
+ synthetic: 'equal',
+ },
+ ],
+ cases: [],
+ comparisons: 0,
+ durationMs: 0,
+ files: [],
+ head: 'b'.repeat(40),
+ mutation: {
+ caught: 1,
+ equivalent: 0,
+ evaluated: 2,
+ mutants: [
+ { caseKey: 'src/A.tsx|A#0', description: 'numeric: 8px → 9px', outcome: 'missed' },
+ { caseKey: 'src/B.tsx|B#0', description: 'delete-state: &:hover', outcome: 'caught' },
+ ],
+ passed: false,
+ requested: 2,
+ },
+ runDir: '/r',
+ verdict: { items: [], mergeable: false, reasons: ['mutation not fully caught'] },
+ });
+ expect(text.split('\n')[0]).toBe('verdict not mergeable: mutation not fully caught');
+ expect(text.split('\n').slice(3, 7)).toEqual([
+ 'mutation FAILED 1/2 caught',
+ ' missed src/A.tsx|A#0 numeric: 8px → 9px',
+ 'calibration 0 agree · 1 mismatch · 0 inconclusive',
+ ' mismatch B (src/B.tsx): real mount difference, synthetic equal',
+ ]);
+ });
+});
+
+describe('formatStack', () => {
+ it('prints one line per PR shard and the conflicts', () => {
+ const text = formatStack({
+ base: 'a'.repeat(40),
+ conflicts: [{ files: ['src/A.tsx'], id: '21459' }],
+ head: 'c'.repeat(40),
+ mergeable: false,
+ merged: ['21446', '21452'],
+ resolved: [{ files: ['scripts/legacyFiles.json'], id: '21452' }],
+ shards: [
+ {
+ files: ['x'],
+ id: '21446',
+ result: { runDir: '/r/1', verdict: { mergeable: true, reasons: [] } },
+ },
+ {
+ files: ['y', 'z'],
+ id: '21452',
+ result: { runDir: '/r/2', verdict: { mergeable: false, reasons: ['difference 6'] } },
+ },
+ ],
+ });
+ expect(text.split('\n')).toEqual([
+ 'stack verdict not mergeable · aaaaaaa..ccccccc · merged 2 · conflicts 1 · shards 2',
+ ' conflict #21459 src/A.tsx',
+ ' kept stack side #21452 scripts/legacyFiles.json',
+ ' #21446 mergeable (1 files) /r/1',
+ ' #21452 not mergeable: difference 6 (2 files) /r/2',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/cli/summary.ts b/packages/style-equivalence/src/cli/summary.ts
new file mode 100644
index 00000000000..c0431c1fc35
--- /dev/null
+++ b/packages/style-equivalence/src/cli/summary.ts
@@ -0,0 +1,117 @@
+import type { CalibrationResult } from '../calibration';
+import type { StyleDifference } from '../capture/snapshot';
+import type { MutantResult, MutationReport } from '../mutation/run';
+import type { Verdict, VerdictItem } from '../verdict';
+import type { CaseCategory } from '../verdict/categorize';
+
+export interface SummaryInput {
+ base: string;
+ calibration: CalibrationResult[];
+ cases: Array<{
+ category: CaseCategory;
+ key: string;
+ result: { differingConditions: string[]; rootCauses: StyleDifference[] };
+ }>;
+ comparisons: number;
+ durationMs: number;
+ files: string[];
+ head: string;
+ mutation: Omit<MutationReport, 'mutants'> & {
+ mutants: Array<Pick<MutantResult, 'caseKey' | 'description' | 'outcome'>>;
+ };
+ runDir: string;
+ verdict: Pick<Verdict, 'mergeable' | 'reasons'> & {
+ items: Array<Pick<VerdictItem, 'category' | 'key'>>;
+ };
+}
+
+const TOP = 10;
+
+const calibrationLines = ({ calibration }: SummaryInput) => {
+ if (!calibration.length) return [];
+ const count = (status: CalibrationResult['status']) =>
+ calibration.filter((entry) => entry.status === status).length;
+ return [
+ `calibration ${count('agree')} agree · ${count('mismatch')} mismatch · ${count('inconclusive')} inconclusive`,
+ ...calibration
+ .filter((entry) => entry.status === 'mismatch')
+ .map(
+ (entry) =>
+ ` mismatch ${entry.fixtureId} (${entry.file}): real mount ${entry.fixture}, synthetic ${entry.synthetic}`,
+ ),
+ ];
+};
+
+const mutationLines = ({ mutation }: SummaryInput) => {
+ if (!mutation.requested) return ['mutation off'];
+ if (mutation.error) return [`mutation FAILED: ${mutation.error.split('\n')[0]}`];
+ if (!mutation.passed)
+ return [
+ `mutation FAILED ${mutation.caught}/${mutation.evaluated} caught`,
+ ...mutation.mutants
+ .filter((mutant) => mutant.outcome === 'missed' || mutant.outcome === 'error')
+ .map((mutant) => ` ${mutant.outcome} ${mutant.caseKey} ${mutant.description}`),
+ ];
+ return [
+ `mutation ${mutation.caught}/${mutation.evaluated} caught · ${mutation.equivalent} equivalent dropped (requested ${mutation.requested})`,
+ ];
+};
+
+const countLine = ({ verdict }: SummaryInput) => {
+ const of = (category: VerdictItem['category']) =>
+ verdict.items.filter((item) => item.category === category);
+ const signoff = of('needs-signoff');
+ const files = signoff.filter((item) => item.key.endsWith('|file')).length;
+ return `difference ${of('difference').length} · needs sign-off ${signoff.length} (${signoff.length - files} cases · ${files} files) · unpaired ${of('unpaired').length} · blocking ${of('blocking').length} · equal ${of('equal').length}`;
+};
+
+export const formatSummary = (input: SummaryInput) => {
+ const lines = [
+ input.verdict.mergeable
+ ? 'verdict mergeable'
+ : `verdict not mergeable: ${input.verdict.reasons.join(' · ')}`,
+ `style-equivalence ${input.base.slice(0, 7)}..${input.head.slice(0, 7)} · ${input.files.length} files · ${input.cases.length} cases · ${input.comparisons} comparisons · ${Math.round(input.durationMs / 1000)}s`,
+ countLine(input),
+ ...mutationLines(input),
+ ...calibrationLines(input),
+ ];
+ const differences = input.cases.filter((entry) => entry.category === 'difference').slice(0, TOP);
+ if (differences.length) {
+ lines.push('Top root causes:');
+ for (const entry of differences) {
+ const [cause] = entry.result.rootCauses;
+ lines.push(
+ ` ${entry.key} ${cause ? `${cause.property}: ${cause.before} → ${cause.after}` : 'difference'} (${entry.result.differingConditions.length} conditions)`,
+ );
+ }
+ }
+ lines.push(`Evidence: ${input.runDir}`);
+ return lines.join('\n');
+};
+
+export interface StackSummaryInput {
+ base: string;
+ conflicts: Array<{ files: string[]; id: string }>;
+ head: string;
+ mergeable: boolean;
+ merged: string[];
+ resolved: Array<{ files: string[]; id: string }>;
+ shards: Array<{
+ files: string[];
+ id: string;
+ result: { runDir: string; verdict: Pick<Verdict, 'mergeable' | 'reasons'> };
+ }>;
+}
+
+export const formatStack = (input: StackSummaryInput) =>
+ [
+ `stack verdict ${input.mergeable ? 'mergeable' : 'not mergeable'} · ${input.base.slice(0, 7)}..${input.head.slice(0, 7)} · merged ${input.merged.length} · conflicts ${input.conflicts.length} · shards ${input.shards.length}`,
+ ...input.conflicts.map(
+ (conflict) => ` conflict #${conflict.id} ${conflict.files.join(', ')}`,
+ ),
+ ...input.resolved.map((entry) => ` kept stack side #${entry.id} ${entry.files.join(', ')}`),
+ ...input.shards.map(
+ ({ files, id, result }) =>
+ ` #${id} ${result.verdict.mergeable ? 'mergeable' : `not mergeable: ${result.verdict.reasons.join(' · ')}`} (${files.length} files) ${result.runDir}`,
+ ),
+ ].join('\n');
diff --git a/packages/style-equivalence/src/cli/uiBuild.test.ts b/packages/style-equivalence/src/cli/uiBuild.test.ts
new file mode 100644
index 00000000000..decc0838ae3
--- /dev/null
+++ b/packages/style-equivalence/src/cli/uiBuild.test.ts
@@ -0,0 +1,47 @@
+import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { uiBuildStale } from './uiBuild';
+
+let root: string;
+
+const touch = async (file: string, seconds: number) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, '');
+ await utimes(file, seconds, seconds);
+};
+
+afterEach(async () => {
+ if (root) await rm(root, { force: true, recursive: true });
+});
+
+describe('uiBuildStale', () => {
+ it('rebuilds when there is no build yet', async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'ui-build-'));
+ await touch(path.join(root, 'src/report/ui/App.tsx'), 100);
+ expect(await uiBuildStale(path.join(root, 'ui/dist'), [path.join(root, 'src')])).toBe(true);
+ });
+
+ it('rebuilds when a source file is newer than the build', async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'ui-build-'));
+ await touch(path.join(root, 'ui/dist/index.html'), 100);
+ await touch(path.join(root, 'src/report/ui/nested/Review.tsx'), 200);
+ expect(await uiBuildStale(path.join(root, 'ui/dist'), [path.join(root, 'src')])).toBe(true);
+ });
+
+ it('keeps a build that is newer than every source file', async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'ui-build-'));
+ await touch(path.join(root, 'src/report/ui/App.tsx'), 100);
+ await touch(path.join(root, 'report.vite.config.ts'), 100);
+ await touch(path.join(root, 'ui/dist/index.html'), 200);
+ expect(
+ await uiBuildStale(path.join(root, 'ui/dist'), [
+ path.join(root, 'src'),
+ path.join(root, 'report.vite.config.ts'),
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/packages/style-equivalence/src/cli/uiBuild.ts b/packages/style-equivalence/src/cli/uiBuild.ts
new file mode 100644
index 00000000000..91a7004b350
--- /dev/null
+++ b/packages/style-equivalence/src/cli/uiBuild.ts
@@ -0,0 +1,18 @@
+import { readdir, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+const newestMtime = async (target: string): Promise<number> => {
+ const info = await stat(target).catch(() => undefined);
+ if (!info) return 0;
+ if (!info.isDirectory()) return info.mtimeMs;
+ const entries = await readdir(target);
+ const times = await Promise.all(entries.map((entry) => newestMtime(path.join(target, entry))));
+ return Math.max(0, ...times);
+};
+
+export const uiBuildStale = async (distDir: string, sources: string[]) => {
+ const built = await stat(path.join(distDir, 'index.html')).catch(() => undefined);
+ if (!built) return true;
+ const times = await Promise.all(sources.map(newestMtime));
+ return Math.max(0, ...times) > built.mtimeMs;
+};
diff --git a/packages/style-equivalence/src/config.ts b/packages/style-equivalence/src/config.ts
new file mode 100644
index 00000000000..c0bfd7768ae
--- /dev/null
+++ b/packages/style-equivalence/src/config.ts
@@ -0,0 +1,33 @@
+import type { PluginOption } from 'vite';
+
+import type { CalibrationAdapter } from './calibration';
+import type { RealComponent, StyleAdapter } from './extract';
+
+export type ConditionVariant = 'reduced-motion' | 'rtl';
+
+export interface ConditionConfig {
+ themeAttribute: string;
+ themes: string[];
+ variants?: ConditionVariant[];
+ widths: number[];
+}
+
+export interface ViteSetup {
+ alias?: Array<{ find: string | RegExp; replacement: string }>;
+ dedupe?: string[];
+ define?: Record<string, string>;
+ plugins: PluginOption[];
+ tsconfigPaths?: boolean;
+}
+
+export interface ProjectConfig {
+ adapters: StyleAdapter[];
+ aliases: Record<string, string>;
+ calibration?: CalibrationAdapter;
+ conditions: ConditionConfig;
+ cxFallback?: { name: string; source: string };
+ hostWrapper: string;
+ layoutComponents: string[];
+ realComponents?: Record<string, RealComponent>;
+ vite: (root: string) => Promise<ViteSetup>;
+}
diff --git a/packages/style-equivalence/src/evidence/store.test.ts b/packages/style-equivalence/src/evidence/store.test.ts
new file mode 100644
index 00000000000..2d3d7f2a5c6
--- /dev/null
+++ b/packages/style-equivalence/src/evidence/store.test.ts
@@ -0,0 +1,21 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { createRunDir } from './store';
+
+describe('createRunDir', () => {
+ it('gives runs started at the same moment their own directories', async () => {
+ const records = await mkdtemp(path.join(tmpdir(), 'style-eq-records-'));
+ try {
+ const runs = await Promise.all(
+ Array.from({ length: 4 }, () => createRunDir(records, 'a'.repeat(40), 'b'.repeat(40))),
+ );
+ expect(new Set(runs.map((run) => run.runDir)).size).toBe(4);
+ } finally {
+ await rm(records, { force: true, recursive: true });
+ }
+ });
+});
diff --git a/packages/style-equivalence/src/evidence/store.ts b/packages/style-equivalence/src/evidence/store.ts
new file mode 100644
index 00000000000..861d81da915
--- /dev/null
+++ b/packages/style-equivalence/src/evidence/store.ts
@@ -0,0 +1,23 @@
+import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+export const createRunDir = async (recordsDir: string, base: string, head: string) => {
+ const stamp = new Date().toISOString().replaceAll(/[:.]/g, '-');
+ const stem = `${stamp}-${base.slice(0, 7)}-${head.slice(0, 7)}`;
+ await mkdir(recordsDir, { recursive: true });
+ for (let attempt = 1; ; attempt++) {
+ const runId = attempt === 1 ? stem : `${stem}-${attempt}`;
+ try {
+ await mkdir(path.join(recordsDir, runId));
+ return { runDir: await realpath(path.join(recordsDir, runId)), runId };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ }
+ }
+};
+
+export const writeEvidence = (runDir: string, name: string, value: unknown) =>
+ writeFile(path.join(runDir, name), `${JSON.stringify(value, null, 2)}\n`);
+
+export const readEvidence = async <T>(runDir: string, name: string): Promise<T> =>
+ JSON.parse(await readFile(path.join(runDir, name), 'utf8')) as T;
diff --git a/packages/style-equivalence/src/extract/adapters/cssModules.ts b/packages/style-equivalence/src/extract/adapters/cssModules.ts
new file mode 100644
index 00000000000..4b1a20deff4
--- /dev/null
+++ b/packages/style-equivalence/src/extract/adapters/cssModules.ts
@@ -0,0 +1,13 @@
+import type { StyleAdapter } from '../types';
+
+export const cssModulesAdapter: StyleAdapter = {
+ importedStyleSymbols: (source, clause) =>
+ source.endsWith('.module.css') && clause.name ? [clause.name.text] : [],
+ markerIdentifiers: [],
+ name: 'cssModules',
+ recognizeFactory: () => false,
+ stylesheet: (source, clause) =>
+ source.endsWith('.module.css') && clause?.name
+ ? { kind: 'module', symbol: clause.name.text }
+ : undefined,
+};
diff --git a/packages/style-equivalence/src/extract/adapters/emotionStatic.ts b/packages/style-equivalence/src/extract/adapters/emotionStatic.ts
new file mode 100644
index 00000000000..c66363589e0
--- /dev/null
+++ b/packages/style-equivalence/src/extract/adapters/emotionStatic.ts
@@ -0,0 +1,16 @@
+import ts from 'typescript';
+
+import { templateSlotRules } from '../css';
+import { templateSlotProperties } from '../properties';
+import type { StyleAdapter } from '../types';
+
+const FACTORIES = new Set(['createStaticStyles', 'createStyles']);
+
+export const emotionStaticAdapter: StyleAdapter = {
+ markerIdentifiers: [],
+ name: 'emotionStatic',
+ propertiesOf: templateSlotProperties,
+ recognizeFactory: (call) =>
+ ts.isIdentifier(call.expression) && FACTORIES.has(call.expression.text),
+ rulesOf: templateSlotRules,
+};
diff --git a/packages/style-equivalence/src/extract/adapters/globalCss.ts b/packages/style-equivalence/src/extract/adapters/globalCss.ts
new file mode 100644
index 00000000000..2b3b4da372d
--- /dev/null
+++ b/packages/style-equivalence/src/extract/adapters/globalCss.ts
@@ -0,0 +1,11 @@
+import type { StyleAdapter } from '../types';
+
+export const globalCssAdapter: StyleAdapter = {
+ markerIdentifiers: [],
+ name: 'globalCss',
+ recognizeFactory: () => false,
+ stylesheet: (source, clause) =>
+ source.endsWith('.css') && !source.endsWith('.module.css') && !clause
+ ? { kind: 'global' }
+ : undefined,
+};
diff --git a/packages/style-equivalence/src/extract/adapters/stylex.ts b/packages/style-equivalence/src/extract/adapters/stylex.ts
new file mode 100644
index 00000000000..4ce8dc51146
--- /dev/null
+++ b/packages/style-equivalence/src/extract/adapters/stylex.ts
@@ -0,0 +1,32 @@
+import ts from 'typescript';
+
+import { objectSlotConditions, objectSlotProperties } from '../properties';
+import type { StyleAdapter } from '../types';
+
+const FACTORIES = new Set([
+ 'create',
+ 'createTheme',
+ 'defineConsts',
+ 'defineMarker',
+ 'defineVars',
+ 'keyframes',
+ 'positionTry',
+ 'viewTransitionClass',
+]);
+
+const isCreate = (factory: ts.CallExpression) =>
+ ts.isPropertyAccessExpression(factory.expression) && factory.expression.name.text === 'create';
+
+export const stylexAdapter: StyleAdapter = {
+ conditionsOf: (symbol, factory) =>
+ isCreate(factory) ? objectSlotConditions(symbol, factory) : {},
+ markerIdentifiers: ['stylex'],
+ name: 'stylex',
+ propertiesOf: (symbol, factory) =>
+ isCreate(factory) ? objectSlotProperties(symbol, factory) : {},
+ recognizeFactory: (call) =>
+ ts.isPropertyAccessExpression(call.expression) &&
+ ts.isIdentifier(call.expression.expression) &&
+ call.expression.expression.text === 'stylex' &&
+ FACTORIES.has(call.expression.name.text),
+};
diff --git a/packages/style-equivalence/src/extract/aliases.test.ts b/packages/style-equivalence/src/extract/aliases.test.ts
new file mode 100644
index 00000000000..6cc11b985ec
--- /dev/null
+++ b/packages/style-equivalence/src/extract/aliases.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+
+import { generateModule } from '../generate/module';
+import { planFile } from '../plan/planFile';
+import { emotionStaticAdapter } from './adapters/emotionStatic';
+import { extractFile } from './index';
+
+const STYLES = `import { createStaticStyles } from '@lobehub/ui';
+
+export const useStyles = createStaticStyles(({ css }) => ({
+ container: css\`height: 32px;\`,
+}));
+`;
+
+const COMPONENT = `import { useStyles } from './styles';
+
+export const TabBar = () => {
+ const styles = useStyles;
+ return <div className={styles.container} />;
+};
+`;
+
+const options = {
+ adapters: [emotionStaticAdapter],
+ layoutComponents: [],
+ readModule: (_from: string, specifier: string) => (specifier === './styles' ? STYLES : undefined),
+};
+
+describe('a component that renames an imported style object locally', () => {
+ it('reads the slots through the local name and renders with the real object', () => {
+ const extraction = extractFile(COMPONENT, 'a.tsx', options);
+ const [element] = extraction.elements;
+ expect(element.slots).toEqual(['useStyles.container']);
+ expect(element.variables).toEqual([]);
+ expect(element.aliases).toEqual({ styles: 'useStyles' });
+ expect(extraction.outsideReferences).toEqual([]);
+ const plan = planFile('a.tsx', extraction, extraction, { layoutComponents: [] });
+ expect(plan.cases[0].flags).toEqual([]);
+ const module = generateModule(extraction, plan, 'base', { layoutComponents: [] });
+ expect(module).toContain('const styles = useStyles;');
+ expect(module).toContain("import { useStyles } from './styles';");
+ });
+
+ it('resolves the same local name to the object each component binds', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+
+const a = createStaticStyles(({ css }) => ({ x: css\`color: red;\` }));
+const b = createStaticStyles(({ css }) => ({ x: css\`color: blue;\` }));
+
+export const A = () => {
+ const styles = a;
+ return <div className={styles.x} />;
+};
+
+export const B = () => {
+ const styles = b;
+ return <div className={styles.x} />;
+};
+`;
+ const extraction = extractFile(code, 'a.tsx', options);
+ expect(extraction.elements.map((element) => element.slots)).toEqual([['a.x'], ['b.x']]);
+ });
+});
diff --git a/packages/style-equivalence/src/extract/aliases.ts b/packages/style-equivalence/src/extract/aliases.ts
new file mode 100644
index 00000000000..214adab9245
--- /dev/null
+++ b/packages/style-equivalence/src/extract/aliases.ts
@@ -0,0 +1,25 @@
+import ts from 'typescript';
+
+export const aliasDeclaration = (declaration: ts.VariableDeclaration, symbols: Set<string>) =>
+ ts.isIdentifier(declaration.name) &&
+ declaration.initializer &&
+ ts.isIdentifier(declaration.initializer) &&
+ symbols.has(declaration.initializer.text) &&
+ !symbols.has(declaration.name.text) &&
+ ts.isVariableDeclarationList(declaration.parent) &&
+ declaration.parent.flags & ts.NodeFlags.Const
+ ? declaration.initializer.text
+ : undefined;
+
+export const aliasOf = (node: ts.Identifier, symbols: Set<string>) => {
+ 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))
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === node.text)
+ return aliasDeclaration(declaration, symbols);
+ if (ts.isSourceFile(scope)) return undefined;
+ }
+ return undefined;
+};
diff --git a/packages/style-equivalence/src/extract/attributes.ts b/packages/style-equivalence/src/extract/attributes.ts
new file mode 100644
index 00000000000..5732bf0cf86
--- /dev/null
+++ b/packages/style-equivalence/src/extract/attributes.ts
@@ -0,0 +1,12 @@
+const escape = (text: string) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+
+export const isStateAttribute = (name: string) => /^(?:aria|data)-[\w-]+$/.test(name);
+
+export const booleanAttribute = (code: string, name: string) => {
+ const selector = new RegExp(`\\[${escape(name)}(?:\\s*=\\s*(['"]?)([^'"\\]]*)\\1)?\\s*\\]`, 'g');
+ const values = [...code.matchAll(selector)].map((match) => match[2]);
+ return (
+ values.length > 0 &&
+ values.every((value) => value === undefined || value === 'true' || value === 'false')
+ );
+};
diff --git a/packages/style-equivalence/src/extract/children.ts b/packages/style-equivalence/src/extract/children.ts
new file mode 100644
index 00000000000..1107f2a1465
--- /dev/null
+++ b/packages/style-equivalence/src/extract/children.ts
@@ -0,0 +1,139 @@
+import ts from 'typescript';
+
+import type { LiteralValue, StyleElement } from './types';
+
+type JsxNode = ts.JsxElement | ts.JsxSelfClosingElement;
+
+export const PLAIN_ATTRIBUTES_UNMODELED = 'PLAIN_ATTRIBUTES_UNMODELED';
+
+const STYLE_PROPS = new Set(['class', 'className', 'style']);
+
+const objectLiteralOf = (expression: ts.ObjectLiteralExpression) => {
+ const value: Record<string, LiteralValue> = {};
+ for (const property of expression.properties) {
+ if (!ts.isPropertyAssignment(property)) return undefined;
+ const { name } = property;
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) return undefined;
+ const inner = literalOf(property.initializer);
+ if (inner === undefined) return undefined;
+ value[name.text] = inner;
+ }
+ return value;
+};
+
+export const literalOf = (expression: ts.Expression): LiteralValue | undefined => {
+ if (ts.isParenthesizedExpression(expression)) return literalOf(expression.expression);
+ if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression))
+ return expression.text;
+ if (ts.isNumericLiteral(expression)) return Number(expression.text);
+ if (
+ ts.isPrefixUnaryExpression(expression) &&
+ expression.operator === ts.SyntaxKind.MinusToken &&
+ ts.isNumericLiteral(expression.operand)
+ )
+ return -Number(expression.operand.text);
+ if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
+ if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
+ if (ts.isObjectLiteralExpression(expression)) return objectLiteralOf(expression);
+ return undefined;
+};
+
+const isElement = (node: ts.Node): node is JsxNode =>
+ ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node);
+
+const openingOf = (node: JsxNode) => (ts.isJsxElement(node) ? node.openingElement : node);
+
+const isIntrinsic = (tag: string) => /^[a-z][\w-]*$/.test(tag);
+
+const directChildren = (node: JsxNode) => {
+ const found: JsxNode[] = [];
+ const visit = (current: ts.Node) => {
+ if (isElement(current)) found.push(current);
+ else ts.forEachChild(current, visit);
+ };
+ if (ts.isJsxElement(node)) node.children.forEach(visit);
+ return found;
+};
+
+const subtreeTags = (node: JsxNode, ast: ts.SourceFile) => {
+ const counts: Record<string, number> = {};
+ const components = new Set<string>();
+ const visit = (current: ts.Node) => {
+ if (isElement(current)) {
+ const tag = openingOf(current).tagName.getText(ast);
+ if (isIntrinsic(tag)) counts[tag] = (counts[tag] ?? 0) + 1;
+ else components.add(tag);
+ }
+ ts.forEachChild(current, visit);
+ };
+ if (ts.isJsxElement(node)) node.children.forEach(visit);
+ return { components: [...components].sort(), counts };
+};
+
+const plainAttributes = (opening: ts.JsxOpeningLikeElement, ast: ts.SourceFile) => {
+ const literalProps: Record<string, LiteralValue> = {};
+ let opaque = false;
+ for (const attribute of opening.attributes.properties) {
+ if (ts.isJsxSpreadAttribute(attribute)) {
+ opaque = true;
+ continue;
+ }
+ const name = attribute.name.getText(ast);
+ const { initializer } = attribute;
+ if (!initializer) {
+ literalProps[name] = true;
+ continue;
+ }
+ if (ts.isStringLiteral(initializer)) {
+ literalProps[name] = initializer.text;
+ continue;
+ }
+ const literal =
+ ts.isJsxExpression(initializer) && initializer.expression
+ ? literalOf(initializer.expression)
+ : undefined;
+ if (literal !== undefined) literalProps[name] = literal;
+ else if (STYLE_PROPS.has(name)) opaque = true;
+ }
+ return { literalProps, opaque };
+};
+
+export const collectChildren = (
+ styled: Map<ts.Node, StyleElement>,
+ ast: ts.SourceFile,
+ classifyTag: (tag: string) => boolean,
+) => {
+ const plain: StyleElement[] = [];
+ for (const [node, element] of styled) {
+ const jsx = node as JsxNode;
+ const children = directChildren(jsx).map((child, index) => {
+ const known = styled.get(child);
+ if (known) return known.id;
+ const opening = openingOf(child);
+ const tag = opening.tagName.getText(ast);
+ const { literalProps, opaque } = plainAttributes(opening, ast);
+ const id = `${element.id}/${index}`;
+ const real = classifyTag(tag);
+ const { counts: tags } = subtreeTags(child, ast);
+ plain.push({
+ bindings: [],
+ flags: opaque ? [PLAIN_ATTRIBUTES_UNMODELED] : [],
+ id,
+ literalProps,
+ owner: element.owner,
+ parent: element.id,
+ ...(real ? { real } : {}),
+ slots: [],
+ ...(Object.keys(tags).length ? { subtreeTags: tags } : {}),
+ tag,
+ variables: [],
+ });
+ return id;
+ });
+ if (children.length) element.children = children;
+ const { components, counts } = subtreeTags(jsx, ast);
+ if (Object.keys(counts).length) element.subtreeTags = counts;
+ if (components.length) element.subtreeComponents = components;
+ }
+ return plain;
+};
diff --git a/packages/style-equivalence/src/extract/constraints.ts b/packages/style-equivalence/src/extract/constraints.ts
new file mode 100644
index 00000000000..edf1e449fd7
--- /dev/null
+++ b/packages/style-equivalence/src/extract/constraints.ts
@@ -0,0 +1,80 @@
+import ts from 'typescript';
+
+const LOGICAL = new Set([
+ ts.SyntaxKind.AmpersandAmpersandToken,
+ ts.SyntaxKind.BarBarToken,
+ ts.SyntaxKind.QuestionQuestionToken,
+ ts.SyntaxKind.EqualsEqualsEqualsToken,
+ ts.SyntaxKind.ExclamationEqualsEqualsToken,
+ ts.SyntaxKind.EqualsEqualsToken,
+ ts.SyntaxKind.ExclamationEqualsToken,
+]);
+
+export const isCondition = (node: ts.Expression): boolean => {
+ if (ts.isIdentifier(node)) return true;
+ if (
+ node.kind === ts.SyntaxKind.TrueKeyword ||
+ node.kind === ts.SyntaxKind.FalseKeyword ||
+ node.kind === ts.SyntaxKind.NullKeyword
+ )
+ return true;
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
+ return isCondition(node.expression);
+ if (ts.isPrefixUnaryExpression(node))
+ return node.operator === ts.SyntaxKind.ExclamationToken && isCondition(node.operand);
+ if (ts.isBinaryExpression(node))
+ return (
+ LOGICAL.has(node.operatorToken.kind) && isCondition(node.left) && isCondition(node.right)
+ );
+ if (ts.isCallExpression(node))
+ return (
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === 'Boolean' &&
+ node.arguments.length === 1 &&
+ isCondition(node.arguments[0])
+ );
+ return false;
+};
+
+export const localCondition = (node: ts.Identifier) => {
+ for (let scope: ts.Node = node.parent; !ts.isSourceFile(scope); scope = scope.parent) {
+ if (ts.isFunctionLike(scope)) return undefined;
+ if (!ts.isBlock(scope)) continue;
+ for (const statement of scope.statements) {
+ if (!ts.isVariableStatement(statement)) continue;
+ for (const declaration of statement.declarationList.declarations) {
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== node.text) continue;
+ const value = declaration.initializer;
+ return statement.declarationList.flags & ts.NodeFlags.Const && value && isCondition(value)
+ ? value.getText()
+ : undefined;
+ }
+ }
+ }
+ return undefined;
+};
+
+export const renderGuards = (element: ts.Node) => {
+ const guards: string[] = [];
+ let child = element;
+ for (let parent = element.parent; parent && !ts.isSourceFile(parent); parent = parent.parent) {
+ if (ts.isFunctionLike(parent)) break;
+ if (
+ ts.isBinaryExpression(parent) &&
+ parent.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken &&
+ parent.right === child &&
+ isCondition(parent.left)
+ )
+ guards.push(parent.left.getText());
+ if (
+ ts.isConditionalExpression(parent) &&
+ parent.condition !== child &&
+ isCondition(parent.condition)
+ )
+ guards.push(
+ parent.whenTrue === child ? parent.condition.getText() : `!(${parent.condition.getText()})`,
+ );
+ child = parent;
+ }
+ return guards;
+};
diff --git a/packages/style-equivalence/src/extract/css.ts b/packages/style-equivalence/src/extract/css.ts
new file mode 100644
index 00000000000..1b3a5c4bb7f
--- /dev/null
+++ b/packages/style-equivalence/src/extract/css.ts
@@ -0,0 +1,152 @@
+import postcss, { type AtRule, type Container, type Declaration, type Rule } from 'postcss';
+import ts from 'typescript';
+
+import type { StyleRule } from './types';
+
+export const SELF = '__self__';
+const PLACEHOLDER = /^__I\d+__$/;
+
+const conditionsOf = (node: Rule) => {
+ const conditions: string[] = [];
+ for (let parent: Container | undefined = node; parent; parent = parent.parent as Container) {
+ if (parent.type === 'atrule')
+ conditions.unshift(`@${(parent as AtRule).name} ${(parent as AtRule).params}`);
+ if (parent.type === 'rule' && PLACEHOLDER.test((parent as Rule).selector.trim()))
+ conditions.unshift((parent as Rule).selector.trim());
+ if (parent.type === 'root') break;
+ }
+ return conditions;
+};
+
+const fullSelector = (rule: Rule, rootSelector: string | undefined): string | undefined => {
+ const parent = rule.parent;
+ const parentSelector =
+ parent && parent.type === 'rule' ? fullSelector(parent as Rule, rootSelector) : rootSelector;
+ if (PLACEHOLDER.test(rule.selector.trim())) return parentSelector;
+ if (parentSelector === undefined) return rule.selector;
+ return rule.selector
+ .split(',')
+ .map((part) =>
+ part.includes('&')
+ ? part.replaceAll('&', parentSelector)
+ : `${parentSelector} ${part.trim()}`,
+ )
+ .join(', ');
+};
+
+const declarationsOf = (rule: Rule) =>
+ (rule.nodes ?? [])
+ .filter((node): node is Declaration => node.type === 'decl')
+ .map(
+ (node) =>
+ `${node.prop.toLowerCase()}: ${node.value.replaceAll(/\s+/g, ' ').trim()}${node.important ? ' !important' : ''}`,
+ );
+
+export const parseRules = (css: string, rootSelector?: string) => {
+ const rules: Array<{ conditions: string[]; declarations: string[]; selector: string }> = [];
+ let root;
+ try {
+ root = postcss.parse(css);
+ } catch {
+ return { error: true, rules };
+ }
+ root.walkRules((rule) => {
+ const selector = fullSelector(rule, rootSelector);
+ if (selector && selector !== rootSelector)
+ rules.push({ conditions: conditionsOf(rule), declarations: declarationsOf(rule), selector });
+ });
+ return { error: false, rules };
+};
+
+export const templateText = (template: ts.TemplateLiteral) => {
+ if (ts.isNoSubstitutionTemplateLiteral(template)) return template.text;
+ let text = template.head.text;
+ template.templateSpans.forEach((span, index) => {
+ text += `__I${index}__${span.literal.text}`;
+ });
+ return text;
+};
+
+export const returnedObject = (factory: ts.CallExpression) => {
+ const callback = factory.arguments[0];
+ if (!callback) return undefined;
+ if (ts.isObjectLiteralExpression(callback)) return callback;
+ if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) return undefined;
+ let body: ts.Node | undefined = callback.body;
+ if (ts.isBlock(body)) body = body.statements.find(ts.isReturnStatement)?.expression;
+ while (body && ts.isParenthesizedExpression(body)) body = body.expression;
+ return body && ts.isObjectLiteralExpression(body) ? body : undefined;
+};
+
+const topLevelConstants = (sf: ts.SourceFile) => {
+ const constants = new Map<string, ts.Expression>();
+ for (const statement of sf.statements)
+ if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const)
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.initializer)
+ constants.set(declaration.name.text, declaration.initializer);
+ return constants;
+};
+
+const constantText = (
+ node: ts.Expression,
+ constants: Map<string, ts.Expression>,
+ depth = 0,
+): string | undefined => {
+ if (depth > 4) return undefined;
+ if (ts.isParenthesizedExpression(node)) return constantText(node.expression, constants, depth);
+ if (ts.isStringLiteralLike(node)) return node.text;
+ if (ts.isNumericLiteral(node)) return String(Number(node.getText().replaceAll('_', '')));
+ if (!ts.isIdentifier(node)) return undefined;
+ const target = constants.get(node.text);
+ return target && constantText(target, constants, depth + 1);
+};
+
+export const importAliases = (sf: ts.SourceFile, imported: string) => {
+ const aliases = new Map<string, string>();
+ for (const statement of sf.statements) {
+ const named = ts.isImportDeclaration(statement)
+ ? statement.importClause?.namedBindings
+ : undefined;
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements)
+ if ((element.propertyName ?? element.name).text === imported)
+ aliases.set(element.name.text, imported);
+ }
+ return aliases;
+};
+
+export const templateSlotRules = (symbol: string, factory: ts.CallExpression): StyleRule[] => {
+ const object = returnedObject(factory);
+ if (!object) return [];
+ const constants = topLevelConstants(factory.getSourceFile());
+ const tokenAliases = importAliases(factory.getSourceFile(), 'cssVar');
+ const rules: StyleRule[] = [];
+ for (const property of object.properties) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ const value = property.initializer;
+ if (!ts.isTaggedTemplateExpression(value)) continue;
+ const slot = `${symbol}.${property.name.getText()}`;
+ const spans = ts.isTemplateExpression(value.template) ? value.template.templateSpans : [];
+ const interpolations = spans.map((span) => {
+ const { expression } = span;
+ const alias =
+ ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)
+ ? tokenAliases.get(expression.expression.text)
+ : undefined;
+ if (alias && ts.isPropertyAccessExpression(expression))
+ return `${alias}.${expression.name.text}`;
+ return expression.getText().replaceAll(/\s+/g, ' ').trim();
+ });
+ const folded = spans.map((span) => constantText(span.expression, constants) ?? null);
+ for (const rule of parseRules(templateText(value.template), `.${SELF}`).rules)
+ rules.push({
+ ...rule,
+ ...(interpolations.length ? { interpolations } : {}),
+ ...(folded.some((item) => item !== null) ? { interpolationValues: folded } : {}),
+ owned: { [SELF]: slot },
+ slot,
+ });
+ }
+ return rules;
+};
diff --git a/packages/style-equivalence/src/extract/extract.test.ts b/packages/style-equivalence/src/extract/extract.test.ts
new file mode 100644
index 00000000000..ab72ebe60ac
--- /dev/null
+++ b/packages/style-equivalence/src/extract/extract.test.ts
@@ -0,0 +1,296 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from './adapters/emotionStatic';
+import { stylexAdapter } from './adapters/stylex';
+import { extractFile } from './index';
+
+const options = {
+ adapters: [emotionStaticAdapter, stylexAdapter],
+ layoutComponents: ['Flexbox'],
+};
+
+const base = `import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';
+import { Spin } from '@lobehub/ui';
+import { useStore } from '@/store/home';
+
+const indicator = <Spin size={9} />;
+
+const styles = createStaticStyles(({ css }) => ({
+ item: css\`height: 40px;\`,
+ itemDragging: css\`opacity: 0;\`,
+}));
+
+export const SortableItem = memo(({ isDragging }) => {
+ const store = useStore();
+ return (
+ <Flexbox horizontal gap={8} className={isDragging ? cx(styles.item, styles.itemDragging) : styles.item}>
+ {store.name}
+ </Flexbox>
+ );
+});
+`;
+
+const head = `import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ item: { height: '40px' },
+ itemDragging: { opacity: 0 },
+});
+
+export const SortableItem = memo(({ isDragging }) => (
+ <Flexbox horizontal gap={8} className={isDragging ? stylex.props(styles.item, styles.itemDragging).className : stylex.props(styles.item).className}>
+ x
+ </Flexbox>
+));
+`;
+
+describe('extractFile', () => {
+ it('finds the same element and condition variable on both sides of a cx → stylex.props migration', () => {
+ const before = extractFile(base, 'a.tsx', options);
+ const after = extractFile(head, 'a.tsx', options);
+ expect(before.styleSymbols).toEqual(['styles']);
+ expect(after.styleSymbols).toEqual(['styles']);
+ for (const result of [before, after]) {
+ expect(result.elements).toHaveLength(1);
+ expect(result.elements[0]).toMatchObject({
+ id: 'SortableItem#0',
+ literalProps: { gap: 8, horizontal: true },
+ owner: 'SortableItem',
+ slots: ['styles.item', 'styles.itemDragging'],
+ tag: 'Flexbox',
+ variables: [{ kind: 'boolean', name: 'isDragging' }],
+ });
+ }
+ });
+
+ 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';");
+ expect(prelude).toContain('const styles = createStaticStyles(');
+ expect(prelude).not.toContain('useStore');
+ expect(prelude).not.toContain('indicator');
+ });
+
+ it('imports the stylex namespace when the styles come from another module', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+import { styles } from './a.styles';
+export const A = () => <span {...stylex.props(styles.a)} />;
+`;
+ expect(extractFile(code, 'a.tsx', options).prelude).toContain(
+ "import * as stylex from '@stylexjs/stylex';",
+ );
+ });
+
+ it('treats styles imported from a sibling style module as style symbols', () => {
+ const modules: Record<string, string> = {
+ './style': `import { createStaticStyles } from '@lobehub/ui';
+export const styles = createStaticStyles(({ css }) => ({ box: css\`padding: 4px; .foreign { color: red; }\` }));
+`,
+ './A.styles': `import * as stylex from '@stylexjs/stylex';
+export const atomic = stylex.create({ box: { padding: 4 } });
+`,
+ };
+ const code = `import * as stylex from '@stylexjs/stylex';
+import { atomic } from './A.styles';
+import { styles } from './style';
+export const A = () => <div className={styles.box}><span {...stylex.props(atomic.box)} /></div>;
+`;
+ const result = extractFile(code, 'src/A.tsx', {
+ ...options,
+ readModule: (_from, specifier) => modules[specifier],
+ });
+ expect(result.elements.map((element) => [element.id, element.slots])).toEqual([
+ ['A#0', ['styles.box']],
+ ['A#1', ['atomic.box']],
+ ]);
+ expect(result.prelude).toContain("import { styles } from './style';");
+ expect(result.elements[0].flags).toEqual(['CROSS_COMPONENT']);
+ });
+
+ it('imports JSX tags used by a kept top-level statement', () => {
+ const code = `import { Spin } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+const spinner = <Spin size={9} />;
+const styles = stylex.create({ a: { color: 'red' } });
+const tokens = { spinner };
+export const A = () => <span {...stylex.props(styles.a)} data-x={tokens} />;
+`;
+ const { prelude } = extractFile(code, 'a.tsx', options);
+ expect(prelude).not.toContain('Spin');
+ const kept = extractFile(
+ code.replace("{ a: { color: 'red' } }", "{ a: { color: 'red', content: String(spinner) } }"),
+ 'a.tsx',
+ options,
+ ).prelude;
+ expect(kept).toContain("import { Spin } from '@lobehub/ui';");
+ expect(kept).toContain('const spinner = <Spin size={9} />;');
+ });
+
+ it('binds JSX passed as a prop value to its own element, parented to the outer parent', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({ row: { display: 'flex' }, wrapper: { position: 'relative' } });
+export const Row = ({ isLoading, avatarNode }) => (
+ <div {...stylex.props(styles.row)}>
+ <Item avatar={isLoading ? <span {...stylex.props(styles.wrapper)}>{avatarNode}</span> : avatarNode} />
+ </div>
+);
+`;
+ const { elements } = extractFile(code, 'a.tsx', options);
+ expect(elements.map((element) => [element.id, element.tag, element.parent])).toEqual([
+ ['Row#0', 'div', undefined],
+ ['Row#1', 'span', 'Row#0'],
+ ]);
+ });
+
+ it('classifies how each free variable is used', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({ a: { color: 'red' }, b: { color: 'blue' }, c: { color: 'green' } });
+export const A = ({ isActive, item, visible, className }) => (
+ <div {...stylex.props(styles.a, isActive() && styles.b, item.done && styles.c, !visible && styles.b)} className={className} />
+);
+`;
+ const [element] = extractFile(code, 'a.tsx', options).elements;
+ expect(element.variables).toEqual([
+ { kind: 'call', name: 'isActive' },
+ { kind: 'member', name: 'item' },
+ { kind: 'boolean', name: 'visible' },
+ ]);
+ });
+
+ it('reports style references outside JSX but not object keys or attribute names', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({ a: css\`color: red;\` }));
+const columns = [{ className: styles.a }];
+export const open = () => createModal({ styles: { content: {} } });
+export const A = () => <Modal styles={{ body: {} }} className={styles.a} />;
+`;
+ expect(extractFile(code, 'a.tsx', options).outsideReferences).toEqual(['styles@3']);
+ });
+});
+
+describe('extractFile selector ownership', () => {
+ const source = (child: string) => `import { createStaticStyles, cx } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ header: css\`
+ &:hover .${child} { color: red; }
+ \`,
+ label: css\`font-size: 12px;\`,
+}));
+
+export const Header = ({ title }) => (
+ <button className={styles.header}>
+ <span className={cx(styles.label, 'header-label')}>{title}</span>
+ </button>
+);
+`;
+
+ it('treats a class the same file puts on its own element as local, not cross-component', () => {
+ const result = extractFile(source('header-label'), 'a.tsx', options);
+ expect(result.elements.flatMap((element) => element.flags)).toEqual([]);
+ });
+
+ it('flags a descendant class the file never renders as cross-component', () => {
+ const result = extractFile(source('ant-btn'), 'a.tsx', options);
+ expect(result.elements.find((element) => element.id === 'Header#0')?.flags).toEqual([
+ 'CROSS_COMPONENT',
+ ]);
+ });
+});
+
+describe('extractFile variable modeling', () => {
+ const kindsOf = (body: string, imports = '') => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+${imports}
+const styles = stylex.create({ a: { color: 'red' }, b: { color: 'blue' }, c: { color: 'green' } });
+${body}
+`;
+ const result = extractFile(code, 'a.tsx', options);
+ return { prelude: result.prelude, variables: result.elements[0].variables };
+ };
+
+ it('models a parameter that shadows an import instead of pulling the import in', () => {
+ const { prelude, variables } = kindsOf(
+ 'export const A = ({ active }) => <div {...stylex.props(styles.a, active && styles.b)} />;',
+ "import { active } from '@/store/chat/selectors';",
+ );
+ expect(variables).toEqual([{ kind: 'boolean', name: 'active' }]);
+ expect(prelude).not.toContain('@/store/chat/selectors');
+ });
+
+ it('does not model a member compared with a literal', () => {
+ const { variables } = kindsOf(
+ "export const A = ({ state }) => <div {...stylex.props(styles.a, state.kind === 'off' && styles.b)} />;",
+ );
+ expect(variables).toEqual([{ kind: 'unknown', name: 'state' }]);
+ });
+
+ it('does not model a value used both as a boolean and as an object', () => {
+ const { variables } = kindsOf(
+ 'export const A = ({ item }) => <div {...stylex.props(styles.a, item && styles.b, item.done && styles.c)} />;',
+ );
+ expect(variables).toEqual([{ kind: 'unknown', name: 'item' }]);
+ });
+});
+
+describe('extractFile slot properties', () => {
+ it('records the properties each Emotion slot sets, including nested rules and conditions', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ activated: css\`
+ color: \${cssVar.colorSuccess};
+ background: \${cssVar.colorSuccessBg};
+ \`,
+ listItem: css\`
+ padding-block: 10px;
+ &:not(:last-child) { border-block-end: 1px solid red; }
+ @media (max-width: 600px) { font-size: 12px; }
+ \`,
+}));
+export const A = () => <span className={styles.activated} />;
+`;
+ expect(extractFile(code, 'a.tsx', options).slotProperties).toEqual({
+ 'styles.activated': ['background', 'color'],
+ 'styles.listItem': ['border-block-end', 'font-size', 'padding-block'],
+ });
+ });
+
+ it('leaves out an Emotion slot whose declarations it cannot read', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({
+ mixed: css\`
+ \${mixin}
+ color: red;
+ \`,
+ computed: css\`
+ \${side}: 0;
+ \`,
+ plain: css\`color: red;\`,
+}));
+export const A = () => <span className={styles.plain} />;
+`;
+ expect(extractFile(code, 'a.tsx', options).slotProperties).toEqual({
+ 'styles.plain': ['color'],
+ });
+ });
+
+ it('records the properties each StyleX slot sets as kebab-case names', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({
+ activated: { color: 'green', backgroundColor: 'white', backgroundImage: 'none' },
+ dot: { borderWidth: { default: null, ':hover': '1px' }, '::placeholder': { color: 'gray' } },
+ dynamic: (size) => ({ width: size, WebkitLineClamp: 2 }),
+ spread: { ...base, color: 'red' },
+ vars: { '--accent': 'red' },
+});
+export const A = () => <span {...stylex.props(styles.activated)} />;
+`;
+ expect(extractFile(code, 'a.tsx', options).slotProperties).toEqual({
+ 'styles.activated': ['background-color', 'background-image', 'color'],
+ 'styles.dot': ['border-width', 'color'],
+ 'styles.dynamic': ['-webkit-line-clamp', 'width'],
+ 'styles.vars': ['--accent'],
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/extract/forward.test.ts b/packages/style-equivalence/src/extract/forward.test.ts
new file mode 100644
index 00000000000..aeb4f6a8795
--- /dev/null
+++ b/packages/style-equivalence/src/extract/forward.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+
+import { elementAtPath, resolveForward } from './forward';
+
+const component = (title: string, extra = '') => `
+import { Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const AcceptanceIdentity = ({ focusSlot, titleXstyle }) => {
+ const { data } = useBundle();
+ if (!data) return null;
+ return (
+ <Flexbox gap={10}>
+ <Flexbox horizontal className={styles.titleRow}>
+ ${title}
+ {focusSlot && <div data-role={'focus-entry'}>{focusSlot}</div>}
+ </Flexbox>
+ ${extra}
+ </Flexbox>
+ );
+};
+
+export default AcceptanceIdentity;
+`;
+
+const title = (props = 'className={stylex.props(titleXstyle).className}') =>
+ `<Text ellipsis as={'h1'} ${props} style={{ fontSize: 18, margin: 0 }} title={data.title} onClick={open}>
+ {data.title}
+ </Text>`;
+
+describe('a style prop forwarded into our own component', () => {
+ it('finds the single element the prop is applied to, with its static attributes', () => {
+ expect(resolveForward(component(title()), 'default', 'titleXstyle')).toEqual({
+ prop: 'titleXstyle',
+ target: {
+ application: 'props',
+ attributes: { as: 'h1', ellipsis: true, style: { fontSize: 18, margin: 0 } },
+ path: [0, 0],
+ tag: 'Text',
+ tagImport: { imported: 'Text', source: '@lobehub/ui' },
+ },
+ });
+ });
+
+ it('reads a className prop applied as is and a spread of stylex.props', () => {
+ const memo = `import { memo } from 'react';
+import * as stylex from '@stylexjs/stylex';
+export const Row = memo(({ className, xstyle }) => (
+ <div>
+ <span className={className} />
+ <p {...stylex.props(xstyle)} />
+ </div>
+));
+`;
+ expect(resolveForward(memo, 'Row', 'className').target).toMatchObject({
+ application: 'className',
+ path: [0],
+ tag: 'span',
+ });
+ expect(resolveForward(memo, 'Row', 'xstyle').target).toMatchObject({
+ application: 'spread',
+ path: [1],
+ tag: 'p',
+ });
+ });
+
+ it('refuses a prop applied twice', () => {
+ const code = component(title(), '<h2 className={stylex.props(titleXstyle).className} />');
+ expect(resolveForward(code, 'default', 'titleXstyle').reason).toBe('FORWARD_APPLIED_2_TIMES');
+ });
+
+ it('refuses a prop applied under a condition', () => {
+ const code = component(`{data.title && ${title()}}`);
+ expect(resolveForward(code, 'default', 'titleXstyle').reason).toBe('FORWARD_CONDITIONAL');
+ });
+
+ it('refuses a prop merged with other styles', () => {
+ const code = component(title('className={cx(styles.title, titleXstyle)}'));
+ expect(resolveForward(code, 'default', 'titleXstyle').reason).toBe(
+ 'FORWARD_APPLICATION_UNSUPPORTED',
+ );
+ });
+
+ it('refuses a target whose own style is not static', () => {
+ const code = component(
+ title().replace('style={{ fontSize: 18, margin: 0 }}', 'style={titleStyle}'),
+ );
+ expect(resolveForward(code, 'default', 'titleXstyle').reason).toBe(
+ 'FORWARD_ATTRIBUTES_UNMODELED:style',
+ );
+ });
+
+ it('refuses a prop the component does not destructure', () => {
+ const code = `export const A = (props) => <h1 className={props.className} />;`;
+ expect(resolveForward(code, 'A', 'className').reason).toBe('FORWARD_PROP_NOT_DESTRUCTURED');
+ });
+
+ it('reads the element at the same place in another version of the component', () => {
+ const before = component(title('').replace(' ellipsis', ' ellipsis'));
+ expect(elementAtPath(before, 'default', [0, 0])).toEqual({
+ attributes: { as: 'h1', ellipsis: true, style: { fontSize: 18, margin: 0 } },
+ path: [0, 0],
+ tag: 'Text',
+ tagImport: { imported: 'Text', source: '@lobehub/ui' },
+ });
+ expect(elementAtPath(before, 'default', [0, 3])).toEqual({ reason: 'FORWARD_BASE_MISSING' });
+ });
+});
diff --git a/packages/style-equivalence/src/extract/forward.ts b/packages/style-equivalence/src/extract/forward.ts
new file mode 100644
index 00000000000..1997f5b269e
--- /dev/null
+++ b/packages/style-equivalence/src/extract/forward.ts
@@ -0,0 +1,338 @@
+import ts from 'typescript';
+
+import { literalOf } from './children';
+import type { LiteralValue } from './types';
+
+export type ForwardApplication = 'className' | 'props' | 'spread';
+
+export interface ForwardElement {
+ attributes: Record<string, LiteralValue>;
+ path: number[];
+ tag: string;
+ tagImport?: { imported: string; source: string };
+}
+
+export interface ForwardTarget extends ForwardElement {
+ application: ForwardApplication;
+ base?: ForwardElement;
+ baseReason?: string;
+}
+
+export interface ForwardResolution {
+ prop: string;
+ reason?: string;
+ target?: ForwardTarget;
+}
+
+type ComponentFunction = ts.ArrowFunction | ts.FunctionDeclaration | ts.FunctionExpression;
+type JsxNode = ts.JsxElement | ts.JsxSelfClosingElement;
+
+const WRAPPERS = new Set(['forwardRef', 'memo']);
+const STYLE_ATTRIBUTES = new Set(['class', 'className', 'style']);
+const STYLEX = '@stylexjs/stylex';
+
+const parse = (code: string) =>
+ ts.createSourceFile('component.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+
+const unwrap = (node: ts.Node): ts.Node =>
+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;
+
+const isExported = (node: ts.Node) =>
+ ts.canHaveModifiers(node) &&
+ !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
+
+const declarationOf = (sf: ts.SourceFile, name: string): ts.Node | undefined => {
+ for (const statement of sf.statements) {
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) return statement;
+ if (!ts.isVariableStatement(statement)) continue;
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === name)
+ return declaration.initializer;
+ }
+ return undefined;
+};
+
+const functionOf = (
+ sf: ts.SourceFile,
+ node: ts.Node | undefined,
+ depth = 0,
+): ComponentFunction | undefined => {
+ if (!node || depth > 4) return undefined;
+ const inner = unwrap(node);
+ if (
+ ts.isArrowFunction(inner) ||
+ ts.isFunctionExpression(inner) ||
+ ts.isFunctionDeclaration(inner)
+ )
+ return inner;
+ if (ts.isIdentifier(inner)) return functionOf(sf, declarationOf(sf, inner.text), depth + 1);
+ if (ts.isCallExpression(inner)) {
+ const callee = inner.expression;
+ const name = ts.isPropertyAccessExpression(callee) ? callee.name.text : callee.getText(sf);
+ return WRAPPERS.has(name) ? functionOf(sf, inner.arguments[0], depth + 1) : undefined;
+ }
+ return undefined;
+};
+
+export const findComponent = (sf: ts.SourceFile, exported: string) => {
+ for (const statement of sf.statements) {
+ if (exported === 'default' && ts.isExportAssignment(statement))
+ return functionOf(sf, statement.expression);
+ if (ts.isFunctionDeclaration(statement) && isExported(statement)) {
+ const isDefault = ts
+ .getModifiers(statement)
+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
+ if (isDefault ? exported === 'default' : statement.name?.text === exported) return statement;
+ }
+ if (ts.isVariableStatement(statement) && isExported(statement))
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === exported)
+ return functionOf(sf, declaration.initializer);
+ if (
+ ts.isExportDeclaration(statement) &&
+ !statement.moduleSpecifier &&
+ statement.exportClause &&
+ ts.isNamedExports(statement.exportClause)
+ )
+ for (const element of statement.exportClause.elements)
+ if (element.name.text === exported)
+ return functionOf(sf, declarationOf(sf, (element.propertyName ?? element.name).text));
+ }
+ return undefined;
+};
+
+const importOf = (sf: ts.SourceFile, local: string) => {
+ for (const statement of sf.statements) {
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
+ continue;
+ const clause = statement.importClause;
+ const source = statement.moduleSpecifier.text;
+ if (clause?.name?.text === local) return { imported: 'default', source };
+ const named = clause?.namedBindings;
+ if (named && ts.isNamespaceImport(named) && named.name.text === local)
+ return { imported: '*', source };
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements)
+ if (element.name.text === local)
+ return { imported: (element.propertyName ?? element.name).text, source };
+ }
+ return undefined;
+};
+
+const isReference = (node: ts.Identifier) => {
+ const { parent } = node;
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node) return false;
+ if (ts.isPropertyAssignment(parent) && parent.name === node) return false;
+ if (ts.isJsxAttribute(parent) && parent.name === node) return false;
+ return !(ts.isBindingElement(parent) && parent.propertyName === node);
+};
+
+const referencesIn = (root: ts.Node, name: string) => {
+ const found: ts.Identifier[] = [];
+ const visit = (node: ts.Node) => {
+ if (ts.isIdentifier(node) && node.text === name && isReference(node)) found.push(node);
+ ts.forEachChild(node, visit);
+ };
+ visit(root);
+ return found;
+};
+
+const outerOf = (node: ts.Node) => {
+ let current = node;
+ while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
+ return current;
+};
+
+const applicationAt = (reference: ts.Identifier, sf: ts.SourceFile) => {
+ const outer = outerOf(reference);
+ const holder = outer.parent;
+ if (ts.isJsxExpression(holder) && ts.isJsxAttribute(holder.parent))
+ return holder.parent.name.getText(sf) === 'className'
+ ? { application: 'className' as const, attribute: holder.parent }
+ : undefined;
+ if (!ts.isCallExpression(holder) || holder.arguments.length !== 1) return undefined;
+ const callee = holder.expression;
+ if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'props') return undefined;
+ if (
+ !ts.isIdentifier(callee.expression) ||
+ importOf(sf, callee.expression.text)?.source !== STYLEX
+ )
+ return undefined;
+ const call = outerOf(holder);
+ if (ts.isJsxSpreadAttribute(call.parent))
+ return { application: 'spread' as const, attribute: call.parent };
+ const access = call.parent;
+ if (!ts.isPropertyAccessExpression(access) || access.name.text !== 'className') return undefined;
+ const value = outerOf(access).parent;
+ return ts.isJsxExpression(value) &&
+ ts.isJsxAttribute(value.parent) &&
+ value.parent.name.getText(sf) === 'className'
+ ? { application: 'props' as const, attribute: value.parent }
+ : undefined;
+};
+
+const jsxChildren = (node: ts.Node) =>
+ ts.isJsxElement(node) || ts.isJsxFragment(node)
+ ? node.children.filter(
+ (child): child is JsxNode => ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child),
+ )
+ : [];
+
+const rootReturn = (fn: ComponentFunction) => {
+ if (!fn.body) return undefined;
+ if (!ts.isBlock(fn.body)) return unwrap(fn.body);
+ const returns = fn.body.statements.filter(ts.isReturnStatement);
+ const last = returns.at(-1)?.expression;
+ return last && unwrap(last);
+};
+
+const pathTo = (fn: ComponentFunction, element: JsxNode) => {
+ const root = rootReturn(fn);
+ const path: number[] = [];
+ let node: ts.Node = element;
+ while (node !== root) {
+ const { parent } = node;
+ if (ts.isJsxElement(parent) || ts.isJsxFragment(parent)) {
+ path.unshift(jsxChildren(parent).indexOf(node as JsxNode));
+ node = parent;
+ } else if (ts.isParenthesizedExpression(parent)) node = parent;
+ else return undefined;
+ }
+ return path;
+};
+
+const describe = (node: JsxNode, sf: ts.SourceFile, skip?: ts.Node) => {
+ const opening = ts.isJsxElement(node) ? node.openingElement : node;
+ const tag = opening.tagName.getText(sf);
+ const attributes: Record<string, LiteralValue> = {};
+ for (const attribute of opening.attributes.properties) {
+ if (attribute === skip) continue;
+ if (ts.isJsxSpreadAttribute(attribute)) return { reason: 'FORWARD_ATTRIBUTES_UNMODELED:...' };
+ const name = attribute.name.getText(sf);
+ if (name === 'key' || name === 'ref' || /^on[A-Z]/.test(name)) continue;
+ const { initializer } = attribute;
+ const value = !initializer
+ ? true
+ : ts.isStringLiteral(initializer)
+ ? initializer.text
+ : ts.isJsxExpression(initializer) && initializer.expression
+ ? literalOf(initializer.expression)
+ : undefined;
+ if (value !== undefined) attributes[name] = value;
+ else if (STYLE_ATTRIBUTES.has(name)) return { reason: `FORWARD_ATTRIBUTES_UNMODELED:${name}` };
+ }
+ const tagImport = /^[a-z]/.test(tag) ? undefined : importOf(sf, tag);
+ return { attributes, tag, ...(tagImport ? { tagImport } : {}) };
+};
+
+const elementOf = (attribute: ts.Node) => {
+ const opening = attribute.parent.parent as ts.JsxOpeningElement | ts.JsxSelfClosingElement;
+ return ts.isJsxOpeningElement(opening) ? opening.parent : opening;
+};
+
+export const applicationIn = (fn: ComponentFunction, prop: string, sf: ts.SourceFile) => {
+ const [first] = fn.parameters;
+ const pattern = first?.name;
+ if (!pattern || !ts.isObjectBindingPattern(pattern))
+ return { reason: 'FORWARD_PROP_NOT_DESTRUCTURED' };
+ const binding = pattern.elements.find(
+ (element) => (element.propertyName ?? element.name).getText(sf) === prop,
+ );
+ if (!binding || !ts.isIdentifier(binding.name))
+ return { reason: 'FORWARD_PROP_NOT_DESTRUCTURED' };
+ if (binding.initializer) return { reason: 'FORWARD_PROP_DEFAULTED' };
+ const references = fn.body ? referencesIn(fn.body, binding.name.text) : [];
+ if (references.length !== 1) return { reason: `FORWARD_APPLIED_${references.length}_TIMES` };
+ const applied = applicationAt(references[0], sf);
+ if (!applied) return { reason: 'FORWARD_APPLICATION_UNSUPPORTED' };
+ const element = elementOf(applied.attribute);
+ const path = pathTo(fn, element);
+ if (!path) return { reason: 'FORWARD_CONDITIONAL' };
+ return { application: applied.application, attribute: applied.attribute, element, path };
+};
+
+export const resolveForward = (code: string, exported: string, prop: string): ForwardResolution => {
+ const sf = parse(code);
+ const fn = findComponent(sf, exported);
+ if (!fn) return { prop, reason: 'FORWARD_COMPONENT_NOT_FOUND' };
+ const found = applicationIn(fn, prop, sf);
+ if (!('element' in found) || !found.element) return { prop, reason: found.reason };
+ const described = describe(found.element, sf, found.attribute);
+ if ('reason' in described) return { prop, reason: described.reason };
+ return { prop, target: { application: found.application, ...described, path: found.path } };
+};
+
+export const elementAtPath = (
+ code: string,
+ exported: string,
+ path: number[],
+): ForwardElement | { reason: string } => {
+ const sf = parse(code);
+ const fn = findComponent(sf, exported);
+ const root = fn && rootReturn(fn);
+ if (
+ !root ||
+ !(ts.isJsxElement(root) || ts.isJsxSelfClosingElement(root) || ts.isJsxFragment(root))
+ )
+ return { reason: 'FORWARD_BASE_MISSING' };
+ let node: ts.Node | undefined = root;
+ for (const index of path) node = node && jsxChildren(node)[index];
+ if (!node || !(ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)))
+ return { reason: 'FORWARD_BASE_MISSING' };
+ const described = describe(node, sf);
+ return 'reason' in described ? { reason: described.reason! } : { ...described, path };
+};
+
+export const componentOfStatement = (sf: ts.SourceFile, statement: ts.Statement) => {
+ if (ts.isFunctionDeclaration(statement)) return statement;
+ if (ts.isExportAssignment(statement)) return functionOf(sf, statement.expression);
+ if (!ts.isVariableStatement(statement)) return undefined;
+ const [declaration] = statement.declarationList.declarations;
+ return statement.declarationList.declarations.length === 1
+ ? functionOf(sf, declaration.initializer)
+ : undefined;
+};
+
+export const FORWARDABLE_PROP = /^(?:className|xstyle|[a-z]\w*(?:ClassName|Xstyle))$/;
+
+interface ForwardOptions {
+ readBaseModule?: (fromFile: string, specifier: string) => string | undefined;
+ readModule?: (fromFile: string, specifier: string) => string | undefined;
+}
+
+export const forwardsOf = (
+ tag: string,
+ bindings: Array<{ prop: string; spread: boolean }>,
+ file: string,
+ imports: Map<string, ts.ImportDeclaration>,
+ options: ForwardOptions,
+) => {
+ const statement = imports.get(tag);
+ if (/^[a-z]/.test(tag) || !statement || !ts.isStringLiteral(statement.moduleSpecifier)) return [];
+ const specifier = statement.moduleSpecifier.text;
+ const clause = statement.importClause;
+ const named = clause?.namedBindings;
+ const exported =
+ clause?.name?.text === tag
+ ? 'default'
+ : named && ts.isNamedImports(named)
+ ? (named.elements.find((element) => element.name.text === tag)?.propertyName?.text ?? tag)
+ : undefined;
+ const code = exported && options.readModule?.(file, specifier);
+ if (!exported || !code) return [];
+ const baseCode = options.readBaseModule?.(file, specifier);
+ return bindings
+ .filter((binding) => !binding.spread && FORWARDABLE_PROP.test(binding.prop))
+ .map((binding): ForwardResolution => {
+ const resolution = resolveForward(code, exported, binding.prop);
+ const { target } = resolution;
+ if (!target) return resolution;
+ const base =
+ baseCode === undefined ? undefined : elementAtPath(baseCode, exported, target.path);
+ if (!base)
+ return { prop: binding.prop, target: { ...target, baseReason: 'FORWARD_BASE_UNREADABLE' } };
+ return 'reason' in base
+ ? { prop: binding.prop, target: { ...target, baseReason: base.reason } }
+ : { prop: binding.prop, target: { ...target, base } };
+ });
+};
diff --git a/packages/style-equivalence/src/extract/globalStyles.ts b/packages/style-equivalence/src/extract/globalStyles.ts
new file mode 100644
index 00000000000..74860da9a67
--- /dev/null
+++ b/packages/style-equivalence/src/extract/globalStyles.ts
@@ -0,0 +1,120 @@
+import ts from 'typescript';
+
+import { importAliases, parseRules, templateText } from './css';
+import type { StyleRule } from './types';
+
+const GLOBAL_FACTORIES = new Set(['createGlobalStyle', 'injectGlobal']);
+const MAX_DEPTH = 4;
+
+type ReadModule = (specifier: string) => string | undefined;
+
+interface Scope {
+ constants: Map<string, ts.Expression>;
+ imports: Map<string, { imported: string; specifier: string }>;
+ readModule?: ReadModule;
+ sf: ts.SourceFile;
+}
+
+const scopeOf = (sf: ts.SourceFile, readModule?: ReadModule): Scope => {
+ const constants = new Map<string, ts.Expression>();
+ const imports = new Map<string, { imported: string; specifier: string }>();
+ for (const statement of sf.statements) {
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
+ const named = statement.importClause?.namedBindings;
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements)
+ imports.set(element.name.text, {
+ imported: (element.propertyName ?? element.name).text,
+ specifier: statement.moduleSpecifier.text,
+ });
+ }
+ if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const)
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.initializer)
+ constants.set(declaration.name.text, declaration.initializer);
+ }
+ return { constants, imports, readModule, sf };
+};
+
+const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)
+ ? unwrap(node.expression)
+ : node;
+
+const lookup = (name: string, scope: Scope, depth: number) => {
+ const local = scope.constants.get(name);
+ if (local) return { node: local, scope };
+ const imported = scope.imports.get(name);
+ const code = imported && scope.readModule?.(imported.specifier);
+ if (!imported || !code || depth > MAX_DEPTH) return undefined;
+ const sf = ts.createSourceFile('module.ts', code, ts.ScriptTarget.Latest, true);
+ const next = scopeOf(sf);
+ const node = next.constants.get(imported.imported);
+ return node && { node, scope: next };
+};
+
+export const foldConstant = (raw: ts.Expression, scope: Scope, depth = 0): string | undefined => {
+ if (depth > MAX_DEPTH) return undefined;
+ const node = unwrap(raw);
+ if (ts.isStringLiteralLike(node)) return node.text;
+ if (ts.isNumericLiteral(node)) return String(Number(node.getText().replaceAll('_', '')));
+ if (ts.isIdentifier(node)) {
+ const found = lookup(node.text, scope, depth);
+ return found && foldConstant(found.node, found.scope, depth + 1);
+ }
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
+ const found = lookup(node.expression.text, scope, depth);
+ const object = found && unwrap(found.node);
+ if (!object || !ts.isObjectLiteralExpression(object)) return undefined;
+ const property = object.properties.find(
+ (item): item is ts.PropertyAssignment =>
+ ts.isPropertyAssignment(item) &&
+ (ts.isIdentifier(item.name) || ts.isStringLiteral(item.name)) &&
+ item.name.text === node.name.text,
+ );
+ return property && foldConstant(property.initializer, found.scope, depth + 1);
+ }
+ return undefined;
+};
+
+const isGlobalFactory = (tag: ts.Expression) =>
+ ts.isIdentifier(tag) && GLOBAL_FACTORIES.has(tag.text);
+
+export const globalStyleRules = (sf: ts.SourceFile, readModule?: ReadModule): StyleRule[] => {
+ const scope = scopeOf(sf, readModule);
+ const tokenAliases = importAliases(sf, 'cssVar');
+ const rules: StyleRule[] = [];
+ const visit = (node: ts.Node) => {
+ if (ts.isTaggedTemplateExpression(node) && isGlobalFactory(node.tag)) {
+ const spans = ts.isTemplateExpression(node.template) ? node.template.templateSpans : [];
+ const interpolations = spans.map(({ expression }) => {
+ const alias =
+ ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)
+ ? tokenAliases.get(expression.expression.text)
+ : undefined;
+ if (alias && ts.isPropertyAccessExpression(expression))
+ return `${alias}.${expression.name.text}`;
+ return expression.getText(sf).replaceAll(/\s+/g, ' ').trim();
+ });
+ const folded = spans.map((span) => foldConstant(span.expression, scope) ?? null);
+ const parsed = parseRules(templateText(node.template));
+ const symbol = ts.isVariableDeclaration(node.parent)
+ ? node.parent.name.getText(sf)
+ : 'global';
+ for (const rule of parsed.error ? [] : parsed.rules)
+ rules.push({
+ ...rule,
+ ...(interpolations.length ? { interpolations } : {}),
+ ...(folded.some((item) => item !== null) ? { interpolationValues: folded } : {}),
+ owned: {},
+ stylesheet: `global:${symbol}`,
+ });
+ if (parsed.error)
+ rules.push({ conditions: [], owned: {}, selector: '', stylesheet: `unparsed:${symbol}` });
+ return;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ return rules;
+};
diff --git a/packages/style-equivalence/src/extract/identifiers.ts b/packages/style-equivalence/src/extract/identifiers.ts
new file mode 100644
index 00000000000..f1bd49b6adc
--- /dev/null
+++ b/packages/style-equivalence/src/extract/identifiers.ts
@@ -0,0 +1,143 @@
+import ts from 'typescript';
+
+import type { VariableKind } from './types';
+
+export const isJsxNode = (node: ts.Node) =>
+ ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
+
+const isTagName = (node: ts.Identifier) => {
+ const parent = node.parent;
+ return (
+ (ts.isJsxOpeningElement(parent) ||
+ ts.isJsxSelfClosingElement(parent) ||
+ ts.isJsxClosingElement(parent)) &&
+ parent.tagName === node
+ );
+};
+
+const isNameOnly = (node: ts.Identifier) => {
+ const parent = node.parent;
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node) return true;
+ if (
+ (ts.isPropertyAssignment(parent) ||
+ ts.isMethodDeclaration(parent) ||
+ ts.isPropertyDeclaration(parent)) &&
+ parent.name === node
+ )
+ return true;
+ if (ts.isJsxAttribute(parent) && parent.name === node) return true;
+ if (ts.isBindingElement(parent) && parent.propertyName === node) return true;
+ return false;
+};
+
+export interface IdentifierOptions {
+ includeTags?: boolean;
+ skipJsx?: boolean;
+}
+
+export const valueIdentifierNodes = (root: ts.Node, options: IdentifierOptions = {}) => {
+ const found: ts.Identifier[] = [];
+ const visit = (node: ts.Node) => {
+ if (options.skipJsx && isJsxNode(node)) return;
+ if (ts.isTypeNode(node)) return;
+ if (ts.isIdentifier(node) && !isNameOnly(node) && (options.includeTags || !isTagName(node)))
+ found.push(node);
+ if (ts.isShorthandPropertyAssignment(node)) found.push(node.name);
+ ts.forEachChild(node, visit);
+ };
+ if (options.skipJsx && isJsxNode(root)) return found;
+ visit(root);
+ return found;
+};
+
+export const valueIdentifiers = (root: ts.Node, options: IdentifierOptions = {}) =>
+ new Set(valueIdentifierNodes(root, options).map((node) => node.text));
+
+const outerOf = (node: ts.Expression) => {
+ let current: ts.Node = node;
+ while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
+ return current;
+};
+
+const isBooleanContext = (node: ts.Node): boolean => {
+ const expression = outerOf(node as ts.Expression);
+ const parent = expression.parent;
+ if (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken)
+ return true;
+ if (ts.isConditionalExpression(parent) && parent.condition === expression) return true;
+ if (
+ ts.isBinaryExpression(parent) &&
+ [
+ ts.SyntaxKind.AmpersandAmpersandToken,
+ ts.SyntaxKind.BarBarToken,
+ ts.SyntaxKind.QuestionQuestionToken,
+ ].includes(parent.operatorToken.kind)
+ )
+ return parent.left === expression || isBooleanContext(parent);
+ return false;
+};
+
+const usageOf = (node: ts.Identifier): VariableKind => {
+ const parent = node.parent;
+ if (ts.isCallExpression(parent) && parent.expression === node) return 'call';
+ if (
+ (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) &&
+ parent.expression === node
+ ) {
+ let top: ts.Expression = parent;
+ while (
+ (ts.isPropertyAccessExpression(top.parent) || ts.isElementAccessExpression(top.parent)) &&
+ top.parent.expression === top
+ )
+ top = top.parent;
+ return isBooleanContext(top) ? 'member' : 'unknown';
+ }
+ return isBooleanContext(node) ? 'boolean' : 'unknown';
+};
+
+export const mergeKinds = (kinds: VariableKind[]): VariableKind => {
+ const unique = [...new Set(kinds)];
+ return unique.length === 1 ? unique[0] : 'unknown';
+};
+
+export const usageKinds = (root: ts.Node, names: Set<string>) => {
+ const kinds = new Map<string, VariableKind[]>();
+ for (const node of valueIdentifierNodes(root, { skipJsx: true })) {
+ if (!names.has(node.text)) continue;
+ kinds.set(node.text, [...(kinds.get(node.text) ?? []), usageOf(node)]);
+ }
+ return kinds;
+};
+
+const bindingNames = (name: ts.BindingName): string[] =>
+ ts.isIdentifier(name)
+ ? [name.text]
+ : name.elements.flatMap((element) =>
+ ts.isOmittedExpression(element) ? [] : bindingNames(element.name),
+ );
+
+export const declaredLocally = (node: ts.Identifier) => {
+ for (let scope: ts.Node = node.parent; !ts.isSourceFile(scope); scope = scope.parent) {
+ if (ts.isFunctionLike(scope))
+ for (const parameter of scope.parameters)
+ if (bindingNames(parameter.name).includes(node.text)) return true;
+ if (ts.isBlock(scope))
+ for (const statement of scope.statements)
+ if (
+ ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some((declaration) =>
+ bindingNames(declaration.name).includes(node.text),
+ )
+ )
+ return true;
+ }
+ return false;
+};
+
+export const literalText = (node: ts.Node) =>
+ ts.isStringLiteralLike(node) ||
+ ts.isTemplateHead(node) ||
+ ts.isTemplateMiddle(node) ||
+ ts.isTemplateTail(node)
+ ? node.text
+ : undefined;
diff --git a/packages/style-equivalence/src/extract/importedClasses.ts b/packages/style-equivalence/src/extract/importedClasses.ts
new file mode 100644
index 00000000000..45a0a574541
--- /dev/null
+++ b/packages/style-equivalence/src/extract/importedClasses.ts
@@ -0,0 +1,84 @@
+import ts from 'typescript';
+
+import { valueIdentifierNodes } from './identifiers';
+import type { StyleAdapter } from './types';
+
+export interface ImportedClass {
+ expansion: string;
+ factories: Map<string, ts.CallExpression>;
+ tokens: string[];
+}
+
+const MAX_DEPTH = 4;
+
+export const NAMESPACE = '$';
+
+export const importedClassOf = (
+ code: string,
+ imported: string,
+ local: string,
+ adapters: StyleAdapter[],
+): ImportedClass | undefined => {
+ const sf = ts.createSourceFile(
+ 'module.tsx',
+ code,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const initializers = new Map<string, ts.Expression>();
+ const exported = new Set<string>();
+ for (const statement of sf.statements) {
+ if (!ts.isVariableStatement(statement)) continue;
+ const isExported = statement.modifiers?.some(
+ (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
+ );
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.initializer) {
+ initializers.set(declaration.name.text, declaration.initializer);
+ if (isExported) exported.add(declaration.name.text);
+ }
+ }
+ const isFactory = (node: ts.Expression | undefined): node is ts.CallExpression =>
+ !!node &&
+ ts.isCallExpression(node) &&
+ adapters.some((adapter) => adapter.recognizeFactory(node));
+ const root = initializers.get(imported);
+ if (!exported.has(imported) || !root || isFactory(root)) return undefined;
+ const factories = new Map<string, ts.CallExpression>();
+ const tokens = new Set<string>();
+ const expand = (node: ts.Expression, depth: number): string | undefined => {
+ if (depth > MAX_DEPTH) return undefined;
+ const start = node.getStart(sf);
+ let text = node.getText(sf);
+ const visitLiterals = (child: ts.Node) => {
+ if (ts.isStringLiteralLike(child))
+ child.text.split(/\s+/).forEach((token) => token && tokens.add(token));
+ ts.forEachChild(child, visitLiterals);
+ };
+ visitLiterals(node);
+ const replacements: Array<[number, number, string]> = [];
+ for (const identifier of valueIdentifierNodes(node)) {
+ const name = identifier.text;
+ const target = initializers.get(name);
+ if (!target) continue;
+ let replacement: string | undefined;
+ if (isFactory(target)) {
+ replacement = `${local}${NAMESPACE}${name}`;
+ factories.set(replacement, target);
+ } else {
+ const inner = expand(target, depth + 1);
+ if (inner === undefined) return undefined;
+ replacement = `(${inner})`;
+ }
+ replacements.push([identifier.getStart(sf) - start, identifier.end - start, replacement]);
+ }
+ for (const [from, to, replacement] of replacements.sort(([a], [b]) => b - a))
+ text = text.slice(0, from) + replacement + text.slice(to);
+ return text;
+ };
+ const expansion = expand(root, 0);
+ return expansion !== undefined && (factories.size || tokens.size)
+ ? { expansion, factories, tokens: [...tokens] }
+ : undefined;
+};
diff --git a/packages/style-equivalence/src/extract/index.ts b/packages/style-equivalence/src/extract/index.ts
new file mode 100644
index 00000000000..08ed744429b
--- /dev/null
+++ b/packages/style-equivalence/src/extract/index.ts
@@ -0,0 +1,500 @@
+import ts from 'typescript';
+
+import { aliasDeclaration, aliasOf } from './aliases';
+import { booleanAttribute, isStateAttribute } from './attributes';
+import { collectChildren, literalOf } from './children';
+import { localCondition, renderGuards } from './constraints';
+import { parseRules } from './css';
+import { applicationIn, componentOfStatement, forwardsOf } from './forward';
+import { globalStyleRules } from './globalStyles';
+import {
+ declaredLocally,
+ isJsxNode,
+ literalText,
+ mergeKinds,
+ usageKinds,
+ valueIdentifierNodes,
+} from './identifiers';
+import { applyRenderedStyle, renderedStyle, slotStylesOf } from './renderedStyle';
+import { classifyRules, classNamesIn, foreignClassNames } from './selectors';
+import { collectTables } from './tables';
+import { collectTopLevel } from './topLevel';
+import type {
+ ExtractOptions,
+ FileExtraction,
+ LiteralValue,
+ StyleBinding,
+ StyleElement,
+ StyleRule,
+ VariableKind,
+} from './types';
+import { stylexUnsupported } from './unsupported';
+
+export type * from './types';
+
+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,
+ options: ExtractOptions,
+): FileExtraction => {
+ const ast = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const top = collectTopLevel(ast, options.adapters, (specifier) =>
+ options.readModule?.(file, specifier),
+ );
+ const markers = new Set(options.adapters.flatMap((adapter) => adapter.markerIdentifiers));
+ 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 derived = new Map<string, string>();
+ const isStyleName = (name: string) => top.styleSymbols.has(name) || markers.has(name);
+ const referencesStyle = (node: ts.Node, prop?: string) =>
+ valueIdentifierNodes(node, { skipJsx: true }).some(
+ (identifier) =>
+ isStyleName(identifier.text) ||
+ !!aliasOf(identifier, top.styleSymbols) ||
+ (CLASS_PROPS.has(prop ?? '') && derived.has(identifier.text)),
+ );
+ const slotsOf = (node: ts.Node) => {
+ const slots = new Set<string>();
+ const visit = (current: ts.Node) => {
+ if (isJsxNode(current)) return;
+ if (
+ ts.isPropertyAccessExpression(current) &&
+ ts.isIdentifier(current.expression) &&
+ (top.styleSymbols.has(current.expression.text) ||
+ aliasOf(current.expression, top.styleSymbols))
+ )
+ slots.add(
+ `${top.styleSymbols.has(current.expression.text) ? current.expression.text : aliasOf(current.expression, top.styleSymbols)}.${current.name.text}`,
+ );
+ ts.forEachChild(current, visit);
+ };
+ if (!isJsxNode(node)) ts.forEachChild(node, visit);
+ if (ts.isPropertyAccessExpression(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 expandedOf = (expression: ts.Expression) => {
+ const start = expression.getStart(ast);
+ let text = expression.getText(ast);
+ const found = valueIdentifierNodes(expression, { skipJsx: true })
+ .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)}`;
+ const parsed = ts.createSourceFile(
+ 'x.tsx',
+ `(${text});`,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const [statement] = parsed.statements;
+ return statement && ts.isExpressionStatement(statement)
+ ? { node: statement.expression, text }
+ : undefined;
+ };
+ const usedGlobal = new Set<string>();
+ const globalTokensIn = (node: ts.Node) => {
+ const tokens = new Set<string>();
+ const visit = (current: ts.Node) => {
+ const text = literalText(current);
+ if (text !== undefined)
+ for (const token of text.split(/\s+/)) if (globalClasses.has(token)) tokens.add(token);
+ ts.forEachChild(current, visit);
+ };
+ visit(node);
+ return tokens;
+ };
+
+ const elements: StyleElement[] = [];
+ const styled = new Map<ts.Node, StyleElement>();
+ const classTokens = new Map<string, Set<string>>();
+ const bound = new Set<ts.Node>();
+
+ for (const statement of ast.statements) {
+ if (top.keptStatements.has(statement) || ts.isImportDeclaration(statement)) continue;
+ const owner = ownerOf(statement, ast);
+ let ordinal = 0;
+ const visit = (node: ts.Node, parent: string | undefined): void => {
+ if (!ts.isJsxElement(node) && !ts.isJsxSelfClosingElement(node)) {
+ ts.forEachChild(node, (child) => visit(child, parent));
+ return;
+ }
+ const opening = ts.isJsxElement(node) ? node.openingElement : node;
+ const bindings: StyleBinding[] = [];
+ const literalProps: Record<string, LiteralValue> = {};
+ const attributes: Record<string, string> = {};
+ const attributeNames: ts.Identifier[] = [];
+ let iconNode: ts.Node | undefined;
+ const slots = new Set<string>();
+ const expressions: ts.Expression[] = [];
+ const expansions: ts.Expression[] = [];
+ const bindingOf = (expression: ts.Expression, prop: string, spread: boolean) => {
+ bound.add(expression);
+ expressions.push(expression);
+ slotsOf(expression).forEach((slot) => slots.add(slot));
+ for (const token of globalTokensIn(expression)) {
+ usedGlobal.add(token);
+ slots.add(`global.${token}`);
+ }
+ const expanded = expandedOf(expression);
+ if (expanded) {
+ expansions.push(expanded.node);
+ slotsOf(expanded.node).forEach((slot) => slots.add(slot));
+ for (const token of globalTokensIn(expanded.node)) {
+ usedGlobal.add(token);
+ slots.add(`global.${token}`);
+ }
+ }
+ bindings.push({
+ expr: expression.getText(ast),
+ ...(expanded ? { expansion: expanded.text } : {}),
+ prop,
+ spread,
+ });
+ };
+ let runtimeStyle: string | undefined;
+ let styleExpr: string | undefined;
+ let inlineStyle: ReturnType<typeof renderedStyle>;
+ let lastStyle = -1;
+ let lastForeign = -1;
+ for (const [position, attribute] of opening.attributes.properties.entries()) {
+ if (ts.isJsxSpreadAttribute(attribute)) {
+ if (!referencesStyle(attribute.expression, '...')) {
+ lastForeign = position;
+ continue;
+ }
+ lastStyle = position;
+ bindingOf(attribute.expression, '...', true);
+ continue;
+ }
+ const name = attribute.name.getText(ast);
+ const initializer =
+ attribute.initializer &&
+ ts.isJsxExpression(attribute.initializer) &&
+ attribute.initializer.expression &&
+ (ts.isStringLiteral(attribute.initializer.expression) ||
+ ts.isNoSubstitutionTemplateLiteral(attribute.initializer.expression))
+ ? ts.factory.createStringLiteral(attribute.initializer.expression.text)
+ : attribute.initializer;
+ if (!initializer) {
+ literalProps[name] = true;
+ continue;
+ }
+ if (ts.isStringLiteral(initializer)) {
+ const matched =
+ name === 'className'
+ ? initializer.text.split(/\s+/).filter((token) => globalClasses.has(token))
+ : [];
+ if (matched.length) {
+ bindings.push({ expr: JSON.stringify(initializer.text), prop: name, spread: false });
+ matched.forEach((token) => {
+ usedGlobal.add(token);
+ slots.add(`global.${token}`);
+ });
+ continue;
+ }
+ literalProps[name] = initializer.text;
+ continue;
+ }
+ if (!ts.isJsxExpression(initializer) || !initializer.expression) continue;
+ const expression = initializer.expression;
+ if (name === 'icon' && isJsxNode(expression)) iconNode = expression;
+ const slotStyles = slotStylesOf(name, opening.tagName.getText(ast), expression, top);
+ if (referencesStyle(expression, name) || slotStyles) {
+ bindingOf(expression, name, false);
+ if (slotStyles && ts.isIdentifier(expression)) bindings.at(-1)!.expansion = slotStyles;
+ continue;
+ }
+ const literal = literalOf(expression);
+ if (literal !== undefined) literalProps[name] = literal;
+ else if (
+ isStateAttribute(name) &&
+ ts.isIdentifier(expression) &&
+ !GLOBALS.has(expression.text) &&
+ booleanAttribute(code, name)
+ ) {
+ attributes[name] = expression.text;
+ attributeNames.push(expression);
+ } else if (
+ name === 'style' &&
+ !(ts.isIdentifier(expression) && GLOBALS.has(expression.text))
+ ) {
+ styleExpr = expression.getText(ast).replaceAll(/\s+/g, ' ');
+ inlineStyle = renderedStyle(expression, top.importOf, GLOBALS);
+ lastStyle = position;
+ if (ts.isIdentifier(expression)) runtimeStyle = expression.text;
+ }
+ }
+ let current = parent;
+ if (bindings.length) {
+ const tag = opening.tagName.getText(ast);
+ const names = new Set<string>();
+ const used = new Map<string, string>();
+ const derivedConditions: Record<string, string> = {};
+ for (const expression of expressions)
+ for (const node of valueIdentifierNodes(expression, { skipJsx: true })) {
+ const name = node.text;
+ if (GLOBALS.has(name)) continue;
+ const alias = aliasOf(node, top.styleSymbols);
+ if (alias) {
+ used.set(name, alias);
+ continue;
+ }
+ const condition = localCondition(node);
+ if (condition) derivedConditions[name] = condition;
+ if (declaredLocally(node)) names.add(name);
+ else if (markers.has(name)) top.require(name);
+ else if (!top.styleSymbols.has(name) && !top.require(name)) names.add(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]);
+ if (inlineStyle) applyRenderedStyle(inlineStyle, top.require, names, kinds);
+ for (const node of attributeNames)
+ if (
+ declaredLocally(node) ||
+ (!top.styleSymbols.has(node.text) && !top.require(node.text))
+ ) {
+ names.add(node.text);
+ kinds.set(node.text, [...(kinds.get(node.text) ?? []), 'boolean']);
+ }
+ const real = isReal(tag);
+ const guards = renderGuards(node);
+ if (layout.has(tag) || real) top.require(tag);
+ const id = `${owner}#${ordinal++}`;
+ const tokens = new Set<string>();
+ const collectTokens = (node: ts.Node) => {
+ literalText(node)
+ ?.split(/\s+/)
+ .forEach((token) => token && tokens.add(token));
+ ts.forEachChild(node, collectTokens);
+ };
+ expressions.forEach(collectTokens);
+ expansions.forEach(collectTokens);
+ for (const binding of bindings)
+ if (binding.prop === 'className' && binding.expr.startsWith('"'))
+ (JSON.parse(binding.expr) as string).split(/\s+/).forEach((token) => tokens.add(token));
+ classTokens.set(id, tokens);
+ const element: StyleElement = {
+ bindings,
+ flags: [],
+ id,
+ literalProps,
+ ...(Object.keys(attributes).length ? { attributes } : {}),
+ ...(Object.keys(derivedConditions).length ? { derived: derivedConditions } : {}),
+ ...(guards.length ? { guards } : {}),
+ ...(inlineStyle ? { inlineStyle: inlineStyle.text } : {}),
+ owner,
+ parent,
+ ...(real ? { real } : {}),
+ ...(runtimeStyle && !opening.attributes.properties.some(ts.isJsxSpreadAttribute)
+ ? { runtimeStyle }
+ : {}),
+ slots: [...slots].sort(),
+ ...(styleExpr ? { styleExpr } : {}),
+ ...(opening.attributes.properties.filter(ts.isJsxSpreadAttribute).length >
+ bindings.filter((binding) => binding.spread).length
+ ? { foreignSpread: true }
+ : {}),
+ ...(lastForeign > lastStyle && lastStyle >= 0 ? { spreadAfterStyle: true } : {}),
+ ...(used.size ? { aliases: Object.fromEntries([...used].sort()) } : {}),
+ tag,
+ variables: [...names].sort().map((name) => ({
+ kind: mergeKinds(kinds.get(name) ?? ['unknown']),
+ name,
+ })),
+ };
+ const forwards = forwardsOf(tag, bindings, file, top.importOf, options);
+ if (forwards.length) element.forwards = forwards;
+ const [binding] = bindings;
+ const [variable] = element.variables;
+ if (bindings.length === 1 && element.variables.length === 1 && !binding.spread) {
+ const fn = componentOfStatement(ast, statement);
+ const found = fn && applicationIn(fn, variable.name, ast);
+ if (found && 'element' in found && found.element === node)
+ element.forwardedParam = variable.name;
+ }
+ elements.push(element);
+ styled.set(node, element);
+ current = id;
+ }
+ if (ts.isJsxElement(node)) {
+ ts.forEachChild(node.openingElement, (child) => visit(child, parent));
+ node.children.forEach((child) => visit(child, current));
+ } else ts.forEachChild(node, (child) => visit(child, parent));
+ const host = styled.get(node);
+ if (host && iconNode) host.iconElement = styled.get(iconNode)?.id ?? true;
+ };
+ visit(statement, undefined);
+ }
+
+ const plain = collectChildren(styled, ast, (tag) => {
+ const real = isReal(tag);
+ if (layout.has(tag) || real) top.require(tag);
+ return real;
+ });
+
+ const outsideReferences: string[] = [];
+ for (const statement of ast.statements) {
+ if (top.keptStatements.has(statement) || ts.isImportDeclaration(statement)) continue;
+ const visit = (node: ts.Node) => {
+ if (bound.has(node)) return;
+ if (ts.isIdentifier(node) && top.styleSymbols.has(node.text)) {
+ const parent = node.parent;
+ const nameOnly =
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
+ (ts.isPropertyAssignment(parent) && parent.name === node) ||
+ (ts.isJsxAttribute(parent) && parent.name === node);
+ const aliased =
+ ts.isVariableDeclaration(parent) &&
+ parent.initializer === node &&
+ aliasDeclaration(parent, top.styleSymbols) === node.text;
+ if (!nameOnly && !aliased)
+ outsideReferences.push(
+ `${node.text}@${ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1}`,
+ );
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(statement);
+ }
+
+ const globalOwned = Object.fromEntries([...usedGlobal].map((name) => [name, `global.${name}`]));
+ const ownersOf = (matches: (element: (typeof elements)[number]) => boolean) =>
+ new Set(elements.filter(matches).map((element) => element.owner));
+ const isLocal = (name: string, slots: string[]) => {
+ const carriers = ownersOf((element) => classTokens.get(element.id)?.has(name) ?? false);
+ const users = ownersOf((element) => element.slots.some((slot) => slots.includes(slot)));
+ return carriers.size > 0 && [...carriers].every((owner) => users.has(owner));
+ };
+ const flags = classifyRules(rules, globalOwned, isLocal);
+ const foreign = foreignClassNames(rules, globalOwned, isLocal);
+ for (const element of elements) {
+ const found = new Set(element.slots.flatMap((slot) => [...(flags.get(slot) ?? [])]));
+ if ([...(classTokens.get(element.id) ?? [])].some((token) => foreign.has(token)))
+ found.add('CROSS_COMPONENT');
+ element.flags = [...found].sort();
+ }
+
+ const globalRules = globalStyleRules(ast, (specifier) => options.readModule?.(file, specifier));
+ const literalClasses = new Set<string>();
+ const collectLiterals = (node: ts.Node) => {
+ literalText(node)
+ ?.split(/\s+/)
+ .forEach((token) => /^[a-z][\w-]*-[\w-]+$/i.test(token) && literalClasses.add(token));
+ ts.forEachChild(node, collectLiterals);
+ };
+ collectLiterals(ast);
+ return {
+ elements,
+ file,
+ gaps,
+ ...(globalRules.length ? { globalRules } : {}),
+ ...(literalClasses.size ? { literalClasses: [...literalClasses].sort() } : {}),
+ ...(Object.keys(unsupported).length ? { unsupported } : {}),
+ outsideReferences,
+ ...(plain.length ? { plain } : {}),
+ prelude: top.prelude(),
+ rules,
+ ...(Object.keys(slotConditions).length ? { slotConditions } : {}),
+ slotProperties,
+ styleSymbols: [...top.styleSymbols].sort(),
+ tables: collectTables(ast),
+ };
+};
diff --git a/packages/style-equivalence/src/extract/properties.ts b/packages/style-equivalence/src/extract/properties.ts
new file mode 100644
index 00000000000..7c06f85cfab
--- /dev/null
+++ b/packages/style-equivalence/src/extract/properties.ts
@@ -0,0 +1,111 @@
+import postcss from 'postcss';
+import ts from 'typescript';
+
+import { returnedObject, templateText } from './css';
+
+const PLACEHOLDER = /_I\d+__/;
+
+const templateProperties = (template: ts.TemplateLiteral) => {
+ const properties = new Set<string>();
+ let readable = true;
+ try {
+ const root = postcss.parse(templateText(template));
+ root.walkDecls((node) => {
+ if (PLACEHOLDER.test(node.prop)) readable = false;
+ else properties.add(node.prop.toLowerCase());
+ });
+ } catch {
+ return undefined;
+ }
+ return readable ? [...properties].sort() : undefined;
+};
+
+export const templateSlotProperties = (symbol: string, factory: ts.CallExpression) => {
+ const object = returnedObject(factory);
+ const found: Record<string, string[]> = {};
+ for (const property of object?.properties ?? []) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ const value = property.initializer;
+ if (!ts.isTaggedTemplateExpression(value)) continue;
+ const properties = templateProperties(value.template);
+ if (properties) found[`${symbol}.${property.name.getText()}`] = properties;
+ }
+ return found;
+};
+
+const keyOf = (name: ts.PropertyName) =>
+ ts.isIdentifier(name) || ts.isStringLiteral(name)
+ ? name.text
+ : ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)
+ ? name.expression.text
+ : undefined;
+
+const kebab = (key: string) =>
+ key.startsWith('--') ? key : key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
+
+const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;
+
+const objectProperties = (object: ts.ObjectLiteralExpression, into: Set<string>): boolean =>
+ object.properties.every((property) => {
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
+ return false;
+ const key = keyOf(property.name);
+ if (key === undefined) return false;
+ if (!/^[:@]/.test(key)) {
+ into.add(kebab(key));
+ return true;
+ }
+ const nested = ts.isPropertyAssignment(property) ? unwrap(property.initializer) : undefined;
+ return !!nested && ts.isObjectLiteralExpression(nested) && objectProperties(nested, into);
+ });
+
+const styleObjectOf = (value: ts.Expression) => {
+ const node = unwrap(value);
+ if (ts.isObjectLiteralExpression(node)) return node;
+ if (!ts.isArrowFunction(node) || ts.isBlock(node.body)) return undefined;
+ const body = unwrap(node.body);
+ return ts.isObjectLiteralExpression(body) ? body : undefined;
+};
+
+export const objectSlotProperties = (symbol: string, factory: ts.CallExpression) => {
+ const found: Record<string, string[]> = {};
+ const [argument] = factory.arguments;
+ const object = argument && unwrap(argument);
+ if (!object || !ts.isObjectLiteralExpression(object)) return found;
+ for (const property of object.properties) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ const slot = keyOf(property.name);
+ const style = styleObjectOf(property.initializer);
+ const properties = new Set<string>();
+ if (slot !== undefined && style && objectProperties(style, properties))
+ found[`${symbol}.${slot}`] = [...properties].sort();
+ }
+ return found;
+};
+
+const objectConditions = (object: ts.ObjectLiteralExpression, into: Set<string>) => {
+ for (const property of object.properties) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ const key = keyOf(property.name);
+ if (key?.startsWith(':')) into.add(key);
+ const nested = unwrap(property.initializer);
+ if (ts.isObjectLiteralExpression(nested)) objectConditions(nested, into);
+ }
+};
+
+export const objectSlotConditions = (symbol: string, factory: ts.CallExpression) => {
+ const found: Record<string, string[]> = {};
+ const [argument] = factory.arguments;
+ const object = argument && unwrap(argument);
+ if (!object || !ts.isObjectLiteralExpression(object)) return found;
+ for (const property of object.properties) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ const slot = keyOf(property.name);
+ const style = styleObjectOf(property.initializer);
+ const conditions = new Set<string>();
+ if (style) objectConditions(style, conditions);
+ if (slot !== undefined && conditions.size) found[`${symbol}.${slot}`] = [...conditions].sort();
+ }
+ return found;
+};
diff --git a/packages/style-equivalence/src/extract/renderedStyle.ts b/packages/style-equivalence/src/extract/renderedStyle.ts
new file mode 100644
index 00000000000..20773f3c9ed
--- /dev/null
+++ b/packages/style-equivalence/src/extract/renderedStyle.ts
@@ -0,0 +1,91 @@
+import ts from 'typescript';
+
+import { declaredLocally, usageKinds, valueIdentifierNodes } from './identifiers';
+import type { VariableKind } from './types';
+
+const PACKAGE = /^(?![./]|@\/)/;
+
+const hasCall = (node: ts.Node): boolean =>
+ ts.isCallExpression(node) ||
+ ts.isTaggedTemplateExpression(node) ||
+ !!ts.forEachChild(node, hasCall);
+
+export interface RenderedStyle {
+ imports: string[];
+ locals: string[];
+ text: string;
+}
+
+export const renderedStyle = (
+ expression: ts.Expression,
+ importOf: Map<string, ts.ImportDeclaration>,
+ globals: Set<string>,
+): RenderedStyle | undefined => {
+ if (ts.isIdentifier(expression) || hasCall(expression)) return undefined;
+ const locals = new Set<string>();
+ const imports = new Set<string>();
+ for (const node of valueIdentifierNodes(expression, { skipJsx: true })) {
+ if (globals.has(node.text)) continue;
+ if (declaredLocally(node)) {
+ locals.add(node.text);
+ continue;
+ }
+ const specifier = importOf.get(node.text)?.moduleSpecifier;
+ if (!specifier || !ts.isStringLiteral(specifier) || !PACKAGE.test(specifier.text))
+ return undefined;
+ imports.add(node.text);
+ }
+ const kinds = usageKinds(expression, locals);
+ if ([...locals].some((name) => (kinds.get(name) ?? []).some((kind) => kind !== 'boolean')))
+ return undefined;
+ return {
+ imports: [...imports],
+ locals: [...locals],
+ text: expression.getText().replaceAll(/\s+/g, ' '),
+ };
+};
+
+export const applyRenderedStyle = (
+ style: RenderedStyle,
+ require: (name: string) => boolean,
+ names: Set<string>,
+ kinds: Map<string, VariableKind[]>,
+) => {
+ for (const name of style.imports) require(name);
+ for (const name of style.locals) {
+ names.add(name);
+ kinds.set(name, [...(kinds.get(name) ?? []), 'boolean']);
+ }
+};
+
+const SLOT_GLOBALS = new Set(['undefined']);
+
+const constInitializer = (ast: ts.SourceFile, name: string) => {
+ for (const statement of ast.statements) {
+ if (!ts.isVariableStatement(statement)) continue;
+ if (!(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === name)
+ return declaration.initializer;
+ }
+ return undefined;
+};
+
+export const slotStylesOf = (
+ name: string,
+ tag: string,
+ expression: ts.Expression,
+ { importOf }: { importOf: Map<string, ts.ImportDeclaration> },
+) => {
+ if (name !== 'styles' || /^[a-z]/.test(tag)) return undefined;
+ const object = ts.isIdentifier(expression)
+ ? constInitializer(expression.getSourceFile(), expression.text)
+ : expression;
+ if (!object || !ts.isObjectLiteralExpression(object)) return undefined;
+ const slots = object.properties.every(
+ (property) =>
+ ts.isPropertyAssignment(property) && ts.isObjectLiteralExpression(property.initializer),
+ );
+ const rendered = slots && renderedStyle(object, importOf, SLOT_GLOBALS);
+ return rendered && !rendered.locals.length ? object.getText() : undefined;
+};
diff --git a/packages/style-equivalence/src/extract/selectors.test.ts b/packages/style-equivalence/src/extract/selectors.test.ts
new file mode 100644
index 00000000000..e0a4f86d64b
--- /dev/null
+++ b/packages/style-equivalence/src/extract/selectors.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+
+import { cssModulesAdapter } from './adapters/cssModules';
+import { emotionStaticAdapter } from './adapters/emotionStatic';
+import { globalCssAdapter } from './adapters/globalCss';
+import { stylexAdapter } from './adapters/stylex';
+import { extractFile } from './index';
+
+const stylesheets: Record<string, string> = {
+ 'feature/QueueTray.css':
+ '.queue-tray-thumb { border-radius: 4px; }\n.queue-tray-thumb img { width: 100%; }',
+ 'feature/Panel.module.css':
+ '.panel { padding: 8px; }\n.panel .title { color: red; }\n.panel :global(.ant-btn) { color: blue; }',
+};
+
+const options = {
+ adapters: [emotionStaticAdapter, stylexAdapter, cssModulesAdapter, globalCssAdapter],
+ layoutComponents: ['Flexbox'],
+ readStylesheet: (from: string, specifier: string) =>
+ stylesheets[`${from.split('/').slice(0, -1).join('/')}/${specifier.replace('./', '')}`],
+};
+
+const flagsById = (code: string, file = 'feature/A.tsx') =>
+ Object.fromEntries(extractFile(code, file, options).elements.map((e) => [e.id, e.flags]));
+
+describe('selector classification', () => {
+ it('flags an element whose slot styles a class owned by another component', () => {
+ const code = `import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({
+ muted: css\`
+ .control-label { color: gray; }
+ \`,
+ row: css\`
+ height: 40px;
+ &:hover { background: red; }
+ \`,
+}));
+export const Row = ({ muted }) => <Flexbox className={cx(styles.row, muted && styles.muted)} />;
+export const Plain = () => <div className={styles.row} />;
+`;
+ expect(flagsById(code)).toEqual({ 'Plain#0': [], 'Row#0': ['CROSS_COMPONENT'] });
+ });
+
+ it("flags an element whose class is the target of another element's cross-component rule", () => {
+ const code = `import { createStaticStyles, cx } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({
+ label: css\`color: black;\`,
+ muted: css\`.control-label { color: gray; }\`,
+}));
+const Label = () => <span className={cx(styles.label, 'control-label')} />;
+export const Row = ({ muted }) => <div className={cx(muted && styles.muted)}><Label /></div>;
+`;
+ expect(flagsById(code)).toEqual({
+ 'Label#0': ['CROSS_COMPONENT'],
+ 'Row#0': ['CROSS_COMPONENT'],
+ });
+ });
+
+ it('flags a descendant selector that reaches into a child type', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({
+ thumb: css\`
+ & img { width: 100%; }
+ \`,
+}));
+export const Thumb = () => <Image className={styles.thumb} />;
+`;
+ expect(flagsById(code)).toEqual({ 'Thumb#0': ['INNER_TARGET'] });
+ });
+
+ it('treats a literal className matched by an imported global stylesheet as a styled element', () => {
+ const code = `import './QueueTray.css';
+export const Tray = () => (
+ <div className="queue-tray">
+ <Image className="queue-tray-thumb" />
+ </div>
+);
+`;
+ const result = extractFile(code, 'feature/A.tsx', options);
+ expect(result.elements.map((e) => [e.id, e.tag, e.slots, e.flags])).toEqual([
+ ['Tray#0', 'Image', ['global.queue-tray-thumb'], ['INNER_TARGET']],
+ ]);
+ expect(result.prelude).toContain("import './QueueTray.css';");
+ });
+
+ it('reads a global className written as a braced string literal', () => {
+ const code = `import './QueueTray.css';
+export const Tray = () => <Image className={'queue-tray-thumb'} />;
+`;
+ expect(extractFile(code, 'feature/A.tsx', options).elements.map((e) => e.slots)).toEqual([
+ ['global.queue-tray-thumb'],
+ ]);
+ });
+
+ it('reads CSS module classes as owned slots and flags :global targets', () => {
+ const code = `import styles from './Panel.module.css';
+export const Panel = () => (
+ <div className={styles.panel}>
+ <span className={styles.title}>t</span>
+ </div>
+);
+`;
+ const result = extractFile(code, 'feature/A.tsx', options);
+ expect(result.styleSymbols).toEqual(['styles']);
+ expect(Object.fromEntries(result.elements.map((e) => [e.id, e.flags]))).toEqual({
+ 'Panel#0': ['CROSS_COMPONENT'],
+ 'Panel#1': [],
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/extract/selectors.ts b/packages/style-equivalence/src/extract/selectors.ts
new file mode 100644
index 00000000000..d8e26415027
--- /dev/null
+++ b/packages/style-equivalence/src/extract/selectors.ts
@@ -0,0 +1,95 @@
+import selectorParser from 'postcss-selector-parser';
+
+import type { StyleRule } from './types';
+
+export type SelectorFlag = 'CROSS_COMPONENT' | 'INNER_TARGET';
+
+interface Sibling {
+ prev: () => Sibling | undefined;
+ type: string;
+}
+
+interface Lineage {
+ parent?: { parent?: { type: string; value?: string } };
+}
+
+interface Analysis {
+ classes: Array<{ global: boolean; name: string }>;
+ innerType: boolean;
+}
+
+const analyze = (selector: string): Analysis | undefined => {
+ const result: Analysis = { classes: [], innerType: false };
+ try {
+ selectorParser((root) => {
+ root.walkClasses((node) => {
+ const grandparent = (node as unknown as Lineage).parent?.parent;
+ const global = grandparent?.type === 'pseudo' && grandparent.value === ':global';
+ result.classes.push({ global, name: node.value });
+ });
+ root.walkTags((node) => {
+ let cursor = (node as unknown as Sibling).prev();
+ while (cursor && cursor.type !== 'combinator') cursor = cursor.prev();
+ if (cursor) result.innerType = true;
+ });
+ }).processSync(selector);
+ } catch {
+ return undefined;
+ }
+ return result;
+};
+
+export type LocalClass = (name: string, slots: string[]) => boolean;
+
+export const classifyRules = (
+ rules: StyleRule[],
+ extraOwned: Record<string, string> = {},
+ isLocal: LocalClass = () => false,
+) => {
+ const flags = new Map<string, Set<SelectorFlag>>();
+ const add = (slot: string, flag: SelectorFlag) =>
+ flags.set(slot, (flags.get(slot) ?? new Set()).add(flag));
+ for (const rule of rules) {
+ const owned = { ...rule.owned, ...extraOwned };
+ const analysis = analyze(rule.selector);
+ if (!analysis) continue;
+ const ownedSlots = analysis.classes
+ .filter((item) => !item.global && owned[item.name])
+ .map((item) => owned[item.name]);
+ if (!ownedSlots.length) continue;
+ const foreign = analysis.classes.some(
+ (item) => item.global || (!owned[item.name] && !isLocal(item.name, ownedSlots)),
+ );
+ for (const slot of new Set(ownedSlots)) {
+ if (foreign) add(slot, 'CROSS_COMPONENT');
+ if (analysis.innerType) add(slot, 'INNER_TARGET');
+ }
+ }
+ return flags;
+};
+
+export const foreignClassNames = (
+ rules: StyleRule[],
+ extraOwned: Record<string, string> = {},
+ isLocal: LocalClass = () => false,
+) => {
+ const names = new Set<string>();
+ for (const rule of rules) {
+ const owned = { ...rule.owned, ...extraOwned };
+ const analysis = analyze(rule.selector);
+ const ownedSlots =
+ analysis?.classes
+ .filter((item) => !item.global && owned[item.name])
+ .map((item) => owned[item.name]) ?? [];
+ if (!ownedSlots.length) continue;
+ for (const item of analysis!.classes)
+ if (!item.global && !owned[item.name] && !isLocal(item.name, ownedSlots))
+ names.add(item.name);
+ }
+ return names;
+};
+
+export const classNamesIn = (selector: string) =>
+ (analyze(selector)?.classes ?? []).filter((item) => !item.global).map((item) => item.name);
+
+export const targetsInnerTag = (selector: string) => analyze(selector)?.innerType ?? true;
diff --git a/packages/style-equivalence/src/extract/tables.ts b/packages/style-equivalence/src/extract/tables.ts
new file mode 100644
index 00000000000..e91f69bc967
--- /dev/null
+++ b/packages/style-equivalence/src/extract/tables.ts
@@ -0,0 +1,79 @@
+import ts from 'typescript';
+
+const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) ||
+ ts.isAsExpression(node) ||
+ ts.isSatisfiesExpression(node) ||
+ ts.isTypeAssertionExpression(node)
+ ? unwrap(node.expression)
+ : node;
+
+const literalKeys = (initializer: ts.Expression | undefined) => {
+ const object = initializer && unwrap(initializer);
+ if (!object || !ts.isObjectLiteralExpression(object)) return undefined;
+ const keys = new Set<string>();
+ for (const property of object.properties) {
+ if (ts.isShorthandPropertyAssignment(property)) {
+ keys.add(property.name.text);
+ continue;
+ }
+ if (!ts.isPropertyAssignment(property)) return undefined;
+ const { name } = property;
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name) && !ts.isNumericLiteral(name))
+ return undefined;
+ keys.add(name.text);
+ }
+ return [...keys].sort();
+};
+
+const isWriteTarget = (access: ts.Expression) => {
+ let node: ts.Node = access;
+ while (ts.isParenthesizedExpression(node.parent)) node = node.parent;
+ const { parent } = node;
+ if (ts.isBinaryExpression(parent) && parent.left === node)
+ return (
+ parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
+ parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment
+ );
+ return (
+ ts.isDeleteExpression(parent) ||
+ ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&
+ [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(parent.operator))
+ );
+};
+
+const onlyRead = (ast: ts.SourceFile, name: string, declaration: ts.Identifier) => {
+ let read = true;
+ const visit = (node: ts.Node) => {
+ if (!read) return;
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration) {
+ const { parent } = node;
+ const access =
+ (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) &&
+ parent.expression === node;
+ const nameOnly =
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
+ (ts.isPropertyAssignment(parent) && parent.name === node) ||
+ ts.isTypeQueryNode(parent);
+ if (!nameOnly && (!access || isWriteTarget(parent))) read = false;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ return read;
+};
+
+export const collectTables = (ast: ts.SourceFile) => {
+ const tables: Record<string, string[]> = {};
+ for (const statement of ast.statements) {
+ if (!ts.isVariableStatement(statement)) continue;
+ if (!(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
+ for (const declaration of statement.declarationList.declarations) {
+ if (!ts.isIdentifier(declaration.name)) continue;
+ const keys = literalKeys(declaration.initializer);
+ if (keys && onlyRead(ast, declaration.name.text, declaration.name))
+ tables[declaration.name.text] = keys;
+ }
+ }
+ return tables;
+};
diff --git a/packages/style-equivalence/src/extract/topLevel.ts b/packages/style-equivalence/src/extract/topLevel.ts
new file mode 100644
index 00000000000..5b58746a963
--- /dev/null
+++ b/packages/style-equivalence/src/extract/topLevel.ts
@@ -0,0 +1,182 @@
+import ts from 'typescript';
+
+import { valueIdentifiers } from './identifiers';
+import { type ImportedClass, importedClassOf } from './importedClasses';
+import type { StyleAdapter, StylesheetBinding } from './types';
+
+const STYLESHEET = /\.css$/;
+
+export interface TopLevel {
+ importedClasses: Map<string, ImportedClass>;
+ importOf: Map<string, ts.ImportDeclaration>;
+ keptStatements: Set<ts.Statement>;
+ prelude: () => string;
+ require: (name: string) => boolean;
+ sideEffectCss: string[];
+ styleFactories: Map<string, ts.CallExpression>;
+ stylesheets: Array<{ binding: StylesheetBinding; source: string }>;
+ styleSymbols: Set<string>;
+}
+
+const importedFactory = (
+ code: string,
+ name: string,
+ adapters: StyleAdapter[],
+): ts.CallExpression | undefined => {
+ const sf = ts.createSourceFile(
+ 'module.tsx',
+ code,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const recognized = (node: ts.Expression | undefined) =>
+ node && ts.isCallExpression(node) && adapters.some((adapter) => adapter.recognizeFactory(node))
+ ? node
+ : undefined;
+ for (const statement of sf.statements) {
+ if (name === 'default' && ts.isExportAssignment(statement))
+ return recognized(statement.expression);
+ if (!ts.isVariableStatement(statement)) continue;
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === name)
+ return recognized(declaration.initializer);
+ }
+ return undefined;
+};
+
+export const collectTopLevel = (
+ ast: ts.SourceFile,
+ adapters: StyleAdapter[],
+ readModule?: (specifier: string) => string | undefined,
+): TopLevel => {
+ const importOf = new Map<string, ts.ImportDeclaration>();
+ const declarations = new Map<string, ts.Statement>();
+ const styleSymbols = new Set<string>();
+ const styleFactories = new Map<string, ts.CallExpression>();
+ const importedClasses = new Map<string, ImportedClass>();
+ const sideEffectCss: string[] = [];
+ const stylesheets: TopLevel['stylesheets'] = [];
+
+ for (const statement of ast.statements) {
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
+ const source = statement.moduleSpecifier.text;
+ const clause = statement.importClause;
+ for (const adapter of adapters) {
+ const binding = adapter.stylesheet?.(source, clause);
+ if (binding) {
+ stylesheets.push({ binding, source });
+ break;
+ }
+ }
+ if (!clause) {
+ if (STYLESHEET.test(source)) sideEffectCss.push(statement.getText(ast));
+ continue;
+ }
+ if (clause.isTypeOnly) continue;
+ if (clause.name) importOf.set(clause.name.text, statement);
+ const named = clause.namedBindings;
+ if (named && ts.isNamespaceImport(named)) importOf.set(named.name.text, statement);
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements)
+ if (!element.isTypeOnly) importOf.set(element.name.text, statement);
+ for (const adapter of adapters)
+ for (const symbol of adapter.importedStyleSymbols?.(source, clause) ?? [])
+ styleSymbols.add(symbol);
+ const module = readModule && !STYLESHEET.test(source) ? readModule(source) : undefined;
+ if (module) {
+ const names: Array<[string, string]> = [];
+ if (clause.name) names.push([clause.name.text, 'default']);
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements)
+ if (!element.isTypeOnly)
+ names.push([element.name.text, (element.propertyName ?? element.name).text]);
+ for (const [local, imported] of names) {
+ const factory = importedFactory(module, imported, adapters);
+ if (factory) {
+ styleSymbols.add(local);
+ styleFactories.set(local, factory);
+ continue;
+ }
+ const derived = importedClassOf(module, imported, local, adapters);
+ if (derived) importedClasses.set(local, derived);
+ }
+ }
+ continue;
+ }
+ if (ts.isVariableStatement(statement))
+ for (const declaration of statement.declarationList.declarations) {
+ if (!ts.isIdentifier(declaration.name)) continue;
+ declarations.set(declaration.name.text, statement);
+ const initializer = declaration.initializer;
+ if (
+ initializer &&
+ ts.isCallExpression(initializer) &&
+ adapters.some((adapter) => adapter.recognizeFactory(initializer))
+ ) {
+ styleSymbols.add(declaration.name.text);
+ styleFactories.set(declaration.name.text, initializer);
+ }
+ }
+ if (ts.isFunctionDeclaration(statement) && statement.name)
+ declarations.set(statement.name.text, statement);
+ }
+
+ const keptStatements = new Set<ts.Statement>();
+ const keptImports = new Map<ts.ImportDeclaration, Set<string>>();
+ const require = (name: string): boolean => {
+ const imported = importOf.get(name);
+ if (imported) {
+ keptImports.set(imported, (keptImports.get(imported) ?? new Set()).add(name));
+ return true;
+ }
+ const statement = declarations.get(name);
+ if (!statement) return false;
+ if (keptStatements.has(statement)) return true;
+ keptStatements.add(statement);
+ for (const dependency of valueIdentifiers(statement, { includeTags: true }))
+ require(dependency);
+ return true;
+ };
+ for (const symbol of styleSymbols) require(symbol);
+
+ const prelude = () => {
+ const lines = [...sideEffectCss];
+ for (const statement of ast.statements) {
+ if (ts.isImportDeclaration(statement)) {
+ const names = keptImports.get(statement);
+ if (!names) continue;
+ const clause = statement.importClause!;
+ const parts: string[] = [];
+ if (clause.name && names.has(clause.name.text)) parts.push(clause.name.text);
+ const named = clause.namedBindings;
+ if (named && ts.isNamespaceImport(named) && names.has(named.name.text))
+ parts.push(`* as ${named.name.text}`);
+ if (named && ts.isNamedImports(named)) {
+ const kept = named.elements
+ .filter((element) => !element.isTypeOnly && names.has(element.name.text))
+ .map((element) => element.getText(ast));
+ if (kept.length) parts.push(`{ ${kept.join(', ')} }`);
+ }
+ if (parts.length)
+ lines.push(`import ${parts.join(', ')} from ${statement.moduleSpecifier.getText(ast)};`);
+ continue;
+ }
+ if (keptStatements.has(statement))
+ lines.push(statement.getText(ast).replace(/^export\s+(?:default\s+)?/, ''));
+ }
+ return lines.join('\n');
+ };
+
+ return {
+ importedClasses,
+ importOf,
+ keptStatements,
+ prelude,
+ require,
+ sideEffectCss,
+ styleFactories,
+ styleSymbols,
+ stylesheets,
+ };
+};
diff --git a/packages/style-equivalence/src/extract/types.ts b/packages/style-equivalence/src/extract/types.ts
new file mode 100644
index 00000000000..319bc37d368
--- /dev/null
+++ b/packages/style-equivalence/src/extract/types.ts
@@ -0,0 +1,107 @@
+import type ts from 'typescript';
+
+import type { ForwardResolution } from './forward';
+
+export type LiteralValue = string | number | boolean | { [key: string]: LiteralValue };
+
+export type VariableKind = 'boolean' | 'call' | 'member' | 'unknown';
+
+export interface VariableUse {
+ kind: VariableKind;
+ name: string;
+}
+
+export interface StyleBinding {
+ expansion?: string;
+ expr: string;
+ prop: string;
+ spread: boolean;
+}
+
+export interface StyleElement {
+ aliases?: Record<string, string>;
+ attributes?: Record<string, string>;
+ bindings: StyleBinding[];
+ children?: string[];
+ derived?: Record<string, string>;
+ flags: string[];
+ foreignSpread?: boolean;
+ forwardedParam?: string;
+ forwards?: ForwardResolution[];
+ guards?: string[];
+ iconElement?: boolean | string;
+ id: string;
+ inlineStyle?: string;
+ literalProps: Record<string, LiteralValue>;
+ owner: string;
+ parent?: string;
+ real?: boolean;
+ runtimeStyle?: string;
+ slots: string[];
+ spreadAfterStyle?: boolean;
+ styleExpr?: string;
+ subtreeComponents?: string[];
+ subtreeTags?: Record<string, number>;
+ tag: string;
+ variables: VariableUse[];
+}
+
+export interface StyleRule {
+ conditions: string[];
+ declarations?: string[];
+ interpolations?: string[];
+ interpolationValues?: Array<string | null>;
+ owned: Record<string, string>;
+ selector: string;
+ slot?: string;
+ stylesheet?: string;
+}
+
+export type StylesheetBinding = { kind: 'global' } | { kind: 'module'; symbol: string };
+
+export interface FileExtraction {
+ elements: StyleElement[];
+ file: string;
+ gaps: string[];
+ globalRules?: StyleRule[];
+ literalClasses?: string[];
+ outsideReferences: string[];
+ plain?: StyleElement[];
+ prelude: string;
+ rules: StyleRule[];
+ slotConditions?: Record<string, string[]>;
+ slotProperties?: Record<string, string[]>;
+ styleSymbols: string[];
+ tables?: Record<string, string[]>;
+ unsupported?: Record<string, string[]>;
+}
+
+export interface StyleAdapter {
+ conditionsOf?: (symbol: string, factory: ts.CallExpression) => Record<string, string[]>;
+ importedStyleSymbols?: (source: string, clause: ts.ImportClause) => string[];
+ markerIdentifiers: string[];
+ name: string;
+ propertiesOf?: (symbol: string, factory: ts.CallExpression) => Record<string, string[]>;
+ recognizeFactory: (call: ts.CallExpression) => boolean;
+ rulesOf?: (symbol: string, factory: ts.CallExpression) => StyleRule[];
+ stylesheet?: (
+ source: string,
+ clause: ts.ImportClause | undefined,
+ ) => StylesheetBinding | undefined;
+}
+
+export interface RealComponent {
+ leaf?: boolean;
+ sample?: (content: string) => string;
+ source: string;
+ tag?: { default: string; prop: string };
+}
+
+export interface ExtractOptions {
+ adapters: StyleAdapter[];
+ layoutComponents: string[];
+ readBaseModule?: (fromFile: string, specifier: string) => string | undefined;
+ readModule?: (fromFile: string, specifier: string) => string | undefined;
+ readStylesheet?: (fromFile: string, specifier: string) => string | undefined;
+ realComponents?: Record<string, RealComponent>;
+}
diff --git a/packages/style-equivalence/src/extract/unsupported.ts b/packages/style-equivalence/src/extract/unsupported.ts
new file mode 100644
index 00000000000..67ab34c0e06
--- /dev/null
+++ b/packages/style-equivalence/src/extract/unsupported.ts
@@ -0,0 +1,28 @@
+import ts from 'typescript';
+
+const UNSUPPORTED_STYLEX_KEYS = new Set(['all']);
+
+export const stylexUnsupported = (factories: Map<string, ts.CallExpression>) => {
+ const found: Record<string, string[]> = {};
+ for (const [symbol, factory] of factories) {
+ const callee = factory.expression;
+ if (!ts.isPropertyAccessExpression(callee) || callee.getText() !== 'stylex.create') continue;
+ const [argument] = factory.arguments;
+ if (!argument || !ts.isObjectLiteralExpression(argument)) continue;
+ for (const slot of argument.properties) {
+ if (!ts.isPropertyAssignment(slot)) continue;
+ const keys = new Set<string>();
+ const visit = (node: ts.Node) => {
+ if (ts.isPropertyAssignment(node)) {
+ const key =
+ ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : '';
+ if (UNSUPPORTED_STYLEX_KEYS.has(key)) keys.add(key);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(slot.initializer);
+ if (keys.size) found[`${symbol}.${slot.name.getText()}`] = [...keys].sort();
+ }
+ }
+ return found;
+};
diff --git a/packages/style-equivalence/src/generate/forward.ts b/packages/style-equivalence/src/generate/forward.ts
new file mode 100644
index 00000000000..55b5ea8d4aa
--- /dev/null
+++ b/packages/style-equivalence/src/generate/forward.ts
@@ -0,0 +1,40 @@
+import type { ForwardApplication, ForwardElement } from '../extract/forward';
+import type { PlanCase, Side } from '../plan/planFile';
+import { keepLiteral, renderLiteral, SAMPLE_TEXT, VOID_TAGS } from './literal';
+
+const STYLEX = '__stylex';
+
+const tagOf = (element: ForwardElement) =>
+ element.tagImport ? `__forward_${element.tagImport.imported}` : element.tag;
+
+export const applicationOf = (application: ForwardApplication, expr: string) => {
+ if (application === 'className') return `className={${expr}}`;
+ if (application === 'spread') return `{...${STYLEX}.props(${expr})}`;
+ return `className={${STYLEX}.props(${expr}).className}`;
+};
+
+export const renderForward = (id: string, element: ForwardElement, application?: string) => {
+ const tag = tagOf(element);
+ const attributes = [`data-synthetic-element=${JSON.stringify(id)}`];
+ for (const [name, value] of Object.entries(element.attributes))
+ if (keepLiteral(name, false)) attributes.push(renderLiteral(name, value));
+ if (application) attributes.push(application);
+ const open = `<${tag} ${attributes.join(' ')}`;
+ return VOID_TAGS.has(tag) ? `${open} />` : `${open}>{${JSON.stringify(SAMPLE_TEXT)}}</${tag}>`;
+};
+
+export const forwardImports = (cases: PlanCase[], side: Side) => {
+ const lines = new Set<string>();
+ for (const entry of cases) {
+ const target = entry.forward?.[side];
+ if (!target) continue;
+ const imported = target.tagImport;
+ if (imported && imported.imported !== 'default' && imported.imported !== '*')
+ lines.add(
+ `import { ${imported.imported} as ${tagOf(target)} } from ${JSON.stringify(imported.source)};`,
+ );
+ if (side === 'head' && entry.forward!.application !== 'className')
+ lines.add(`import * as ${STYLEX} from '@stylexjs/stylex';`);
+ }
+ return [...lines];
+};
diff --git a/packages/style-equivalence/src/generate/generate.test.ts b/packages/style-equivalence/src/generate/generate.test.ts
new file mode 100644
index 00000000000..61982996a47
--- /dev/null
+++ b/packages/style-equivalence/src/generate/generate.test.ts
@@ -0,0 +1,422 @@
+import { mkdir, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { createElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { afterAll, describe, expect, it } from 'vitest';
+
+import type { FileExtraction, StyleElement } from '../extract';
+import type { FilePlan } from '../plan/planFile';
+import { generateHost } from './host';
+import { CaseList, type CaseModules, INNER_BASELINE, readSelection } from './hostRuntime';
+import { generateModule } from './module';
+
+const tmp = path.join(import.meta.dirname, '.generated-test');
+afterAll(() => rm(tmp, { force: true, recursive: true }));
+
+const prelude = `const cx = (...names) => names.filter(Boolean).join(' ');
+const Flexbox = ({ className, children }) => <div data-flex="" className={className}>{children}</div>;
+const styles = { a: 'a', b: 'b', c: 'c', item: 'item', itemDragging: 'itemDragging' };
+const PILL = { on: 'a' };
+const TONE = { on: 'b', off: 'c' };`;
+
+const element = (
+ id: string,
+ tag: string,
+ expr: string,
+ extra: Partial<StyleElement> = {},
+): StyleElement => ({
+ bindings: [{ expr, prop: 'className', spread: false }],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: id.split('#')[0],
+ slots: [...new Set(expr.match(/\bstyles\.\w+/g) ?? [])].sort(),
+ tag,
+ variables: [],
+ ...extra,
+});
+
+const extraction: FileExtraction = {
+ elements: [
+ element('A#0', 'Flexbox', 'isDragging ? cx(styles.item, styles.itemDragging) : styles.item', {
+ variables: [{ kind: 'boolean', name: 'isDragging' }],
+ }),
+ element(
+ 'A#1',
+ 'span',
+ 'cx(styles.a, isActive() && styles.b, item.done && styles.c, size && styles.a)',
+ {
+ parent: 'A#0',
+ variables: [
+ { kind: 'call', name: 'isActive' },
+ { kind: 'member', name: 'item' },
+ { kind: 'unknown', name: 'size' },
+ ],
+ },
+ ),
+ element('C#0', 'span', 'cx(PILL[attrs.kind] ?? styles.b, attrs.meta.color && styles.c)', {
+ variables: [{ kind: 'unknown', name: 'attrs' }],
+ }),
+ element(
+ 'K#0',
+ 'span',
+ "cx(styles.a, state.kind === 'x' ? styles.b : state.kind !== 'y' && styles.c)",
+ {
+ variables: [{ kind: 'unknown', name: 'state' }],
+ },
+ ),
+ element('T#0', 'span', 'cx(styles.a, TONE[tone])', {
+ variables: [{ kind: 'unknown', name: 'tone' }],
+ }),
+ element('D#0', 'details', 'styles.a', { children: ['D#0/0'] }),
+ element('I#0', 'div', 'styles.a'),
+ element('I#1', 'span', 'styles.b', { parent: 'I#0' }),
+ element('P#0', 'div', 'styles.a', { runtimeStyle: 'laneStyle' }),
+ element('P#1', 'span', 'styles.b', { parent: 'P#0' }),
+ element('K#1', 'span', 'cx(styles.a,', {
+ variables: [{ kind: 'unknown', name: 'state' }],
+ }),
+ element('B#0', 'SortableList.Item', 'styles.a', {
+ bindings: [
+ { expr: 'styles.a', prop: 'className', spread: false },
+ { expr: 'styles.b', prop: 'itemClassName', spread: false },
+ ],
+ literalProps: { 'data-id': 'x', 'onClick': 'y', 'title': 'hidden' },
+ }),
+ ],
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ plain: [
+ {
+ ...element('D#0/0', 'summary', ''),
+ bindings: [],
+ literalProps: { title: 'raw' },
+ parent: 'D#0',
+ },
+ ],
+ prelude,
+ rules: [],
+ styleSymbols: ['styles'],
+};
+
+const plan: FilePlan = {
+ cases: [
+ {
+ combos: [],
+ elementIds: { base: 'A#0', head: 'A#0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|A#0',
+ variables: [{ kinds: { base: 'boolean', head: 'boolean' }, name: 'isDragging' }],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'A#1', head: 'A#1' },
+ file: 'a.tsx',
+ flags: ['VARIABLE_UNMODELED'],
+ key: 'a.tsx|A#1',
+ variables: [
+ { kinds: { base: 'call', head: 'call' }, name: 'isActive' },
+ { kinds: { base: 'boolean', head: 'boolean' }, name: 'isDragging' },
+ { kinds: { base: 'member', head: 'member' }, name: 'item' },
+ ],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'C#0', head: 'C#0' },
+ file: 'a.tsx',
+ flags: ['VARIABLE_UNMODELED'],
+ key: 'a.tsx|C#0',
+ variables: [],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'K#0', head: 'K#0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|K#0',
+ knobs: ["state.kind === 'x'", "state.kind !== 'y'"],
+ variables: [],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'T#0', head: 'T#0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|T#0',
+ variables: [
+ {
+ kinds: { base: 'unknown', head: 'unknown' },
+ name: 'tone',
+ values: ['off', 'on', '__style_equivalence_absent__'],
+ },
+ ],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'I#1', head: 'I#1' },
+ file: 'a.tsx',
+ flags: [],
+ inner: {
+ 0: [{ attributes: { role: 'tablist' }, children: [], tag: 'div' }],
+ 1: [
+ { attributes: {}, children: [], tag: 'h1' },
+ { attributes: { className: 'x' }, children: [], tag: 'img' },
+ ],
+ },
+ key: 'a.tsx|I#1',
+ variables: [],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'D#0/0', head: 'D#0/0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|D#0/0',
+ variables: [],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'P#1', head: 'P#1' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|P#1',
+ variables: [{ kinds: { head: 'unknown' }, name: 'laneStyle', probe: true }],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'K#1', head: 'K#1' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|K#1',
+ knobs: ["state.kind === 'x'"],
+ variables: [],
+ },
+ {
+ combos: [],
+ elementIds: { base: 'B#0', head: 'B#0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|B#0',
+ variables: [],
+ },
+ ],
+ file: 'a.tsx',
+ gaps: [],
+ unpaired: [{ elementId: 'A#1', side: 'base' }],
+};
+
+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: ['Flexbox'] }),
+ );
+ return (await import(file)) as Required<Pick<CaseModules[string], 'cases' | 'unpaired'>>;
+};
+
+const render = (node: unknown) => renderToStaticMarkup(node as never);
+
+describe('generateModule', () => {
+ it('applies the combo to the composition expression', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|A#0']({ isDragging: true }))).toBe(
+ '<div data-flex="" class="item itemDragging">Ag 文本 Text</div>',
+ );
+ expect(render(cases['a.tsx|A#0']({ isDragging: false }))).toBe(
+ '<div data-flex="" class="item">Ag 文本 Text</div>',
+ );
+ });
+
+ it('models call and member conditions, binds unknown names to undefined and nests the chain', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|A#1']({ isActive: true, isDragging: false, item: true }))).toBe(
+ '<div data-flex="" class="item"><span data-synthetic-element="A#1" class="a b c">Ag 文本 Text</span></div>',
+ );
+ expect(
+ render(cases['a.tsx|A#1']({ isActive: false, isDragging: false, item: false })),
+ ).toContain('class="a"');
+ });
+
+ it('renders an unmodeled value that is read through members and indexes instead of throwing', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|C#0']({}))).toContain('class="b c"');
+ });
+
+ it('binds each condition knob so every branch renders', async () => {
+ const { cases } = await load();
+ const knob = (x: boolean, y: boolean) =>
+ render(cases['a.tsx|K#0']({ "state.kind !== 'y'": y, "state.kind === 'x'": x }));
+ expect(knob(true, false)).toContain('class="a b"');
+ expect(knob(false, true)).toContain('class="a c"');
+ expect(knob(false, false)).toContain('class="a"');
+ });
+
+ it('renders a table lookup with each key of its domain', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|T#0']({ tone: 'on' }))).toContain('class="a b"');
+ expect(render(cases['a.tsx|T#0']({ tone: 'off' }))).toContain('class="a c"');
+ expect(render(cases['a.tsx|T#0']({ tone: '__style_equivalence_absent__' }))).toContain(
+ 'class="a"',
+ );
+ });
+
+ it('passes a probe style to the runtime style of the chain only when the combo turns it on', async () => {
+ const { cases } = await load();
+ const on = render(cases['a.tsx|P#1']({ laneStyle: true }));
+ expect(on).toContain(
+ '<div data-synthetic-element="P#0" class="a" style="--style-equivalence-probe:laneStyle;tab-size:7">',
+ );
+ expect(render(cases['a.tsx|P#1']({ laneStyle: false }))).not.toContain('style=');
+ });
+
+ it('renders a plain child inside its styled parent', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|D#0/0']({}))).toBe(
+ '<details data-synthetic-element="D#0" class="a"><summary data-synthetic-element="D#0/0" title="raw">Ag 文本 Text</summary></details>',
+ );
+ });
+
+ it('renders the inner targets a moved stylesheet selects inside each chain element', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|I#1']({}))).toBe(
+ '<div data-synthetic-element="I#0" class="a"><span data-synthetic-element="I#1" class="b">Ag 文本 Text<h1 data-synthetic-inner="">Ag 文本 Text</h1><img data-synthetic-inner="" class="x"/></span><div data-synthetic-inner="" role="tablist">Ag 文本 Text</div></div>',
+ );
+ });
+
+ it('fails a knob case it cannot bind instead of rendering it unbound', async () => {
+ const { cases } = await load();
+ expect(() => cases['a.tsx|K#1']({})).toThrow('KNOB_UNBOUND');
+ });
+
+ it('renders an element that exists on one side only with every condition off', async () => {
+ const { unpaired } = await load();
+ expect(Object.keys(unpaired)).toEqual(['a.tsx|unpaired:base:A#1']);
+ expect(render(unpaired['a.tsx|unpaired:base:A#1']())).toBe(
+ '<div data-flex="" class="item"><span data-synthetic-element="A#1" class="a">Ag 文本 Text</span></div>',
+ );
+ });
+
+ it('substitutes non-layout components with a div and renders neutral props as children', async () => {
+ const { cases } = await load();
+ expect(render(cases['a.tsx|B#0']({}))).toBe(
+ '<div data-synthetic-element="B#0" data-id="x" class="a">Ag 文本 Text<div data-synthetic-neutral="itemClassName" class="b">Ag 文本 Text</div></div>',
+ );
+ });
+});
+
+describe('CaseList', () => {
+ it('renders every combo of every case, or only the selected one', async () => {
+ const mod = await load();
+ const fullPlan = [
+ {
+ ...plan,
+ cases: plan.cases
+ .filter(
+ (entry) =>
+ !['a.tsx|D#0/0', 'a.tsx|I#1', 'a.tsx|K#1', 'a.tsx|P#1', 'a.tsx|T#0'].includes(
+ entry.key,
+ ),
+ )
+ .map((entry) => ({
+ ...entry,
+ combos:
+ entry.key === 'a.tsx|A#0' ? [{ isDragging: false }, { isDragging: true }] : [{}],
+ })),
+ },
+ ];
+ const all = render(createElement(CaseList, { modules: { 'a.tsx': mod }, plan: fullPlan }));
+ expect(all.match(/data-case=/g)).toHaveLength(6);
+ expect(all).toContain(`<style>${INNER_BASELINE}</style>`);
+ expect(all).toContain('data-case="a.tsx|A#0|1"');
+ const one = render(
+ createElement(CaseList, {
+ modules: { 'a.tsx': mod },
+ plan: fullPlan,
+ selection: { caseKey: 'a.tsx|A#0', combo: 1 },
+ }),
+ );
+ expect(one.match(/data-case=/g)).toHaveLength(1);
+ expect(one).toContain('class="item itemDragging"');
+ });
+
+ it('renders a one-sided element only when it is selected', async () => {
+ const mod = await load();
+ const all = render(createElement(CaseList, { modules: { 'a.tsx': mod }, plan: [plan] }));
+ expect(all).not.toContain('unpaired');
+ const one = render(
+ createElement(CaseList, {
+ modules: { 'a.tsx': mod },
+ plan: [plan],
+ selection: { caseKey: 'a.tsx|unpaired:base:A#1', combo: 0 },
+ }),
+ );
+ expect(one.match(/data-case="[^"]*"/g)).toEqual(['data-case="a.tsx|unpaired:base:A#1|0"']);
+ expect(one).toContain('<span data-synthetic-element="A#1" class="a">');
+ });
+
+ it('renders only the cases named in the cases query parameter', async () => {
+ const mod = await load();
+ const fullPlan = [
+ {
+ ...plan,
+ cases: plan.cases
+ .filter(
+ (entry) =>
+ !['a.tsx|D#0/0', 'a.tsx|I#1', 'a.tsx|K#1', 'a.tsx|P#1', 'a.tsx|T#0'].includes(
+ entry.key,
+ ),
+ )
+ .map((entry) => ({
+ ...entry,
+ combos:
+ entry.key === 'a.tsx|A#0' ? [{ isDragging: false }, { isDragging: true }] : [{}],
+ })),
+ },
+ ];
+ const selection = readSelection(`?cases=${encodeURIComponent(JSON.stringify(['a.tsx|A#0']))}`);
+ const html = render(
+ createElement(CaseList, { modules: { 'a.tsx': mod }, plan: fullPlan, selection }),
+ );
+ expect(html.match(/data-case="[^"]*"/g)).toEqual([
+ 'data-case="a.tsx|A#0|0"',
+ 'data-case="a.tsx|A#0|1"',
+ ]);
+ });
+
+ it('reads the selected cases from the URL fragment, which never reaches the server', () => {
+ expect(
+ readSelection('?theme=dark', `#cases=${encodeURIComponent(JSON.stringify(['a.tsx|A#0']))}`),
+ ).toEqual({ caseKeys: ['a.tsx|A#0'] });
+ });
+
+ it('renders the cases of a module that failed to load as errors', () => {
+ const html = render(
+ createElement(CaseList, {
+ modules: { 'a.tsx': { cases: {}, error: 'MODULE_LOAD_FAILED: boom' } },
+ plan: [{ ...plan, cases: plan.cases.map((entry) => ({ ...entry, combos: [{}] })) }],
+ }),
+ );
+ expect(html).toContain('data-synthetic-error="MODULE_LOAD_FAILED: boom"');
+ });
+});
+
+describe('generateHost', () => {
+ it('loads each module on its own so one load-time throw does not stop the host', () => {
+ const code = generateHost({
+ hostWrapper: '/host.tsx',
+ modules: [
+ { file: 'a.tsx', specifier: './a.tsx' },
+ { file: 'b.tsx', specifier: './b.tsx' },
+ ],
+ runtime: '/runtime.tsx',
+ themeAttribute: 'data-theme',
+ });
+ expect(code).not.toMatch(/import \* as/);
+ expect(code).toContain('import("./a.tsx")');
+ expect(code).toContain('MODULE_LOAD_FAILED');
+ });
+});
diff --git a/packages/style-equivalence/src/generate/host.ts b/packages/style-equivalence/src/generate/host.ts
new file mode 100644
index 00000000000..1eb68e02d6b
--- /dev/null
+++ b/packages/style-equivalence/src/generate/host.ts
@@ -0,0 +1,40 @@
+import type { FilePlan } from '../plan/planFile';
+
+export const HOST_HTML =
+ '<!doctype html><html><head><meta charset="utf-8"></head><body><div id="app"></div><script type="module" src="./entry.tsx"></script></body></html>';
+
+export interface HostOptions {
+ hostWrapper: string;
+ modules: Array<{ file: string; specifier: string }>;
+ runtime: string;
+ themeAttribute: string;
+}
+
+export const generateHost = ({ hostWrapper, modules, runtime, themeAttribute }: HostOptions) => `
+import { Host } from ${JSON.stringify(hostWrapper)};
+import { createRoot } from 'react-dom/client';
+import { HostApp } from ${JSON.stringify(runtime)};
+import plan from './plan.json';
+
+const loaders: Array<[string, () => Promise<unknown>]> = [
+${modules.map((entry) => ` [${JSON.stringify(entry.file)}, () => import(${JSON.stringify(entry.specifier)})],`).join('\n')}
+];
+const modules: Record<string, any> = {};
+for (const [file, load] of loaders) {
+ try {
+ modules[file] = await load();
+ } catch (error) {
+ modules[file] = { cases: {}, error: 'MODULE_LOAD_FAILED: ' + (error instanceof Error ? error.message : String(error)) };
+ }
+}
+const params = new URLSearchParams(location.search);
+const theme = params.get('theme');
+if (theme) document.documentElement.setAttribute(${JSON.stringify(themeAttribute)}, theme);
+if (params.get('dir')) document.documentElement.setAttribute('dir', params.get('dir')!);
+document.body.style.margin = '0';
+createRoot(document.getElementById('app')!).render(
+ <HostApp Host={Host} modules={modules} plan={plan} onReady={() => document.getElementById('app')!.setAttribute('data-synthetic-ready', 'true')} />,
+);
+`;
+
+export type HostPlan = FilePlan[];
diff --git a/packages/style-equivalence/src/generate/hostRuntime.tsx b/packages/style-equivalence/src/generate/hostRuntime.tsx
new file mode 100644
index 00000000000..5be726c88b7
--- /dev/null
+++ b/packages/style-equivalence/src/generate/hostRuntime.tsx
@@ -0,0 +1,150 @@
+import { Component, type ComponentType, type ReactNode } from 'react';
+
+import type { FilePlan } from '../plan/planFile';
+
+type CaseRender = (combo: Record<string, boolean | string>) => ReactNode;
+export type CaseModules = Record<
+ string,
+ { cases: Record<string, CaseRender>; error?: string; unpaired?: Record<string, () => ReactNode> }
+>;
+
+export type CaseSelection = { caseKey: string; combo: number } | { caseKeys: string[] };
+
+const isSelected = (selection: CaseSelection | undefined, key: string, combo: number) =>
+ !selection ||
+ ('caseKeys' in selection
+ ? selection.caseKeys.includes(key)
+ : selection.caseKey === key && selection.combo === combo);
+
+class Boundary extends Component<{ children: ReactNode }, { error?: string }> {
+ state: { error?: string } = {};
+
+ static getDerivedStateFromError(error: unknown) {
+ return { error: error instanceof Error ? error.message : String(error) };
+ }
+
+ render() {
+ return this.state.error ? <div data-synthetic-error={this.state.error} /> : this.props.children;
+ }
+}
+
+const CaseView = ({
+ combo,
+ error,
+ render,
+}: {
+ combo: Record<string, boolean | string>;
+ error?: string;
+ render?: CaseRender;
+}) =>
+ error ? (
+ <div data-synthetic-error={error} />
+ ) : render ? (
+ render(combo)
+ ) : (
+ <div data-synthetic-error="CASE_RENDER_MISSING" />
+ );
+
+export const SECTION_WIDTH = 360;
+
+export const INNER_BASELINE = ':where([data-synthetic-inner]){width:fit-content}';
+
+const Section = ({ caseKey, children }: { caseKey: string; children: ReactNode }) => (
+ <section
+ data-case={caseKey}
+ style={{ boxSizing: 'border-box', padding: 8, position: 'relative', width: SECTION_WIDTH }}
+ >
+ <Boundary>{children}</Boundary>
+ </section>
+);
+
+const UnpairedView = ({ modules, selection }: { modules: CaseModules; selection: string }) => {
+ const file = selection.slice(0, selection.indexOf('|unpaired:'));
+ const render = modules[file]?.unpaired?.[selection];
+ return (
+ <Section caseKey={`${selection}|0`}>
+ {modules[file]?.error ? (
+ <div data-synthetic-error={modules[file].error} />
+ ) : render ? (
+ render()
+ ) : (
+ <div data-synthetic-error="CASE_RENDER_MISSING" />
+ )}
+ </Section>
+ );
+};
+
+export const CaseList = ({
+ modules,
+ plan,
+ selection,
+}: {
+ modules: CaseModules;
+ plan: FilePlan[];
+ selection?: CaseSelection;
+}) => (
+ <main data-synthetic-cases="">
+ <style>{INNER_BASELINE}</style>
+ {selection && 'caseKey' in selection && selection.caseKey.includes('|unpaired:') ? (
+ <UnpairedView modules={modules} selection={selection.caseKey} />
+ ) : (
+ plan.flatMap((file) =>
+ file.cases.flatMap((entry) =>
+ entry.combos.map((combo, index) => {
+ if (!isSelected(selection, entry.key, index)) return null;
+ const key = `${entry.key}|${index}`;
+ return (
+ <Section caseKey={key} key={key}>
+ <CaseView
+ combo={combo}
+ error={modules[file.file]?.error}
+ render={modules[file.file]?.cases[entry.key]}
+ />
+ </Section>
+ );
+ }),
+ ),
+ )
+ )}
+ </main>
+);
+
+export const readSelection = (search: string, hash = ''): CaseSelection | undefined => {
+ const params = new URLSearchParams(search);
+ const caseKeys = new URLSearchParams(hash.replace(/^#/, '')).get('cases') ?? params.get('cases');
+ if (caseKeys) return { caseKeys: JSON.parse(caseKeys) as string[] };
+ const caseKey = params.get('case');
+ if (!caseKey) return undefined;
+ return { caseKey, combo: Number(params.get('combo') ?? 0) };
+};
+
+export const HostApp = ({
+ Host,
+ modules,
+ onReady,
+ plan,
+}: {
+ Host: ComponentType<{ children: ReactNode }>;
+ modules: CaseModules;
+ onReady: () => void;
+ plan: FilePlan[];
+}) => (
+ <Host>
+ <CaseList
+ modules={modules}
+ plan={plan}
+ selection={readSelection(location.search, location.hash)}
+ />
+ <Ready onReady={onReady} />
+ </Host>
+);
+
+class Ready extends Component<{ onReady: () => void }> {
+ componentDidMount() {
+ this.props.onReady();
+ }
+
+ render() {
+ return null;
+ }
+}
diff --git a/packages/style-equivalence/src/generate/iconProp.test.ts b/packages/style-equivalence/src/generate/iconProp.test.ts
new file mode 100644
index 00000000000..c70a0883a1d
--- /dev/null
+++ b/packages/style-equivalence/src/generate/iconProp.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { extractFile } from '../extract/index';
+import { planFile } from '../plan/planFile';
+import { generateModule } from './module';
+
+const options = { adapters: [emotionStaticAdapter], layoutComponents: [] };
+
+const source = `import { createStaticStyles, Icon, Tag } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ tag: css\`
+ > :first-child {
+ flex-shrink: 0;
+ }
+ \`,
+ label: css\`color: red;\`,
+}));
+
+export const Card = () => (
+ <Tag className={styles.tag} icon={<Icon icon={FolderIcon} />}>
+ <span className={styles.label} />
+ </Tag>
+);
+`;
+
+describe('a stand-in component that receives an icon element', () => {
+ it('renders a placeholder in front of its children so first-child rules land on the icon', () => {
+ const extraction = extractFile(source, 'a.tsx', options);
+ expect(extraction.elements[0].iconElement).toBe(true);
+ const plan = planFile('a.tsx', extraction, extraction, { layoutComponents: [] });
+ const module = generateModule(extraction, plan, 'base', { layoutComponents: [] });
+ const render = module.split('\n').find((line) => line.startsWith('"a.tsx|Card#1"'));
+ expect(render).toMatch(/data-synthetic-icon=""><\/span><span data-synthetic-element="Card#1"/);
+ });
+
+ it('gives the placeholder the classes of a styled icon element', () => {
+ const head = source.replace(
+ 'icon={<Icon icon={FolderIcon} />}',
+ 'icon={<Icon className={styles.label} icon={FolderIcon} />}',
+ );
+ const extraction = extractFile(head, 'a.tsx', options);
+ const tag = extraction.elements.find((element) => element.tag === 'Tag');
+ expect(typeof tag?.iconElement).toBe('string');
+ const plan = planFile('a.tsx', extraction, extraction, { layoutComponents: [] });
+ const module = generateModule(extraction, plan, 'base', { layoutComponents: [] });
+ const render = module.split('\n').find((line) => line.startsWith('"a.tsx|Card#0"'));
+ expect(render).toContain('<span data-synthetic-icon="" className={styles.label}></span>');
+ });
+});
diff --git a/packages/style-equivalence/src/generate/inner.ts b/packages/style-equivalence/src/generate/inner.ts
new file mode 100644
index 00000000000..cf92f8af678
--- /dev/null
+++ b/packages/style-equivalence/src/generate/inner.ts
@@ -0,0 +1,15 @@
+import type { InnerNode } from '../plan/inner';
+
+const VOID_TAGS = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'source', 'wbr']);
+
+export const innerMarkup = (nodes: InnerNode[] | undefined, text: string): string =>
+ (nodes ?? [])
+ .map((node) => {
+ const open = `<${node.tag} data-synthetic-inner="" {...${JSON.stringify(node.attributes)}}`;
+ if (VOID_TAGS.has(node.tag)) return `${open} />`;
+ const content = node.children.length
+ ? innerMarkup(node.children, text)
+ : `{${JSON.stringify(text)}}`;
+ return `${open}>${content}</${node.tag}>`;
+ })
+ .join('');
diff --git a/packages/style-equivalence/src/generate/literal.ts b/packages/style-equivalence/src/generate/literal.ts
new file mode 100644
index 00000000000..73f7bd160b2
--- /dev/null
+++ b/packages/style-equivalence/src/generate/literal.ts
@@ -0,0 +1,25 @@
+import type { LiteralValue } from '../extract';
+
+export const SAMPLE_TEXT = 'Ag 文本 Text';
+
+export const VOID_TAGS = new Set([
+ 'area',
+ 'br',
+ 'col',
+ 'embed',
+ 'hr',
+ 'img',
+ 'input',
+ 'source',
+ 'wbr',
+]);
+
+export const keepLiteral = (name: string, substituted: boolean) => {
+ if (name === 'key' || name === 'ref' || /^on[A-Z]/.test(name)) return false;
+ return substituted ? /^(?:data-|aria-|role$|style$)/.test(name) : true;
+};
+
+export const renderLiteral = (name: string, value: LiteralValue) =>
+ typeof value === 'string'
+ ? `${name}=${JSON.stringify(value)}`
+ : `${name}={${JSON.stringify(value)}}`;
diff --git a/packages/style-equivalence/src/generate/module.ts b/packages/style-equivalence/src/generate/module.ts
new file mode 100644
index 00000000000..e1f1dfb75c2
--- /dev/null
+++ b/packages/style-equivalence/src/generate/module.ts
@@ -0,0 +1,255 @@
+import type { FileExtraction, RealComponent, StyleBinding, StyleElement } from '../extract';
+import type { ForwardElement } from '../extract/forward';
+import { elementsOf } from '../plan/descendants';
+import type { InnerNode } from '../plan/inner';
+import { bindKnobs } from '../plan/knobs';
+import { chainOf, type FilePlan, isIntrinsicTag, type Side } from '../plan/planFile';
+import { rendersReal } from '../plan/real';
+import { applicationOf, forwardImports, renderForward } from './forward';
+import { innerMarkup } from './inner';
+import { keepLiteral, renderLiteral, SAMPLE_TEXT, VOID_TAGS } from './literal';
+
+export { SAMPLE_TEXT } from './literal';
+
+export interface GenerateConfig {
+ cxFallback?: { name: string; source: string };
+ layoutComponents: string[];
+ realComponents?: Record<string, RealComponent>;
+}
+
+const placementTag = (element: StyleElement, layout: Set<string>) =>
+ isIntrinsicTag(element.tag) || layout.has(element.tag) ? element.tag : 'div';
+
+interface ChainContext {
+ byId?: Map<string, StyleElement>;
+ exprOf: (binding: StyleBinding) => string;
+ forward?: { application?: string; element: ForwardElement };
+ inner?: Record<string, InnerNode[]>;
+ layout: Set<string>;
+ omitted?: number[];
+ probed: Set<string>;
+ real?: Record<string, RealComponent>;
+ samples?: InnerNode[];
+}
+
+const sampleContent = (samples: InnerNode[] | undefined) =>
+ samples?.length ? innerMarkup(samples, SAMPLE_TEXT) : `{${JSON.stringify(SAMPLE_TEXT)}}`;
+
+const iconMarkup = (element: StyleElement, context: ChainContext) => {
+ const icon =
+ typeof element.iconElement === 'string' ? context.byId?.get(element.iconElement) : undefined;
+ const attributes =
+ icon && !icon.variables.length
+ ? icon.bindings.flatMap((binding) =>
+ binding.spread
+ ? [`{...(${binding.expr})}`]
+ : binding.prop === 'className'
+ ? [`className={${binding.expr}}`]
+ : [],
+ )
+ : [];
+ return `<span ${['data-synthetic-icon=""', ...attributes].join(' ')}></span>`;
+};
+
+const renderChain = (chain: StyleElement[], context: ChainContext, depth = 0): string => {
+ const { exprOf, layout, probed } = context;
+ const [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 tag = real ? element.tag : placementTag(element, layout);
+ const substituted = tag !== element.tag;
+ const attributes = [`data-synthetic-element=${JSON.stringify(element.id)}`];
+ 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})}`);
+ for (const [name, variable] of Object.entries(element.attributes ?? {}))
+ attributes.push(`${name}={${variable}}`);
+ const neutral: string[] = [];
+ for (const binding of element.bindings) {
+ const expr = exprOf(binding);
+ if (binding.spread) attributes.push(`{...(${expr})}`);
+ else if (binding.prop === 'className' || real) attributes.push(`${binding.prop}={${expr}}`);
+ else if (!context.omitted?.includes(depth))
+ neutral.push(`{__neutral(${JSON.stringify(binding.prop)}, ${expr})}`);
+ }
+ if (element.runtimeStyle && probed.has(element.runtimeStyle))
+ attributes.push(`style={${element.runtimeStyle}}`);
+ 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('')}</>`;
+ const inner = rest.length
+ ? renderChain(rest, context, depth + 1)
+ : `{${JSON.stringify(SAMPLE_TEXT)}}`;
+ const targets = innerMarkup(context.inner?.[depth], SAMPLE_TEXT);
+ const icon = substituted && element.iconElement ? iconMarkup(element, context) : '';
+ return `${open}>${icon}${inner}${targets}${neutral.join('')}</${tag}>`;
+};
+
+const NEUTRAL = `const __neutral = (prop: string, value: unknown): any => {
+ if (value == null || value === false) return null;
+ if (typeof value === 'string') return <div data-synthetic-neutral={prop} className={value}>{${JSON.stringify(SAMPLE_TEXT)}}</div>;
+ if (typeof value === 'object' && /^styles\\.[^.]+$/.test(prop)) return <div data-synthetic-neutral={prop} style={value as any}>{${JSON.stringify(SAMPLE_TEXT)}}</div>;
+ if (typeof value === 'object' && 'className' in (value as object)) return <div data-synthetic-neutral={prop} {...(value as object)}>{${JSON.stringify(SAMPLE_TEXT)}}</div>;
+ if (typeof value === 'object') return Object.entries(value as Record<string, unknown>).map(([key, item]) => <div key={key} data-synthetic-slot={key}>{__neutral(prop + '.' + key, item)}</div>);
+ return null;
+};
+const __probe = (name: string): any => ({ '--style-equivalence-probe': name, tabSize: 7 });
+const __member = (value: boolean): any => new Proxy({}, { get: () => value });
+const __opaque: any = new Proxy(function () {}, {
+ apply: () => __opaque,
+ construct: () => __opaque,
+ get: (_, key) => (key === Symbol.toPrimitive ? () => '' : key === 'then' ? undefined : __opaque),
+});`;
+
+const readsThrough = (expressions: string[], name: string) =>
+ expressions.some((expr) => new RegExp(`(^|[^\\w$.])${name}\\s*(\\?\\.|\\.|\\[)`).test(expr));
+
+const UNPAIRED_VALUES: Record<string, string> = {
+ boolean: 'false',
+ call: '() => false',
+ member: '__member(false)',
+};
+
+export const unpairedKey = (file: string, side: Side, elementId: string) =>
+ `${file}|unpaired:${side}:${elementId}`;
+
+const unpairedEntry = (
+ key: string,
+ chain: StyleElement[],
+ layout: Set<string>,
+ config: GenerateConfig,
+) => {
+ const expressions = chain.flatMap((item) => item.bindings.map((binding) => binding.expr));
+ const declared = new Set<string>();
+ const lines: string[] = [];
+ for (const [alias, symbol] of chain.flatMap((item) => Object.entries(item.aliases ?? {}))) {
+ if (declared.has(alias)) continue;
+ declared.add(alias);
+ lines.push(`const ${alias} = ${symbol};`);
+ }
+ for (const variable of chain.flatMap((item) => item.variables)) {
+ if (declared.has(variable.name)) continue;
+ declared.add(variable.name);
+ const value =
+ variable.name === 'cx' && config.cxFallback
+ ? '__cx'
+ : (UNPAIRED_VALUES[variable.kind] ??
+ (readsThrough(expressions, variable.name) ? '__opaque' : 'undefined'));
+ lines.push(`const ${variable.name} = ${value};`);
+ }
+ return `${JSON.stringify(key)}: () => { ${lines.join(' ')} return (${renderChain(chain, { exprOf: (binding) => binding.expr, layout, probed: new Set(), real: config.realComponents })}); }`;
+};
+
+export const generateModule = (
+ extraction: FileExtraction,
+ plan: FilePlan,
+ side: Side,
+ config: GenerateConfig,
+) => {
+ const layout = new Set(config.layoutComponents);
+ const byId = new Map(elementsOf(extraction).map((element) => [element.id, element]));
+ const entries = plan.cases.map((entry) => {
+ const element = byId.get(entry.elementIds[side]);
+ if (!element)
+ return `${JSON.stringify(entry.key)}: () => { throw new Error('CASE_ELEMENT_MISSING'); }`;
+ const chain = chainOf(element, byId, entry.chainOmit?.[side]);
+ const { knobs } = entry;
+ const inline = entry.inlineStyles?.[side] ?? [];
+ const bound = new Map<StyleBinding, string | undefined>(
+ chain.flatMap((item, index) =>
+ item.bindings.map((binding, position) => {
+ const expr =
+ inline.find((style) => style.index === index && style.binding === position)?.without ??
+ binding.expr;
+ return [binding, knobs ? bindKnobs(expr, knobs) : expr];
+ }),
+ ),
+ );
+ if ([...bound.values()].includes(undefined))
+ return `${JSON.stringify(entry.key)}: () => { throw new Error('KNOB_UNBOUND'); }`;
+ const declared = new Set<string>();
+ const lines: string[] = [];
+ const probed = new Set<string>();
+ for (const variable of entry.variables) {
+ if (variable.probe) {
+ probed.add(variable.name);
+ declared.add(variable.name);
+ lines.push(
+ `const ${variable.name} = __v[${JSON.stringify(variable.name)}] ? __probe(${JSON.stringify(variable.name)}) : undefined;`,
+ );
+ continue;
+ }
+ const kind = variable.kinds[side];
+ if (!kind) continue;
+ declared.add(variable.name);
+ const value = `__v[${JSON.stringify(variable.name)}]`;
+ lines.push(
+ kind === 'call'
+ ? `const ${variable.name} = () => ${value};`
+ : kind === 'member'
+ ? `const ${variable.name} = __member(${value});`
+ : `const ${variable.name} = ${value};`,
+ );
+ }
+ const expressions = chain.flatMap((item) => item.bindings.map((binding) => binding.expr));
+ for (const item of chain)
+ for (const [alias, symbol] of Object.entries(item.aliases ?? {})) {
+ if (declared.has(alias)) continue;
+ declared.add(alias);
+ lines.push(`const ${alias} = ${symbol};`);
+ }
+ for (const item of chain)
+ for (const variable of item.variables) {
+ if (declared.has(variable.name)) continue;
+ declared.add(variable.name);
+ lines.push(
+ variable.name === 'cx' && config.cxFallback
+ ? `const cx = __cx;`
+ : `const ${variable.name} = ${readsThrough(expressions, variable.name) ? '__opaque' : 'undefined'};`,
+ );
+ }
+ const target = entry.forward?.[side];
+ const forwarded =
+ entry.forward && element.bindings.find((item) => item.prop === entry.forward!.prop);
+ const context = {
+ byId,
+ exprOf: (binding: StyleBinding) => bound.get(binding)!,
+ forward: target && {
+ application: forwarded && applicationOf(entry.forward!.application, bound.get(forwarded)!),
+ element: target,
+ },
+ inner: entry.inner,
+ layout,
+ omitted: entry.neutralOmitted,
+ probed,
+ real: config.realComponents,
+ samples: entry.samples,
+ };
+ return `${JSON.stringify(entry.key)}: (__v: Record<string, boolean | string>) => { ${lines.join(' ')} return (${renderChain(chain, context)}); }`;
+ });
+ const unpaired = plan.unpaired
+ .filter((entry) => entry.side === side && byId.has(entry.elementId))
+ .map((entry) =>
+ unpairedEntry(
+ unpairedKey(plan.file, side, entry.elementId),
+ chainOf(byId.get(entry.elementId)!, byId),
+ layout,
+ config,
+ ),
+ );
+ return [
+ extraction.prelude,
+ ...forwardImports(plan.cases, side),
+ config.cxFallback
+ ? `import { ${config.cxFallback.name} as __cx } from ${JSON.stringify(config.cxFallback.source)};`
+ : '',
+ NEUTRAL,
+ `export const side = ${JSON.stringify(side)};`,
+ `export const cases = {\n${entries.join(',\n')}\n};`,
+ `export const unpaired = {\n${unpaired.join(',\n')}\n};`,
+ ]
+ .filter(Boolean)
+ .join('\n');
+};
diff --git a/packages/style-equivalence/src/generate/typeAssertion.test.ts b/packages/style-equivalence/src/generate/typeAssertion.test.ts
new file mode 100644
index 00000000000..decdaa8ad9f
--- /dev/null
+++ b/packages/style-equivalence/src/generate/typeAssertion.test.ts
@@ -0,0 +1,33 @@
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from '../plan/planFile';
+import { generateModule } from './module';
+
+const options = { adapters: [stylexAdapter], layoutComponents: [] };
+
+const source = `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ image: { width: '4px' } });
+
+export const Item = ({ flat }) => (
+ <div {...(flat ? stylex.props(styles.image) : { variant: 'outlined' as const })} />
+);
+`;
+
+describe('a style expression with a type assertion', () => {
+ it('declares only value names, so the generated module still parses', () => {
+ const extraction = extractFile(source, 'a.tsx', options);
+ expect(extraction.elements[0].variables.map((variable) => variable.name)).toEqual(['flat']);
+ const plan = planFile('a.tsx', extraction, extraction, { layoutComponents: [] });
+ const module = generateModule(extraction, plan, 'head', { layoutComponents: [] });
+ const { diagnostics } = ts.transpileModule(module, {
+ compilerOptions: { jsx: ts.JsxEmit.Preserve },
+ fileName: 'a.tsx',
+ reportDiagnostics: true,
+ });
+ expect(diagnostics?.map((entry) => entry.messageText)).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/mutation/operators.test.ts b/packages/style-equivalence/src/mutation/operators.test.ts
new file mode 100644
index 00000000000..6990630f298
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/operators.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyMutation,
+ conditionMutations,
+ declarationMutations,
+ type Mutation,
+ stylesheetMutations,
+} from './operators';
+
+const results = (code: string, mutations: Mutation[]) =>
+ Object.fromEntries(
+ mutations.map((mutation) => [mutation.operator, applyMutation(code, mutation)]),
+ );
+
+describe('declarationMutations on stylex', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+export const styles = stylex.create({
+ label: { color: cssVar.colorText, padding: '8px 4px', opacity: { default: 1, ':hover': 0.5 } },
+ other: { color: cssVar.colorTextSecondary },
+});
+`;
+
+ it('produces one mutation per operator on the member', () => {
+ const mutated = results(code, declarationMutations(code, 'styles', 'label'));
+ expect(mutated.numeric).toContain("padding: '9px 4px'");
+ expect(mutated['delete-declaration']).toContain('label: { padding:');
+ expect(mutated['swap-token']).toContain('label: { color: cssVar.colorTextSecondary,');
+ expect(mutated['delete-state']).toContain('opacity: { default: 1 }');
+ });
+
+ it('swaps a token for the one in its own family', () => {
+ const source = `const styles = stylex.create({ a: { borderRadius: cssVar.borderRadius, color: cssVar.colorText } });
+const other = [cssVar.colorFill, cssVar.borderRadiusLG];
+`;
+ const swap = declarationMutations(source, 'styles', 'a').find(
+ (item) => item.operator === 'swap-token',
+ )!;
+ expect(swap.replacement).toBe('cssVar.borderRadiusLG');
+ });
+
+ it('finds nothing for a member the factory does not declare', () => {
+ expect(declarationMutations(code, 'styles', 'missing')).toEqual([]);
+ });
+});
+
+describe('declarationMutations on a css template', () => {
+ const code = `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ label: css\`
+ gap: 6px;
+ color: \${cssVar.colorText};
+
+ &:hover {
+ color: \${cssVar.colorTextSecondary};
+ }
+ \`,
+}));
+`;
+
+ it('edits the template text and the token placeholders', () => {
+ const mutated = results(code, declarationMutations(code, 'styles', 'label'));
+ expect(mutated.numeric).toContain('gap: 7px;');
+ expect(mutated['delete-declaration']).not.toContain('gap: 6px;');
+ expect(mutated['swap-token']).toContain('color: ${cssVar.colorTextSecondary};\n\n &:hover');
+ expect(mutated['delete-state']).not.toContain('&:hover');
+ expect(mutated['delete-state']).toContain('gap: 6px;');
+ });
+});
+
+describe('stylesheetMutations', () => {
+ const css = `.title { font-weight: 600; color: var(--ink); }
+.title:hover { color: red; }
+.other { color: var(--ink-alias); }
+`;
+
+ it('mutates the rules of the class', () => {
+ const mutated = results(css, stylesheetMutations(css, 'title'));
+ expect(mutated.numeric).toContain('font-weight: 601;');
+ expect(mutated['delete-declaration']).toContain('.title { color: var(--ink); }');
+ expect(mutated['swap-token']).toContain(
+ '.title { font-weight: 600; color: var(--ink-alias); }',
+ );
+ expect(mutated['delete-state']).not.toContain('.title:hover');
+ });
+});
+
+describe('conditionMutations', () => {
+ it('negates a guard and swaps ternary branches', () => {
+ const [guard] = conditionMutations('cx(styles.a, muted && styles.b)');
+ expect(applyMutation('cx(styles.a, muted && styles.b)', guard)).toBe(
+ 'cx(styles.a, !(muted) && styles.b)',
+ );
+ const [ternary] = conditionMutations('active ? styles.on : styles.off');
+ expect(applyMutation('active ? styles.on : styles.off', ternary)).toBe(
+ 'active ? styles.off : styles.on',
+ );
+ });
+});
diff --git a/packages/style-equivalence/src/mutation/operators.ts b/packages/style-equivalence/src/mutation/operators.ts
new file mode 100644
index 00000000000..ab316765655
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/operators.ts
@@ -0,0 +1,343 @@
+import postcss, { type Declaration, type Rule } from 'postcss';
+import ts from 'typescript';
+
+import { classNamesIn } from '../extract/selectors';
+import { findStyleMember, parseSource, propertyNameOf } from '../source/declarations';
+
+export type MutationOperator =
+ 'delete-declaration' | 'delete-state' | 'invert-condition' | 'numeric' | 'swap-token';
+
+export const MUTATION_OPERATORS: MutationOperator[] = [
+ 'numeric',
+ 'delete-declaration',
+ 'swap-token',
+ 'delete-state',
+ 'invert-condition',
+];
+
+export interface Mutation {
+ description: string;
+ end: number;
+ operator: MutationOperator;
+ replacement: string;
+ start: number;
+}
+
+export const applyMutation = (code: string, mutation: Mutation) =>
+ code.slice(0, mutation.start) + mutation.replacement + code.slice(mutation.end);
+
+const NUMBER = /-?\d*\.?\d+/;
+
+const bumpNumber = (text: string) => {
+ const match = NUMBER.exec(text);
+ if (!match) return undefined;
+ const value = Number(match[0]);
+ const next = Number.isInteger(value) ? value + 1 : Math.round((value + 0.1) * 10_000) / 10_000;
+ return text.slice(0, match.index) + String(next) + text.slice(match.index + match[0].length);
+};
+
+const firstOf = (mutations: Array<Mutation | undefined>) => {
+ const seen = new Set<MutationOperator>();
+ return mutations.filter((mutation): mutation is Mutation => {
+ if (!mutation || seen.has(mutation.operator)) return false;
+ seen.add(mutation.operator);
+ return true;
+ });
+};
+
+const removal = (code: string, node: ts.Node, operator: MutationOperator): Mutation => {
+ let start = node.getFullStart();
+ let end = node.end;
+ let after = end;
+ while (/\s/.test(code[after] ?? '')) after++;
+ if (code[after] === ',') end = after + 1;
+ else {
+ let before = start - 1;
+ while (before >= 0 && /\s/.test(code[before])) before--;
+ if (code[before] === ',') start = before;
+ }
+ return { description: `${operator}: ${node.getText()}`, end, operator, replacement: '', start };
+};
+
+const sharedPrefix = (left: string, right: string) => {
+ let length = 0;
+ while (length < left.length && left[length] === right[length]) length++;
+ return length;
+};
+
+const closest = (name: string, others: string[]) =>
+ others.reduce<string | undefined>(
+ (best, other) =>
+ best === undefined || sharedPrefix(name, other) > sharedPrefix(name, best) ? other : best,
+ undefined,
+ );
+
+const tokenSwap = (sf: ts.SourceFile, token: ts.Node): Mutation | undefined => {
+ if (!ts.isPropertyAccessExpression(token) || !ts.isIdentifier(token.expression)) return;
+ const object = token.expression.text;
+ const names: string[] = [];
+ const visit = (node: ts.Node) => {
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === object &&
+ node.name.text !== token.name.text &&
+ !names.includes(node.name.text)
+ )
+ names.push(node.name.text);
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ const name = closest(token.name.text, names);
+ const other = name && `${object}.${name}`;
+ if (!other) return;
+ return {
+ description: `swap-token: ${token.getText(sf)} → ${other}`,
+ end: token.end,
+ operator: 'swap-token',
+ replacement: other,
+ start: token.getStart(sf),
+ };
+};
+
+const objectMutations = (code: string, sf: ts.SourceFile, object: ts.ObjectLiteralExpression) => {
+ const leaves: ts.PropertyAssignment[] = [];
+ const states: ts.PropertyAssignment[] = [];
+ const walk = (node: ts.ObjectLiteralExpression) => {
+ for (const property of node.properties) {
+ if (!ts.isPropertyAssignment(property)) continue;
+ if (/^[:@]/.test(propertyNameOf(property.name) ?? '')) states.push(property);
+ if (ts.isObjectLiteralExpression(property.initializer)) walk(property.initializer);
+ else leaves.push(property);
+ }
+ };
+ walk(object);
+ const numeric = leaves
+ .map((leaf) => leaf.initializer)
+ .find(
+ (value) =>
+ ts.isNumericLiteral(value) || (ts.isStringLiteral(value) && NUMBER.test(value.text)),
+ );
+ const bumped = numeric && bumpNumber(numeric.getText(sf));
+ const first = object.properties.find(ts.isPropertyAssignment);
+ return [
+ numeric && bumped
+ ? {
+ description: `numeric: ${numeric.getText(sf)} → ${bumped}`,
+ end: numeric.end,
+ operator: 'numeric' as const,
+ replacement: bumped,
+ start: numeric.getStart(sf),
+ }
+ : undefined,
+ first ? removal(code, first, 'delete-declaration') : undefined,
+ ...leaves.map((leaf) => tokenSwap(sf, leaf.initializer)),
+ states[0] ? removal(code, states[0], 'delete-state') : undefined,
+ ];
+};
+
+const DECLARATION = /(^|[\s{;])([a-z-]+)\s*:\s*([^;{}]*);/g;
+const STATE = /&[:[]|@(?:media|container|supports)/;
+
+const templateMutations = (code: string, sf: ts.SourceFile, template: ts.TemplateLiteral) => {
+ const offset = template.getStart(sf);
+ let masked = template.getText(sf);
+ const spans = ts.isTemplateExpression(template) ? template.templateSpans : [];
+ for (const span of spans) {
+ const from = span.expression.getFullStart() - 2 - offset;
+ const to = span.literal.getStart(sf) + 1 - offset;
+ masked = masked.slice(0, from) + 'X'.repeat(to - from) + masked.slice(to);
+ }
+ const declarations = [...masked.matchAll(DECLARATION)].map((match) => ({
+ start: match.index + match[1].length,
+ text: match[0].slice(match[1].length),
+ value: match[3],
+ }));
+ const numericDeclaration = declarations.find((item) => NUMBER.test(item.value));
+ const numeric =
+ numericDeclaration &&
+ (() => {
+ const colon = numericDeclaration.text.indexOf(':');
+ const match = NUMBER.exec(numericDeclaration.text.slice(colon))!;
+ const start = offset + numericDeclaration.start + colon + match.index;
+ return {
+ end: start + match[0].length,
+ replacement: bumpNumber(match[0])!,
+ start,
+ text: match[0],
+ };
+ })();
+ const first = declarations[0];
+ const state = STATE.exec(masked);
+ let stateRange: [number, number] | undefined;
+ if (state) {
+ const open = masked.indexOf('{', state.index);
+ let depth = 0;
+ for (let index = open; index >= 0 && index < masked.length; index++) {
+ if (masked[index] === '{') depth++;
+ if (masked[index] === '}' && --depth === 0) {
+ let start = state.index;
+ while (start > 0 && /[\t ]/.test(masked[start - 1])) start--;
+ stateRange = [start, index + 1];
+ break;
+ }
+ }
+ }
+ return [
+ numeric && {
+ description: `numeric: ${numeric.text} → ${numeric.replacement}`,
+ end: numeric.end,
+ operator: 'numeric' as const,
+ replacement: numeric.replacement,
+ start: numeric.start,
+ },
+ first && {
+ description: `delete-declaration: ${code.slice(offset + first.start, offset + first.start + first.text.length)}`,
+ end: offset + first.start + first.text.length,
+ operator: 'delete-declaration' as const,
+ replacement: '',
+ start: offset + first.start,
+ },
+ ...spans.map((span) => tokenSwap(sf, span.expression)),
+ stateRange && {
+ description: `delete-state: ${masked.slice(stateRange[0], stateRange[1]).trim().split('{')[0].trim()}`,
+ end: offset + stateRange[1],
+ operator: 'delete-state' as const,
+ replacement: '',
+ start: offset + stateRange[0],
+ },
+ ];
+};
+
+export 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;
+ if (ts.isObjectLiteralExpression(value)) return firstOf(objectMutations(code, sf, value));
+ if (ts.isTaggedTemplateExpression(value))
+ return firstOf(templateMutations(code, sf, value.template));
+ return [];
+};
+
+const VARIABLE = /var\((--[\w-]+)/;
+
+export const stylesheetMutations = (css: string, className: string): Mutation[] => {
+ const root = postcss.parse(css);
+ const plain: Rule[] = [];
+ const states: Rule[] = [];
+ const variables = new Set<string>();
+ root.walkDecls((declaration) => {
+ for (const match of declaration.value.matchAll(/var\((--[\w-]+)/g)) variables.add(match[1]);
+ });
+ root.walkRules((rule) => {
+ if (!classNamesIn(rule.selector).includes(className)) return;
+ const conditional = rule.parent?.type === 'atrule' || /:(?!:)|\[/.test(rule.selector);
+ (conditional ? states : plain).push(rule);
+ });
+ const range = (node: Declaration | Rule) =>
+ [node.source!.start!.offset, node.source!.end!.offset] as const;
+ const declarations = plain.flatMap((rule) => rule.nodes.filter((node) => node.type === 'decl'));
+ const numeric = declarations.find((declaration) => NUMBER.test(declaration.value));
+ const swap = declarations.find((declaration) => {
+ const used = VARIABLE.exec(declaration.value)?.[1];
+ return used && [...variables].some((name) => name !== used);
+ });
+ const mutations: Array<Mutation | undefined> = [];
+ if (numeric) {
+ const [start, end] = range(numeric);
+ const text = css.slice(start, end);
+ const colon = text.indexOf(':');
+ const replacement = text.slice(0, colon) + bumpNumber(text.slice(colon))!;
+ mutations.push({
+ description: `numeric: ${text} → ${replacement}`,
+ end,
+ operator: 'numeric',
+ replacement,
+ start,
+ });
+ }
+ if (declarations[0]) {
+ const [start, end] = range(declarations[0]);
+ let after = end;
+ while (/[\t ]/.test(css[after] ?? '')) after++;
+ mutations.push({
+ description: `delete-declaration: ${css.slice(start, end)}`,
+ end: after,
+ operator: 'delete-declaration',
+ replacement: '',
+ start,
+ });
+ }
+ if (swap) {
+ const [start, end] = range(swap);
+ const text = css.slice(start, end);
+ const used = VARIABLE.exec(swap.value)![1];
+ const other = closest(
+ used,
+ [...variables].filter((name) => name !== used),
+ )!;
+ const replacement = text.replace(`var(${used}`, `var(${other}`);
+ mutations.push({
+ description: `swap-token: ${used} → ${other}`,
+ end,
+ operator: 'swap-token',
+ replacement,
+ start,
+ });
+ }
+ if (states[0]) {
+ const [start, end] = range(states[0]);
+ mutations.push({
+ description: `delete-state: ${states[0].selector}`,
+ end: css[end] === '\n' ? end + 1 : end,
+ operator: 'delete-state',
+ replacement: '',
+ start,
+ });
+ }
+ return firstOf(mutations);
+};
+
+const PREFIX = 'const __mutated = (';
+
+export const conditionMutations = (expression: string): Mutation[] => {
+ const sf = ts.createSourceFile(
+ 'condition.tsx',
+ `${PREFIX}${expression});`,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const mutations: Mutation[] = [];
+ const at = (node: ts.Node) => [node.getStart(sf) - PREFIX.length, node.end - PREFIX.length];
+ const visit = (node: ts.Node) => {
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken
+ ) {
+ const [start, end] = at(node.left);
+ mutations.push({
+ description: `invert-condition: ${node.left.getText(sf)}`,
+ end,
+ operator: 'invert-condition',
+ replacement: `!(${node.left.getText(sf)})`,
+ start,
+ });
+ }
+ if (ts.isConditionalExpression(node)) {
+ const [start] = at(node.whenTrue);
+ const [, end] = at(node.whenFalse);
+ mutations.push({
+ description: `invert-condition: ${node.condition.getText(sf)} ? … : …`,
+ end,
+ operator: 'invert-condition',
+ replacement: `${node.whenFalse.getText(sf)} : ${node.whenTrue.getText(sf)}`,
+ start,
+ });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ return mutations;
+};
diff --git a/packages/style-equivalence/src/mutation/outcome.test.ts b/packages/style-equivalence/src/mutation/outcome.test.ts
new file mode 100644
index 00000000000..544162da6bb
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/outcome.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { mutantOutcome } from './outcome';
+
+const outcome = (
+ expected: string[],
+ detected: string[],
+ gaps: string[] = [],
+ errors: string[] = [],
+) => mutantOutcome({ detected: new Set(detected), errors, expected: new Set(expected), gaps });
+
+describe('mutantOutcome', () => {
+ it('counts a mutant that changes nothing sampled and opens no gap as equivalent', () => {
+ expect(outcome([], [])).toBe('equivalent');
+ });
+
+ it('counts a mutant inside an unsampled state as caught by the gap it opens', () => {
+ expect(outcome([], [], ['STATE_UNMODELED'])).toBe('caught');
+ });
+
+ it('requires the detected conditions to match the expected ones exactly', () => {
+ expect(outcome(['light/1280/default#0'], ['light/1280/default#0'])).toBe('caught');
+ expect(outcome(['light/1280/default#0'], [])).toBe('missed');
+ });
+
+ it('reports errors before anything else', () => {
+ expect(outcome([], [], [], ['MUTANT_NOT_CAPTURED'])).toBe('error');
+ });
+});
diff --git a/packages/style-equivalence/src/mutation/outcome.ts b/packages/style-equivalence/src/mutation/outcome.ts
new file mode 100644
index 00000000000..f707cc65947
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/outcome.ts
@@ -0,0 +1,19 @@
+export type MutantOutcome = 'caught' | 'equivalent' | 'error' | 'missed';
+
+export const mutantOutcome = ({
+ detected,
+ errors,
+ expected,
+ gaps,
+}: {
+ detected: Set<string>;
+ errors: string[];
+ expected: Set<string>;
+ gaps: string[];
+}): MutantOutcome => {
+ if (errors.length) return 'error';
+ if (!expected.size) return gaps.length ? 'caught' : 'equivalent';
+ return expected.size === detected.size && [...expected].every((item) => detected.has(item))
+ ? 'caught'
+ : 'missed';
+};
diff --git a/packages/style-equivalence/src/mutation/plan.ts b/packages/style-equivalence/src/mutation/plan.ts
new file mode 100644
index 00000000000..b73a2ec3f93
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/plan.ts
@@ -0,0 +1,126 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import type { FileExtraction } from '../extract';
+import type { Side } from '../plan/planFile';
+import { resolveSlot } from '../source/declarations';
+import type { ScopeFile } from '../source/scope';
+import type { CaseCategory } from '../verdict/categorize';
+import {
+ conditionMutations,
+ declarationMutations,
+ type Mutation,
+ MUTATION_OPERATORS,
+ type MutationOperator,
+ stylesheetMutations,
+} from './operators';
+
+export type MutationSite =
+ | { binding: number; kind: 'binding' }
+ | { kind: 'import'; path: string; specifier: string }
+ | { kind: 'source'; path: string };
+
+export interface MutationCandidate {
+ caseKey: string;
+ file: string;
+ mutation: Mutation;
+ site: MutationSite;
+}
+
+export interface PlannableCase {
+ category: CaseCategory;
+ key: string;
+ plan: { elementIds: Record<Side, string>; file: string };
+}
+
+export interface PlanMutationsInput {
+ aliases: Record<string, string>;
+ cases: PlannableCase[];
+ count: number;
+ extractions: Record<string, Record<Side, FileExtraction>>;
+ headRoot: string;
+ operators?: MutationOperator[];
+ scope: ScopeFile[];
+ seed: string;
+}
+
+export const OVERSAMPLE = 3;
+
+const random = (seed: string) => {
+ let state = [...seed].reduce(
+ (hash, char) => Math.imul(hash ^ char.charCodeAt(0), 16_777_619),
+ 2_166_136_261,
+ );
+ return () => {
+ state = Math.imul(state ^ (state >>> 15), 2_246_822_507);
+ state = Math.imul(state ^ (state >>> 13), 3_266_489_909);
+ return ((state ^= state >>> 16) >>> 0) / 4_294_967_296;
+ };
+};
+
+const shuffled = <T>(items: T[], seed: string) => {
+ const next = random(seed);
+ const copy = [...items];
+ for (let index = copy.length - 1; index > 0; index--) {
+ const other = Math.floor(next() * (index + 1));
+ [copy[index], copy[other]] = [copy[other], copy[index]];
+ }
+ return copy;
+};
+
+const slotMutations = (
+ input: PlanMutationsInput,
+ source: string,
+ code: string,
+ slot: string,
+): Array<{ mutation: Mutation; site: MutationSite }> =>
+ resolveSlot(input.headRoot, source, code, slot, input.aliases).flatMap((site) =>
+ (site.css
+ ? stylesheetMutations(site.code, site.member)
+ : declarationMutations(site.code, site.symbol, site.member)
+ ).map((mutation) => ({
+ mutation,
+ site:
+ site.kind === 'source'
+ ? { kind: 'source' as const, path: site.path }
+ : { kind: 'import' as const, path: site.path, specifier: site.specifier! },
+ })),
+ );
+
+export const planMutations = (input: PlanMutationsInput): MutationCandidate[] => {
+ const operators = input.operators ?? MUTATION_OPERATORS;
+ const candidates: MutationCandidate[] = [];
+ const equal = shuffled(
+ input.cases.filter((entry) => entry.category === 'equal'),
+ input.seed,
+ );
+ for (const entry of equal) {
+ if (candidates.length >= input.count * OVERSAMPLE) break;
+ const source = input.scope.find((item) => (item.head ?? item.base) === entry.plan.file)?.head;
+ const extraction = input.extractions[entry.plan.file]?.head;
+ const element = extraction?.elements.find((item) => item.id === entry.plan.elementIds.head);
+ if (!source || !element) continue;
+ const code = readFileSync(path.join(input.headRoot, source), 'utf8');
+ const options = [
+ ...element.slots.flatMap((slot) => slotMutations(input, source, code, slot)),
+ ...element.bindings.flatMap((binding, index) =>
+ element.variables.length
+ ? conditionMutations(binding.expr).map((mutation) => ({
+ mutation,
+ site: { binding: index, kind: 'binding' as const },
+ }))
+ : [],
+ ),
+ ].filter((option) => operators.includes(option.mutation.operator));
+ if (!options.length) continue;
+ const preferred = operators[candidates.length % operators.length];
+ const chosen =
+ options.find((option) => option.mutation.operator === preferred) ??
+ options.find(
+ (option) => operators.indexOf(option.mutation.operator) > operators.indexOf(preferred),
+ ) ??
+ options[0];
+ candidates.push({ caseKey: entry.key, file: entry.plan.file, ...chosen });
+ }
+ return candidates;
+};
diff --git a/packages/style-equivalence/src/mutation/run.ts b/packages/style-equivalence/src/mutation/run.ts
new file mode 100644
index 00000000000..3dbf0901dd8
--- /dev/null
+++ b/packages/style-equivalence/src/mutation/run.ts
@@ -0,0 +1,295 @@
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Browser } from '@playwright/test';
+
+import { analyzeRun } from '../analyze/diff';
+import { buildSide } from '../build/viteBuild';
+import {
+ captureSections,
+ CONDITION_CONCURRENCY,
+ type ConditionCapture,
+ conditionLabel,
+ inspectCaseGaps,
+ type SectionSnapshots,
+} from '../capture/runner';
+import { compareSnapshots } from '../capture/snapshot';
+import type { CaptureState } from '../capture/states';
+import type { ProjectConfig } from '../config';
+import { extractFile, type FileExtraction } from '../extract';
+import { generateHost, HOST_HTML } from '../generate/host';
+import { generateModule } from '../generate/module';
+import { moduleReader, RUNTIME, stylesheetReader } from '../pipeline/synthesize';
+import type { FilePlan } from '../plan/planFile';
+import type { ScopeFile } from '../source/scope';
+import { applyMutation, type MutationOperator } from './operators';
+import { type MutantOutcome, mutantOutcome } from './outcome';
+import type { MutationCandidate } from './plan';
+
+export const MUTANT_HOST_DIR = '.style-equivalence-host-mutants';
+
+export type { MutantOutcome } from './outcome';
+
+export interface MutantResult {
+ caseKey: string;
+ description: string;
+ detected: string[];
+ errors: string[];
+ expected: string[];
+ gaps: string[];
+ operator: MutationOperator;
+ outcome: MutantOutcome;
+ site: MutationCandidate['site'];
+}
+
+export interface MutationReport {
+ caught: number;
+ equivalent: number;
+ error?: string;
+ evaluated: number;
+ mutants: MutantResult[];
+ passed: boolean;
+ requested: number;
+}
+
+export interface MutationContext {
+ browser: Browser;
+ candidates: MutationCandidate[];
+ config: ProjectConfig;
+ configDir: string;
+ configFile: string;
+ count: number;
+ extractions: Record<string, { head: FileExtraction }>;
+ headRoot: string;
+ plans: FilePlan[];
+ runDir: string;
+ scope: ScopeFile[];
+ serverUrl: string;
+ states: CaptureState[];
+ widths: number[];
+}
+
+const prefixed = (file: string, prefix: string) =>
+ path.join(path.dirname(file), `${prefix}${path.basename(file)}`);
+
+const specifierFor = (from: string, target: string) => {
+ const relative = path.relative(path.dirname(from), target).replaceAll(path.sep, '/');
+ const bare = relative.endsWith('.css') ? relative : relative.replace(/\.[cm]?[jt]sx?$/, '');
+ return bare.startsWith('.') ? bare : `./${bare}`;
+};
+
+const replaceSpecifier = (prelude: string, from: string, to: string) =>
+ prelude.replaceAll(`'${from}'`, `'${to}'`).replaceAll(`"${from}"`, `"${to}"`);
+
+const writeMutant = async (
+ context: MutationContext,
+ candidate: MutationCandidate,
+ index: number,
+ plan: FilePlan,
+) => {
+ const source = context.scope.find(
+ (entry) => (entry.head ?? entry.base) === candidate.file,
+ )!.head!;
+ const original = context.extractions[candidate.file].head;
+ const caseEntry = plan.cases.find((entry) => entry.key === candidate.caseKey)!;
+ const single: FilePlan = { ...plan, cases: [caseEntry], file: `${plan.file}#mutant${index}` };
+ let extraction = original;
+ const { site } = candidate;
+ if (site.kind === 'binding')
+ extraction = {
+ ...original,
+ elements: original.elements.map((element) =>
+ element.id === caseEntry.elementIds.head
+ ? {
+ ...element,
+ bindings: element.bindings.map((binding, position) =>
+ position === site.binding
+ ? { ...binding, expr: applyMutation(binding.expr, candidate.mutation) }
+ : binding,
+ ),
+ }
+ : element,
+ ),
+ };
+ if (site.kind === 'source') {
+ const code = await readFile(path.join(context.headRoot, source), 'utf8');
+ extraction = extractFile(applyMutation(code, candidate.mutation), source, {
+ adapters: context.config.adapters,
+ layoutComponents: context.config.layoutComponents,
+ readModule: moduleReader(context.headRoot, context.config.aliases),
+ readStylesheet: stylesheetReader(context.headRoot, context.config.aliases),
+ realComponents: context.config.realComponents,
+ });
+ }
+ if (site.kind === 'import') {
+ const copy = prefixed(site.path, `__style_equivalence_mutant_${index}__`);
+ const code = await readFile(path.join(context.headRoot, site.path), 'utf8');
+ await writeFile(path.join(context.headRoot, copy), applyMutation(code, candidate.mutation));
+ extraction = {
+ ...original,
+ prelude: replaceSpecifier(original.prelude, site.specifier, specifierFor(source, copy)),
+ };
+ }
+ const module = path.join(
+ context.headRoot,
+ prefixed(source, `__style_equivalence_mutant_case_${index}__`),
+ );
+ await writeFile(module, generateModule(extraction, single, 'head', context.config));
+ return { module, single };
+};
+
+const label = (condition: string, section: string) =>
+ `${condition}#${section.slice(section.lastIndexOf('|') + 1)}`;
+
+const failedReport = (context: MutationContext, error: string): MutationReport => ({
+ caught: 0,
+ error,
+ evaluated: 0,
+ equivalent: 0,
+ mutants: [],
+ passed: false,
+ requested: context.count,
+});
+
+export const runMutations = async (context: MutationContext): Promise<MutationReport> => {
+ if (!context.candidates.length)
+ return {
+ caught: 0,
+ evaluated: 0,
+ equivalent: 0,
+ mutants: [],
+ passed: true,
+ requested: context.count,
+ };
+ const host = path.join(context.headRoot, MUTANT_HOST_DIR);
+ await rm(host, { force: true, recursive: true });
+ await mkdir(host, { recursive: true });
+ const written = await Promise.all(
+ context.candidates.map((candidate, index) =>
+ writeMutant(
+ context,
+ candidate,
+ index,
+ context.plans.find((plan) => plan.file === candidate.file)!,
+ ),
+ ),
+ );
+ await writeFile(path.join(host, 'index.html'), HOST_HTML);
+ await writeFile(path.join(host, 'plan.json'), JSON.stringify(written.map((item) => item.single)));
+ await writeFile(
+ path.join(host, 'entry.tsx'),
+ generateHost({
+ hostWrapper: path.resolve(context.configDir, context.config.hostWrapper),
+ modules: written.map((item) => ({ file: item.single.file, specifier: item.module })),
+ runtime: RUNTIME,
+ themeAttribute: context.config.conditions.themeAttribute,
+ }),
+ );
+ try {
+ await buildSide({
+ configFile: context.configFile,
+ hostDir: host,
+ logFile: path.join(context.runDir, 'build-mutants.log'),
+ outDir: path.join(context.runDir, 'dist-mutants'),
+ root: context.headRoot,
+ });
+ } catch (error) {
+ return failedReport(context, error instanceof Error ? error.message : String(error));
+ }
+ const keys = encodeURIComponent(JSON.stringify(context.candidates.map((item) => item.caseKey)));
+ const urls = {
+ base: `${context.serverUrl}/dist-base/#cases=${keys}`,
+ head: `${context.serverUrl}/dist-head/#cases=${keys}`,
+ mutant: `${context.serverUrl}/dist-mutants/`,
+ };
+ const pageErrors: string[] = [];
+ const plan = context.config.conditions.themes.flatMap((theme) =>
+ context.widths.flatMap((width) => context.states.map((state) => ({ state, theme, width }))),
+ );
+ const gaps = await inspectCaseGaps(
+ context.browser,
+ { base: urls.head, head: urls.mutant },
+ plan[0],
+ pageErrors,
+ );
+ const conditions: Array<ConditionCapture & { original: SectionSnapshots }> = [];
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: CONDITION_CONCURRENCY }, async () => {
+ for (let index = next++; index < plan.length; index = next++) {
+ const options = plan[index];
+ const { identical, snapshots } = await captureSections(
+ context.browser,
+ [urls.base, urls.head, urls.mutant],
+ options,
+ pageErrors,
+ );
+ const [base, head, mutant] = snapshots;
+ conditions[index] = {
+ base,
+ baseAgain: base,
+ condition: conditionLabel(options),
+ head: mutant,
+ identical,
+ original: head,
+ ...options,
+ };
+ }
+ }),
+ );
+ const results = new Map(
+ analyzeRun({
+ conditions,
+ containerRules: 0,
+ pageErrors,
+ unparsedMedia: 0,
+ unparsedSelectors: [],
+ widths: context.widths,
+ }).map((result) => [result.key, result]),
+ );
+ const evaluated = context.candidates.map((candidate): MutantResult => {
+ const expected = new Set<string>();
+ for (const condition of conditions)
+ for (const [section, mutant] of Object.entries(condition.head)) {
+ if (!section.startsWith(`${candidate.caseKey}|`)) continue;
+ const original = condition.original[section];
+ if (!original || 'error' in original || 'error' in mutant) continue;
+ if (compareSnapshots(original, mutant).some((item) => !item.diagnosticReason))
+ expected.add(label(condition.condition, section));
+ }
+ const result = results.get(candidate.caseKey);
+ const detected = new Set(
+ result?.comboDifferences.map((item) => `${item.condition}#${item.combo}`) ?? [],
+ );
+ const errors = result ? result.errors : ['MUTANT_NOT_CAPTURED'];
+ const caseGaps = gaps[candidate.caseKey] ?? [];
+ const outcome = mutantOutcome({ detected, errors, expected, gaps: caseGaps });
+ return {
+ caseKey: candidate.caseKey,
+ description: candidate.mutation.description,
+ detected: [...detected].sort(),
+ errors,
+ expected: [...expected].sort(),
+ gaps: caseGaps,
+ operator: candidate.mutation.operator,
+ outcome,
+ site: candidate.site,
+ };
+ });
+ const mutants: MutantResult[] = [];
+ let counted = 0;
+ for (const mutant of evaluated) {
+ if (counted >= context.count) break;
+ mutants.push(mutant);
+ if (mutant.outcome !== 'equivalent') counted++;
+ }
+ const caught = mutants.filter((mutant) => mutant.outcome === 'caught').length;
+ return {
+ caught,
+ evaluated: counted,
+ equivalent: mutants.length - counted,
+ mutants,
+ passed: caught === counted,
+ requested: context.count,
+ };
+};
diff --git a/packages/style-equivalence/src/pipeline/forwardCallers.test.ts b/packages/style-equivalence/src/pipeline/forwardCallers.test.ts
new file mode 100644
index 00000000000..c1a9a7846a0
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/forwardCallers.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FileExtraction } from '../extract';
+import type { FilePlan } from '../plan/planFile';
+import { flagUncheckedCallers } from './forwardCallers';
+
+const extraction = (file: string, props: string[]): FileExtraction => ({
+ elements: props.map((prop, index) => ({
+ bindings: [{ expr: 'styles.title', prop, spread: false }],
+ flags: [],
+ id: `A#${index}`,
+ literalProps: {},
+ owner: 'A',
+ slots: [],
+ tag: 'Identity',
+ variables: [],
+ })),
+ file,
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ styleSymbols: [],
+});
+
+const plans = (): FilePlan[] => [
+ {
+ cases: [
+ {
+ combos: [{}],
+ elementIds: { base: 'I#0/0', head: 'I#1' },
+ file: 'Identity.tsx',
+ flags: [],
+ forwardedParam: 'titleXstyle',
+ key: 'Identity.tsx|I#0/0',
+ variables: [],
+ },
+ ],
+ file: 'Identity.tsx',
+ gaps: [],
+ unpaired: [],
+ },
+];
+
+const sources: Record<string, string> = {
+ 'Embed.tsx': '<Identity titleXstyle={styles.title} />',
+ 'Other.tsx': 'const props = { titleXstyle: styles.title };',
+};
+
+const run = async (files: string[], scoped: Record<string, string[]>) => {
+ const list = plans();
+ await flagUncheckedCallers(list, {
+ extractions: Object.fromEntries(
+ Object.entries(scoped).map(([file, props]) => [
+ file,
+ { base: extraction(file, []), head: extraction(file, props) },
+ ]),
+ ),
+ grep: async () => ['Identity.tsx', ...files],
+ read: (file) => sources[file] ?? '',
+ });
+ return list[0].cases[0].flags;
+};
+
+describe('callers of a forwarded prop', () => {
+ it('accepts callers whose every mention is a style binding the tool compares', async () => {
+ expect(await run(['Embed.tsx'], { 'Embed.tsx': ['titleXstyle'] })).toEqual([]);
+ });
+
+ it('flags a caller outside the compared files', async () => {
+ expect(await run(['Embed.tsx', 'Other.tsx'], { 'Embed.tsx': ['titleXstyle'] })).toEqual([
+ 'FORWARDED_CALLER_UNCHECKED:Other.tsx',
+ ]);
+ });
+
+ it('flags a compared caller that mentions the prop outside a style binding', async () => {
+ expect(await run(['Other.tsx'], { 'Other.tsx': [] })).toEqual([
+ 'FORWARDED_CALLER_UNCHECKED:Other.tsx',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/pipeline/forwardCallers.ts b/packages/style-equivalence/src/pipeline/forwardCallers.ts
new file mode 100644
index 00000000000..0ff4d2662ed
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/forwardCallers.ts
@@ -0,0 +1,59 @@
+import { execFile } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import type { FileExtraction } from '../extract';
+import type { FilePlan, Side } from '../plan/planFile';
+
+const run = promisify(execFile);
+
+export interface CallerContext {
+ extractions: Record<string, Record<Side, FileExtraction>>;
+ grep: (word: string) => Promise<string[]>;
+ read: (file: string) => string;
+}
+
+export const gitGrepWord = (root: string) => async (word: string) => {
+ try {
+ const { stdout } = await run(
+ 'git',
+ ['-C', root, 'grep', '-l', '-w', '-e', word, '--', '*.ts', '*.tsx'],
+ {
+ maxBuffer: 64 * 1024 ** 2,
+ },
+ );
+ return stdout.split('\n').filter(Boolean);
+ } catch (error) {
+ if ((error as { code?: number }).code === 1) return [];
+ throw error;
+ }
+};
+
+export const fileReader = (root: string) => (file: string) =>
+ readFileSync(path.join(root, file), 'utf8');
+
+const checked = (file: string, word: string, context: CallerContext) => {
+ const extraction = Object.values(context.extractions).find(
+ (pair) => pair.head.file === file,
+ )?.head;
+ if (!extraction) return false;
+ const mentions = context.read(file).match(new RegExp(`\\b${word}\\b`, 'g'))?.length ?? 0;
+ const bound = extraction.elements
+ .flatMap((element) => element.bindings)
+ .filter((binding) => binding.prop === word).length;
+ return mentions === bound;
+};
+
+export const flagUncheckedCallers = async (plans: FilePlan[], context: CallerContext) => {
+ for (const plan of plans)
+ for (const entry of plan.cases) {
+ const word = entry.forwardedParam;
+ if (!word) continue;
+ const own = context.extractions[plan.file]?.head.file ?? plan.file;
+ const files = (await context.grep(word)).filter((file) => file !== own);
+ const unchecked = files.filter((file) => !checked(file, word, context));
+ if (unchecked.length)
+ entry.flags = [...entry.flags, `FORWARDED_CALLER_UNCHECKED:${unchecked.join(',')}`].sort();
+ }
+};
diff --git a/packages/style-equivalence/src/pipeline/synthesize.ts b/packages/style-equivalence/src/pipeline/synthesize.ts
new file mode 100644
index 00000000000..0f0644c2609
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/synthesize.ts
@@ -0,0 +1,139 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { ProjectConfig } from '../config';
+import { extractFile, type FileExtraction } from '../extract';
+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 { packageFile } from '../source/aliases';
+import { resolveSpecifier } from '../source/declarations';
+import type { ScopeFile } from '../source/scope';
+import { fileFlags } from '../verdict/fileItems';
+import { fileReader, flagUncheckedCallers, gitGrepWord } from './forwardCallers';
+import { markUnchangedChains } from './unchanged';
+
+export const HOST_DIR = '.style-equivalence-host';
+export const RUNTIME = path.resolve(import.meta.dirname, '../generate/hostRuntime.tsx');
+
+const empty = (file: string): FileExtraction => ({
+ elements: [],
+ file,
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ styleSymbols: [],
+});
+
+export const moduleReader =
+ (root: string, aliases: Record<string, string>) => (fromFile: string, specifier: string) => {
+ const file = resolveSpecifier(root, fromFile, specifier, aliases);
+ return file && /\.[cm]?[jt]sx?$/.test(file)
+ ? readFileSync(path.join(root, file), 'utf8')
+ : undefined;
+ };
+
+export const stylesheetReader =
+ (root: string, aliases: Record<string, string> = {}) =>
+ (fromFile: string, specifier: string) => {
+ const local = resolveSpecifier(root, fromFile, specifier, aliases);
+ const target = local ? path.join(root, local) : packageFile(root, fromFile, specifier);
+ return target && existsSync(target) ? readFileSync(target, 'utf8') : undefined;
+ };
+
+export interface Synthesis {
+ extractions: Record<string, Record<Side, FileExtraction>>;
+ plans: FilePlan[];
+}
+
+export const synthesize = async (
+ scope: ScopeFile[],
+ roots: Record<Side, string>,
+ config: ProjectConfig,
+): Promise<Synthesis> => {
+ const extractions: Synthesis['extractions'] = {};
+ const plans: FilePlan[] = [];
+ const planned: Array<{ file: string; pair: Record<Side, FileExtraction>; plan: FilePlan }> = [];
+ for (const entry of scope) {
+ const file = entry.head ?? entry.base!;
+ 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, {
+ adapters: config.adapters,
+ layoutComponents: config.layoutComponents,
+ readBaseModule: side === 'head' ? moduleReader(roots.base, config.aliases) : undefined,
+ readModule: moduleReader(roots[side], config.aliases),
+ readStylesheet: stylesheetReader(roots[side], config.aliases),
+ realComponents: config.realComponents,
+ });
+ };
+ const pair = { base: await read('base'), head: await read('head') };
+ const plan = planFile(file, pair.base, pair.head, config);
+ markUnchangedChains(plan, pair, {
+ aliases: config.aliases,
+ roots,
+ sources: { base: entry.base, head: entry.head },
+ });
+ planned.push({ file, pair, plan });
+ }
+ const carried = carriedClasses(planned.flatMap(({ pair }) => [pair.base, pair.head]));
+ for (const { file, pair, plan } of planned) {
+ const global = globalRulesChanged(pair.base, pair.head, carried);
+ if (global) plan.gaps.push(global);
+ if (!plan.cases.length && !plan.unpaired.length && !fileFlags(plan, pair).length) continue;
+ extractions[file] = pair;
+ plans.push(plan);
+ }
+ await flagUncheckedCallers(plans, {
+ extractions,
+ grep: gitGrepWord(roots.head),
+ read: fileReader(roots.head),
+ });
+ return { extractions, plans };
+};
+
+export const syntheticPath = (source: string) =>
+ path.join(path.dirname(source), `__style_equivalence__${path.basename(source)}`);
+
+export const writeHost = async (
+ side: Side,
+ root: string,
+ synthesis: Synthesis,
+ scope: ScopeFile[],
+ config: ProjectConfig,
+ configDir: string,
+) => {
+ const host = path.join(root, HOST_DIR);
+ await rm(host, { force: true, recursive: true });
+ await mkdir(host, { recursive: true });
+ const modules: Array<{ file: string; specifier: string }> = [];
+ 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;
+ const target = path.join(root, syntheticPath(source));
+ await writeFile(
+ target,
+ generateModule(synthesis.extractions[plan.file][side], plan, side, config),
+ );
+ written.push(target);
+ modules.push({ file: plan.file, specifier: target });
+ }
+ await writeFile(path.join(host, 'index.html'), HOST_HTML);
+ await writeFile(path.join(host, 'plan.json'), JSON.stringify(synthesis.plans));
+ await writeFile(
+ path.join(host, 'entry.tsx'),
+ generateHost({
+ hostWrapper: path.resolve(configDir, config.hostWrapper),
+ modules,
+ runtime: RUNTIME,
+ themeAttribute: config.conditions.themeAttribute,
+ }),
+ );
+ return { host, written };
+};
diff --git a/packages/style-equivalence/src/pipeline/unchanged.test.ts b/packages/style-equivalence/src/pipeline/unchanged.test.ts
new file mode 100644
index 00000000000..27968cc7a5d
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/unchanged.test.ts
@@ -0,0 +1,135 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile, type Side } from '../plan/planFile';
+import { moduleReader } from './synthesize';
+import { markUnchangedChains } from './unchanged';
+
+const COMPONENT = `import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+import { styles } from './styles';
+
+export const Quote = ({ clickable, xstyle }) => (
+ <Flexbox {...stylex.props(styles.quote, clickable && styles.clickable, xstyle)}>
+ <span className={stylex.props(styles.label).className} />
+ </Flexbox>
+);
+`;
+
+const STYLES = (
+ quote = 'padding: SPACE',
+ space = "'4px'",
+ extra = '',
+) => `import * as stylex from '@stylexjs/stylex';
+${extra}
+const SPACE = ${space};
+
+export const styles = stylex.create({
+ clickable: { cursor: 'pointer' },
+ label: { fontSize: '12px' },
+ quote: { ${quote} },
+});
+`;
+
+const FALLBACK = `import { createStaticStyles } from '@lobehub/ui';
+
+export const fallback = createStaticStyles(({ css }) => ({
+ editor: css\`p { margin: 0; }\`,
+}));
+`;
+
+let root: string;
+const roots = () => ({ base: path.join(root, 'base'), head: path.join(root, 'head') });
+
+const write = async (side: Side, file: string, text: string) => {
+ const target = path.join(roots()[side], file);
+ await mkdir(path.dirname(target), { recursive: true });
+ await writeFile(target, text);
+};
+
+const plan = async (head: { component?: string; styles?: string }, base = COMPONENT) => {
+ await write('base', 'src/Quote.tsx', base);
+ await write('base', 'src/styles.ts', STYLES());
+ await write('head', 'src/Quote.tsx', head.component ?? COMPONENT);
+ await write('head', 'src/styles.ts', head.styles ?? STYLES(undefined, undefined, FALLBACK));
+ const extract = (side: Side, code: string) =>
+ extractFile(code, 'src/Quote.tsx', {
+ adapters: [emotionStaticAdapter, stylexAdapter],
+ layoutComponents: ['Flexbox'],
+ readModule: moduleReader(roots()[side], {}),
+ });
+ const pair = {
+ base: extract('base', base),
+ head: extract('head', head.component ?? COMPONENT),
+ };
+ const result = planFile('src/Quote.tsx', pair.base, pair.head, { layoutComponents: ['Flexbox'] });
+ markUnchangedChains(result, pair, {
+ aliases: {},
+ roots: roots(),
+ sources: { base: 'src/Quote.tsx', head: 'src/Quote.tsx' },
+ });
+ return result.cases;
+};
+
+beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-unchanged-'));
+});
+
+afterEach(async () => {
+ await rm(root, { force: true, recursive: true });
+});
+
+describe('an element whose own style chain did not change', () => {
+ it('needs no sign-off for an unmodeled variable when only an unrelated export was added', async () => {
+ const cases = await plan({});
+ expect(cases.map((entry) => [entry.flags, entry.evidence])).toEqual([
+ [[], ['STYLE_CHAIN_UNCHANGED', 'FILE_RULES_UNCHANGED']],
+ [[], ['STYLE_CHAIN_UNCHANGED', 'FILE_RULES_UNCHANGED']],
+ ]);
+ });
+
+ it('keeps the flag when a declaration the element reads changed', async () => {
+ const [entry] = await plan({ styles: STYLES("padding: '8px'") });
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when a constant the declaration reads changed', async () => {
+ const [entry] = await plan({ styles: STYLES(undefined, "'6px'") });
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when the element binding changed', async () => {
+ const [entry] = await plan({
+ component: COMPONENT.replace(', xstyle)}', ', xstyle, styles.label)}'),
+ });
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ const inner = (other: string) => `import { createStaticStyles } from '@lobehub/ui';
+
+const local = createStaticStyles(({ css }) => ({
+ other: css\`${other}\`,
+ x: css\`&.ant-btn { margin: 0; }\`,
+}));
+
+export const Quote = () => <div className={local.x} />;
+`;
+
+ it('clears any flag when the file rules are unchanged too', async () => {
+ const cases = await plan({ component: inner('p { margin: 0; }') }, inner('p { margin: 0; }'));
+ expect(cases[0].flags).toEqual([]);
+ expect(cases[0].evidence).toContain('FILE_RULES_UNCHANGED');
+ });
+
+ it('keeps a flag beyond unmodeled variables when other rules of the file changed', async () => {
+ const cases = await plan({ component: inner('p { margin: 1px; }') }, inner('p { margin: 0; }'));
+ expect(cases[0].flags).toEqual(['CROSS_COMPONENT']);
+ });
+});
diff --git a/packages/style-equivalence/src/pipeline/unchanged.ts b/packages/style-equivalence/src/pipeline/unchanged.ts
new file mode 100644
index 00000000000..1f1022fba5f
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/unchanged.ts
@@ -0,0 +1,128 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import ts from 'typescript';
+
+import type { FileExtraction } from '../extract';
+import { valueIdentifierNodes } from '../extract/identifiers';
+import { elementsOf } from '../plan/descendants';
+import { chainOf, type FilePlan, type Side } from '../plan/planFile';
+import {
+ declarationText,
+ findStyleMember,
+ parseSource,
+ resolveSlot,
+ type SlotSite,
+} from '../source/declarations';
+
+export const CHAIN_CLEARABLE = new Set(['COMBINATIONS_PAIRWISE', 'VARIABLE_UNMODELED']);
+
+const CALLER_FLAGS = ['FORWARDED_CALLER_UNCHECKED', 'INNER_TARGET_PARTLY_FORWARDED'];
+
+const MAX_DEPTH = 4;
+
+const topLevelOf = (sf: ts.SourceFile) => {
+ const statements = new Map<string, ts.Statement>();
+ for (const statement of sf.statements) {
+ if (ts.isImportDeclaration(statement)) {
+ const clause = statement.importClause;
+ if (clause?.name) statements.set(clause.name.text, statement);
+ const named = clause?.namedBindings;
+ if (named && ts.isNamespaceImport(named)) statements.set(named.name.text, statement);
+ if (named && ts.isNamedImports(named))
+ for (const element of named.elements) statements.set(element.name.text, statement);
+ }
+ if (ts.isVariableStatement(statement))
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name)) statements.set(declaration.name.text, statement);
+ if ((ts.isFunctionDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name)
+ statements.set(statement.name.text, statement);
+ }
+ return statements;
+};
+
+export const slotClosure = (site: SlotSite) => {
+ if (site.css) return declarationText(site);
+ const sf = parseSource(site.code);
+ const member = findStyleMember(sf, site.symbol, site.member);
+ if (!member) return undefined;
+ const statements = topLevelOf(sf);
+ const texts = [member.getText(sf)];
+ const seen = new Set<ts.Statement>();
+ const visit = (node: ts.Node, depth: number) => {
+ for (const identifier of valueIdentifierNodes(node)) {
+ if (identifier.text === site.symbol) continue;
+ const statement = statements.get(identifier.text);
+ if (!statement || seen.has(statement)) continue;
+ if (depth >= MAX_DEPTH) return false;
+ seen.add(statement);
+ texts.push(statement.getText(sf));
+ if (!ts.isImportDeclaration(statement) && visit(statement, depth + 1) === false) return false;
+ }
+ return true;
+ };
+ return visit(member, 0) ? texts.join('\n') : undefined;
+};
+
+const chainSignature = (extraction: FileExtraction, id: string) => {
+ const byId = new Map(elementsOf(extraction).map((element) => [element.id, element]));
+ const element = byId.get(id);
+ if (!element) return undefined;
+ const chain = chainOf(element, byId);
+ return {
+ slots: [...new Set(chain.flatMap((item) => item.slots))].sort(),
+ text: JSON.stringify(
+ chain.map(
+ ({ flags: _flags, id: _id, parent: _parent, children: _children, ...item }) => item,
+ ),
+ ),
+ };
+};
+
+export interface UnchangedContext {
+ aliases: Record<string, string>;
+ roots: Record<Side, string>;
+ sources: Partial<Record<Side, string>>;
+}
+
+export const markUnchangedChains = (
+ plan: FilePlan,
+ pair: Record<Side, FileExtraction>,
+ context: UnchangedContext,
+) => {
+ const { base: baseSource, head: headSource } = context.sources;
+ if (!baseSource || !headSource) return;
+ const codes = {
+ base: readFileSync(path.join(context.roots.base, baseSource), 'utf8'),
+ head: readFileSync(path.join(context.roots.head, headSource), 'utf8'),
+ };
+ const closure = (side: Side, slot: string) => {
+ const source = side === 'base' ? baseSource : headSource;
+ const sites = resolveSlot(context.roots[side], source, codes[side], slot, context.aliases);
+ const texts = sites.map(slotClosure);
+ return sites.length && texts.every((text) => text !== undefined) ? texts.join('\n') : undefined;
+ };
+ const sameRules =
+ JSON.stringify([pair.base.rules, pair.base.globalRules ?? [], pair.base.gaps]) ===
+ JSON.stringify([pair.head.rules, pair.head.globalRules ?? [], pair.head.gaps]);
+ for (const entry of plan.cases) {
+ if (entry.flags.some((flag) => CALLER_FLAGS.some((prefix) => flag.startsWith(prefix))))
+ continue;
+ if (!sameRules && !entry.flags.every((flag) => CHAIN_CLEARABLE.has(flag))) continue;
+ const left = chainSignature(pair.base, entry.elementIds.base);
+ const right = chainSignature(pair.head, entry.elementIds.head);
+ if (!left || !right || left.text !== right.text) continue;
+ const same = left.slots.every((slot) => {
+ const before = closure('base', slot);
+ return before !== undefined && before === closure('head', slot);
+ });
+ if (!same) continue;
+ if (!entry.flags.length && !sameRules) continue;
+ entry.flags = [];
+ entry.evidence = [
+ ...(entry.evidence ?? []),
+ 'STYLE_CHAIN_UNCHANGED',
+ ...(sameRules ? ['FILE_RULES_UNCHANGED'] : []),
+ ];
+ }
+};
diff --git a/packages/style-equivalence/src/plan/combos.ts b/packages/style-equivalence/src/plan/combos.ts
new file mode 100644
index 00000000000..9cac8ad0a7f
--- /dev/null
+++ b/packages/style-equivalence/src/plan/combos.ts
@@ -0,0 +1,71 @@
+export type Combo = Record<string, boolean | string>;
+
+export const FULL_ENUMERATION_LIMIT = 4;
+
+export const fullCombos = (names: string[]): Combo[] => {
+ const combos: Combo[] = [];
+ for (let mask = 0; mask < 2 ** names.length; mask++)
+ combos.push(
+ Object.fromEntries(names.map((name, index) => [name, Boolean(mask & (1 << index))])),
+ );
+ return combos;
+};
+
+export const pairwiseCombos = (names: string[]): Combo[] => {
+ const uncovered = new Set<string>();
+ const key = (i: number, vi: boolean, j: number, vj: boolean) => `${i}:${+vi}|${j}:${+vj}`;
+ for (let i = 0; i < names.length; i++)
+ for (let j = i + 1; j < names.length; j++)
+ for (const vi of [false, true])
+ for (const vj of [false, true]) uncovered.add(key(i, vi, j, vj));
+ const cover = (values: boolean[]) => {
+ for (let i = 0; i < values.length; i++)
+ for (let j = i + 1; j < values.length; j++) uncovered.delete(key(i, values[i], j, values[j]));
+ };
+ const rows: boolean[][] = [];
+ while (uncovered.size) {
+ const [first] = uncovered;
+ const [left, right] = first.split('|').map((part) => part.split(':').map(Number));
+ const values: boolean[] = names.map(() => false);
+ values[left[0]] = Boolean(left[1]);
+ values[right[0]] = Boolean(right[1]);
+ for (let index = 0; index < names.length; index++) {
+ if (index === left[0] || index === right[0]) continue;
+ let best = false;
+ let bestGain = -1;
+ for (const candidate of [false, true]) {
+ values[index] = candidate;
+ let gain = 0;
+ for (let other = 0; other < names.length; other++) {
+ if (other === index) continue;
+ const [i, j] = other < index ? [other, index] : [index, other];
+ if (uncovered.has(key(i, values[i], j, values[j]))) gain++;
+ }
+ if (gain > bestGain) {
+ bestGain = gain;
+ best = candidate;
+ }
+ }
+ values[index] = best;
+ }
+ cover(values);
+ rows.push(values);
+ }
+ return rows.map((values) =>
+ Object.fromEntries(names.map((name, index) => [name, values[index]])),
+ );
+};
+
+export const DOMAIN_COMBO_LIMIT = 64;
+
+export const combosFor = (names: string[], domains: Record<string, string[]> = {}) => {
+ const flags = names.filter((name) => !domains[name]);
+ const pairwise = flags.length > FULL_ENUMERATION_LIMIT;
+ let combos = pairwise ? pairwiseCombos(flags) : fullCombos(flags);
+ for (const name of names)
+ if (domains[name])
+ combos = combos.flatMap((combo) =>
+ domains[name].map((value) => ({ ...combo, [name]: value })),
+ );
+ return { combos, pairwise };
+};
diff --git a/packages/style-equivalence/src/plan/descendants.test.ts b/packages/style-equivalence/src/plan/descendants.test.ts
new file mode 100644
index 00000000000..e3632e59d4f
--- /dev/null
+++ b/packages/style-equivalence/src/plan/descendants.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const base = (summary = '<summary>Raw</summary>', rule = 'summary { cursor: pointer; }') => `
+import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ rawDetails: css\`
+ font-size: 12px;
+ ${rule}
+ \`,
+}));
+
+export const Render = () => (
+ <details className={styles.rawDetails}>
+ ${summary}
+ <Highlighter language="json">{json}</Highlighter>
+ </details>
+);
+`;
+
+const head = (summary = '<summary {...stylex.props(styles.rawSummary)}>Raw</summary>') => `
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ rawDetails: { fontSize: '12px' },
+ rawSummary: { cursor: 'pointer' },
+});
+
+export const Render = () => (
+ <details {...stylex.props(styles.rawDetails)}>
+ ${summary}
+ <Highlighter language="json">{json}</Highlighter>
+ </details>
+);
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: ['Flexbox'],
+ });
+
+describe('a new element that replaces a descendant selector', () => {
+ it('records the direct children and subtree tags of a styled element', () => {
+ const extraction = extractFile(base(), 'a.tsx', options);
+ expect(extraction.elements[0].children).toEqual(['Render#0/0', 'Render#0/1']);
+ expect(extraction.elements[0].subtreeTags).toEqual({ summary: 1 });
+ expect(extraction.plain?.map(({ id, tag }) => [id, tag])).toEqual([
+ ['Render#0/0', 'summary'],
+ ['Render#0/1', 'Highlighter'],
+ ]);
+ });
+
+ it('pairs the styled child with the plain child the parent rule targeted and clears the parent', () => {
+ const result = plan(base(), head());
+ expect(result.unpaired).toEqual([]);
+ expect(result.cases.map((entry) => [entry.key, entry.flags, entry.evidence])).toEqual([
+ ['a.tsx|Render#0', [], ['DESCENDANT_RENDERED']],
+ ['a.tsx|Render#0/0', [], ['DESCENDANT_REPLACED']],
+ ]);
+ expect(result.cases[1].elementIds).toEqual({ base: 'Render#0/0', head: 'Render#1' });
+ });
+
+ it('pairs a child that a universal child rule targeted', () => {
+ const result = plan(base(undefined, '> * { cursor: pointer; }'), head());
+ expect(result.unpaired).toEqual([]);
+ expect(result.cases[1].evidence).toEqual(['DESCENDANT_REPLACED']);
+ });
+
+ it('leaves the child unpaired when no parent rule targets it', () => {
+ const result = plan(base(undefined, 'span { cursor: pointer; }'), head());
+ expect(result.unpaired).toEqual([{ elementId: 'Render#1', side: 'head' }]);
+ expect(result.cases[0].flags).toEqual(['INNER_TARGET']);
+ });
+
+ it('leaves the child unpaired when its attributes differ', () => {
+ const result = plan(
+ base('<summary title="a">Raw</summary>'),
+ head('<summary title="b" {...stylex.props(styles.rawSummary)}>Raw</summary>'),
+ );
+ expect(result.unpaired).toEqual([{ elementId: 'Render#1', side: 'head' }]);
+ });
+
+ it('leaves the child unpaired when it carries a class the tool cannot read', () => {
+ const result = plan(base('<summary className={extra}>Raw</summary>'), head());
+ expect(result.unpaired).toEqual([{ elementId: 'Render#1', side: 'head' }]);
+ });
+
+ it('keeps the parent flagged when the rule also reaches a deeper element of that tag', () => {
+ const result = plan(
+ base('<summary>Raw</summary><div><summary>Nested</summary></div>'),
+ head(
+ '<summary {...stylex.props(styles.rawSummary)}>Raw</summary><div><summary>Nested</summary></div>',
+ ),
+ );
+ expect(result.cases[0].flags).toEqual(['INNER_TARGET']);
+ expect(result.cases[1].flags).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/descendants.ts b/packages/style-equivalence/src/plan/descendants.ts
new file mode 100644
index 00000000000..380ac1a6d54
--- /dev/null
+++ b/packages/style-equivalence/src/plan/descendants.ts
@@ -0,0 +1,132 @@
+import type { FileExtraction, StyleElement, StyleRule } from '../extract';
+import { targetsInnerTag } from '../extract/selectors';
+import { parseSelectorList, type SelectorNode } from './selectorTree';
+
+interface Step {
+ child: boolean;
+ tag: string;
+}
+
+const sortedJson = (value: Record<string, unknown>) =>
+ JSON.stringify(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
+
+export const elementsOf = (extraction: FileExtraction) => [
+ ...extraction.elements,
+ ...(extraction.plain ?? []),
+];
+
+const scopeNames = (rule: StyleRule, element: StyleElement) =>
+ new Set(
+ Object.entries(rule.owned)
+ .filter(([, slot]) => element.slots.includes(slot))
+ .map(([name]) => name),
+ );
+
+const stepOf = (nodes: SelectorNode[], scopes: Set<string>): Step | undefined => {
+ const [scope, combinator, target] = nodes;
+ if (
+ nodes.length !== 3 ||
+ scope.type !== 'class' ||
+ !scopes.has(scope.value ?? '') ||
+ combinator.type !== 'combinator' ||
+ ![' ', '>'].includes(combinator.value?.trim() || ' ') ||
+ (target.type !== 'tag' && target.type !== 'universal')
+ )
+ return undefined;
+ return { child: combinator.value?.trim() === '>', tag: target.value ?? '*' };
+};
+
+const stepsOf = (rule: StyleRule, scopes: Set<string>): Step[] | undefined => {
+ const steps = parseSelectorList(rule.selector)?.map((nodes) => stepOf(nodes, scopes));
+ return steps?.every(Boolean) ? (steps as Step[]) : undefined;
+};
+
+const rulesOf = (element: StyleElement, rules: StyleRule[]) =>
+ rules.flatMap((rule) => {
+ const scopes = scopeNames(rule, element);
+ return scopes.size ? [{ rule, scopes }] : [];
+ });
+
+const targets = (parent: StyleElement, tag: string, rules: StyleRule[]) =>
+ rulesOf(parent, rules).some(({ rule, scopes }) =>
+ stepsOf(rule, scopes)?.some((step) => step.tag === '*' || step.tag === tag),
+ );
+
+export const innerSteps = (parent: StyleElement, rules: StyleRule[]) => {
+ const steps: Step[] = [];
+ for (const { rule, scopes } of rulesOf(parent, rules)) {
+ if (!targetsInnerTag(rule.selector)) continue;
+ const parsed = stepsOf(rule, scopes);
+ if (!parsed) return undefined;
+ steps.push(...parsed.filter((step) => step.tag !== '*'));
+ }
+ return steps;
+};
+
+export const counterparts = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Array<[StyleElement, StyleElement]>,
+) => {
+ 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 tagsOf = (ids: string[], byId: Map<string, StyleElement>) =>
+ JSON.stringify(ids.map((id) => byId.get(id)?.tag));
+ return (element: StyleElement) => {
+ const parent = element.parent ? pairedParent.get(element.parent) : undefined;
+ const headParent = element.parent ? headById.get(element.parent) : undefined;
+ if (!parent || !headParent) return undefined;
+ const baseChildren = parent.children ?? [];
+ const headChildren = headParent.children ?? [];
+ if (tagsOf(baseChildren, baseById) !== tagsOf(headChildren, headById)) return undefined;
+ const counterpart = baseById.get(baseChildren[headChildren.indexOf(element.id)]);
+ return counterpart &&
+ !counterpart.bindings.length &&
+ !counterpart.flags.length &&
+ counterpart.tag === element.tag &&
+ sortedJson(counterpart.literalProps) === sortedJson(element.literalProps) &&
+ sortedJson(counterpart.attributes ?? {}) === sortedJson(element.attributes ?? {})
+ ? { counterpart, parent }
+ : undefined;
+ };
+};
+
+export const replacedDescendants = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Array<[StyleElement, StyleElement]>,
+ unpairedHead: StyleElement[],
+) => {
+ const lookup = counterparts(base, head, pairs);
+ const replaced: Array<[StyleElement, StyleElement]> = [];
+ for (const element of unpairedHead) {
+ const found = lookup(element);
+ if (found && targets(found.parent, found.counterpart.tag, base.rules))
+ replaced.push([found.counterpart, element]);
+ }
+ return replaced;
+};
+
+export const parentCovered = (
+ parent: StyleElement,
+ base: FileExtraction,
+ rendered: Set<string>,
+) => {
+ 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);
+ if (direct.some((child) => !rendered.has(child!.id))) return false;
+ return step.child || (parent.subtreeTags?.[step.tag] ?? 0) === direct.length;
+ });
+};
+
+export const childCovered = (parent: StyleElement, child: StyleElement, rules: StyleRule[]) => {
+ const steps = innerSteps(parent, rules);
+ return (
+ !!steps?.length && steps.every((step) => step.child || !(child.subtreeTags?.[step.tag] ?? 0))
+ );
+};
diff --git a/packages/style-equivalence/src/plan/droppedStyle.test.ts b/packages/style-equivalence/src/plan/droppedStyle.test.ts
new file mode 100644
index 00000000000..86c7f45a248
--- /dev/null
+++ b/packages/style-equivalence/src/plan/droppedStyle.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const base = (lane = '<div className={styles.lane} style={laneStyle} />') => `
+import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ lane: css\`display: flex;\` }));
+
+export const Layout = ({ laneStyle, size }) => ${lane};
+`;
+
+const head = (lane = '<div {...stylex.props(styles.lane)} />') => `
+import * as stylex from '@stylexjs/stylex';
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({ lane: { display: 'flex' } });
+
+export const Layout = ({ laneStyle, size }) => ${lane};
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: ['Flexbox'],
+ }).cases;
+
+describe('a runtime style present on one side only', () => {
+ it('records the style expression even beside a spread', () => {
+ const [lane] = extractFile(
+ head('<div {...stylex.props(styles.lane)} style={laneStyle} />'),
+ 'a.tsx',
+ options,
+ ).elements;
+ expect(lane.styleExpr).toBe('laneStyle');
+ expect(lane.runtimeStyle).toBeUndefined();
+ });
+
+ it('flags a style the head drops entirely', () => {
+ expect(plan(base(), head())[0].flags).toEqual(['RUNTIME_STYLE_DROPPED']);
+ });
+
+ it('flags a style only the head passes', () => {
+ const cases = plan(
+ base('<div className={styles.lane} />'),
+ head('<div {...stylex.props(styles.lane)} style={laneStyle} />'),
+ );
+ expect(cases[0].flags).toEqual(['RUNTIME_STYLE_DROPPED']);
+ });
+
+ it('flags a dropped style object that reads runtime values', () => {
+ const cases = plan(base('<div className={styles.lane} style={{ width: size }} />'), head());
+ expect(cases[0].flags).toEqual(['RUNTIME_STYLE_DROPPED']);
+ });
+
+ it('does not flag a style both sides keep', () => {
+ const cases = plan(base(), head('<div {...stylex.props(styles.lane)} style={laneStyle} />'));
+ expect(cases[0].flags).toEqual([]);
+ });
+
+ it('does not flag a style the head moves into its style call', () => {
+ const cases = plan(base(), head('<div {...sx(styles.lane, undefined, laneStyle)} />'));
+ expect(cases[0].flags).toEqual([]);
+ expect(cases[0].evidence).toEqual(['RUNTIME_STYLE_PROBED']);
+ });
+
+ it('leaves a static style object to the rendered comparison', () => {
+ const before = base('<div className={styles.lane} style={{ fontSize: 18, margin: 0 }} />');
+ const [lane] = extractFile(before, 'a.tsx', options).elements;
+ expect(lane.literalProps.style).toEqual({ fontSize: 18, margin: 0 });
+ expect(lane.styleExpr).toBeUndefined();
+ expect(plan(before, head())[0].flags).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/forwarded.test.ts b/packages/style-equivalence/src/plan/forwarded.test.ts
new file mode 100644
index 00000000000..ccaee78935f
--- /dev/null
+++ b/packages/style-equivalence/src/plan/forwarded.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import type { RealComponent } from '../extract/types';
+import { generateModule } from '../generate/module';
+import { planFile } from './planFile';
+
+const realComponents: Record<string, RealComponent> = {
+ Text: { source: '@lobehub/ui', tag: { default: 'div', prop: 'as' } },
+};
+
+const component = (title: string) => `
+import { createStaticStyles, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { Heading } from './Heading';
+
+const styles = createStaticStyles(({ css }) => ({ titleRow: css\`gap: 10px;\` }));
+
+const AcceptanceIdentity = ({ titleXstyle }) => {
+ const { data } = useBundle();
+ if (!data) return null;
+ return (
+ <Flexbox gap={10}>
+ <Flexbox horizontal className={styles.titleRow}>
+ ${title}
+ </Flexbox>
+ <PullRequestLinks />
+ </Flexbox>
+ );
+};
+
+export default AcceptanceIdentity;
+`;
+
+const TEXT = `<Text ellipsis as={'h1'} style={{ fontSize: 18, margin: 0 }}>{data.title}</Text>`;
+const FORWARDED = `<Text ellipsis as={'h1'} className={stylex.props(titleXstyle).className} style={{ fontSize: 18, margin: 0 }}>{data.title}</Text>`;
+
+const caller = {
+ base: (rule = 'h1 { overflow: visible; white-space: normal; }') => `
+import { createStaticStyles, Flexbox } from '@lobehub/ui';
+import AcceptanceIdentity from './AcceptanceIdentity';
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css\`
+ width: 100%;
+ ${rule}
+ \`,
+}));
+
+export const EmbedContent = () => (
+ <Flexbox className={styles.content} gap={24}>
+ <AcceptanceIdentity />
+ <AcceptanceGoal />
+ </Flexbox>
+);
+`,
+ head: () => `
+import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import AcceptanceIdentity from './AcceptanceIdentity';
+
+const styles = stylex.create({
+ content: { width: '100%' },
+ title: { overflow: 'visible', whiteSpace: 'normal' },
+});
+
+export const EmbedContent = () => (
+ <Flexbox className={stylex.props(styles.content).className} gap={24}>
+ <AcceptanceIdentity titleXstyle={styles.title} />
+ <AcceptanceGoal />
+ </Flexbox>
+);
+`,
+};
+
+const options = (modules: { base: string; head: string }) => ({
+ adapters: [emotionStaticAdapter, stylexAdapter],
+ layoutComponents: ['Flexbox'],
+ readBaseModule: (_from: string, specifier: string) =>
+ specifier === './AcceptanceIdentity' ? modules.base : undefined,
+ readModule: (_from: string, specifier: string) =>
+ specifier === './AcceptanceIdentity' ? modules.head : undefined,
+ realComponents,
+});
+
+const config = { layoutComponents: ['Flexbox'], realComponents };
+
+const callerPlan = (
+ modules = { base: component(TEXT), head: component(FORWARDED) },
+ rule?: string,
+) => {
+ const extractions = {
+ base: extractFile(caller.base(rule), 'a.tsx', options(modules)),
+ head: extractFile(caller.head(), 'a.tsx', options(modules)),
+ };
+ return { extractions, plan: planFile('a.tsx', extractions.base, extractions.head, config) };
+};
+
+describe('a style forwarded into our own component, seen from the caller', () => {
+ it('pairs the forwarded prop with the plain child the descendant rule targeted', () => {
+ const { plan } = callerPlan();
+ expect(plan.unpaired).toEqual([]);
+ const forwarded = plan.cases.find((entry) => entry.forward)!;
+ expect(forwarded.elementIds).toEqual({ base: 'EmbedContent#0/0', head: 'EmbedContent#1' });
+ expect(forwarded.flags).toEqual([]);
+ expect(forwarded.evidence).toEqual(['FORWARDED_RENDERED']);
+ expect(forwarded.forward).toMatchObject({
+ application: 'props',
+ base: { attributes: { as: 'h1', ellipsis: true }, tag: 'Text' },
+ head: { attributes: { as: 'h1', ellipsis: true }, tag: 'Text' },
+ prop: 'titleXstyle',
+ });
+ });
+
+ it('keeps the parent flagged and names the components it did not prove', () => {
+ const { plan } = callerPlan();
+ expect(plan.cases[0].flags).toEqual([
+ 'INNER_TARGET',
+ 'INNER_TARGET_PARTLY_FORWARDED:h1|AcceptanceGoal,AcceptanceIdentity',
+ ]);
+ });
+
+ it('renders the real target element with the forwarded class on the head side', () => {
+ const { extractions, plan } = callerPlan();
+ const head = generateModule(extractions.head, plan, 'head', config);
+ const base = generateModule(extractions.base, plan, 'base', config);
+ expect(head).toContain('import { Text as __forward_Text } from "@lobehub/ui";');
+ expect(head).toContain('className={__stylex.props(styles.title).className}');
+ expect(head).toMatch(
+ /<__forward_Text data-synthetic-element="EmbedContent#1" ellipsis=\{true\} as="h1"/,
+ );
+ expect(base).toMatch(
+ /<__forward_Text data-synthetic-element="EmbedContent#0\/0" ellipsis=\{true\} as="h1"/,
+ );
+ expect(base).not.toContain('__stylex.props');
+ });
+
+ it('leaves the child unpaired when the component applies the prop twice', () => {
+ const { plan } = callerPlan({
+ base: component(TEXT),
+ head: component(`${FORWARDED}<h2 className={stylex.props(titleXstyle).className} />`),
+ });
+ expect(plan.unpaired).toEqual([{ elementId: 'EmbedContent#1', side: 'head' }]);
+ expect(plan.cases[0].flags).toEqual(['INNER_TARGET']);
+ });
+
+ it('leaves the child unpaired when the base rule only reaches direct children', () => {
+ const { plan } = callerPlan(undefined, '> h1 { overflow: visible; }');
+ expect(plan.unpaired).toEqual([{ elementId: 'EmbedContent#1', side: 'head' }]);
+ });
+
+ it('leaves the child unpaired when the target is rendered by yet another own component', () => {
+ const heading = (props: string) => `<Heading as={'h1'} ${props}>{data.title}</Heading>`;
+ const { plan } = callerPlan({
+ base: component(heading('')),
+ head: component(heading('className={stylex.props(titleXstyle).className}')),
+ });
+ expect(plan.unpaired).toEqual([{ elementId: 'EmbedContent#1', side: 'head' }]);
+ });
+
+ it('leaves the child unpaired when the base selector is not a plain descendant', () => {
+ const { plan } = callerPlan(undefined, '&:hover h1 { overflow: visible; }');
+ expect(plan.unpaired).toEqual([{ elementId: 'EmbedContent#1', side: 'head' }]);
+ });
+});
+
+describe('a style forwarded into our own component, seen from inside', () => {
+ const inside = (head: string) => {
+ const extract = (code: string) =>
+ extractFile(code, 'Identity.tsx', {
+ adapters: [emotionStaticAdapter, stylexAdapter],
+ layoutComponents: ['Flexbox'],
+ realComponents,
+ });
+ return planFile('Identity.tsx', extract(component(TEXT)), extract(head), config);
+ };
+
+ it('pairs the element with its plain counterpart and renders it with the prop absent', () => {
+ const plan = inside(component(FORWARDED));
+ expect(plan.unpaired).toEqual([]);
+ const entry = plan.cases.find((item) => item.forwardedParam)!;
+ expect(entry.elementIds).toEqual({
+ base: 'AcceptanceIdentity#0/0',
+ head: 'AcceptanceIdentity#1',
+ });
+ expect(entry.flags).toEqual([]);
+ expect(entry.variables).toEqual([]);
+ expect(entry.evidence).toEqual(['FORWARDED_PROP_ABSENT', 'REAL_COMPONENT_RENDERED']);
+ });
+
+ it('leaves the element unpaired when the prop is applied under a condition', () => {
+ const plan = inside(component(`{data.ok && ${FORWARDED}}`));
+ expect(plan.unpaired).toEqual([{ elementId: 'AcceptanceIdentity#1', side: 'head' }]);
+ });
+
+ it('leaves the element unpaired when the prop has a default', () => {
+ const plan = inside(
+ component(FORWARDED).replace('({ titleXstyle })', '({ titleXstyle = styles.titleRow })'),
+ );
+ expect(plan.unpaired).toEqual([{ elementId: 'AcceptanceIdentity#1', side: 'head' }]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/forwarded.ts b/packages/style-equivalence/src/plan/forwarded.ts
new file mode 100644
index 00000000000..a9a0e364f8c
--- /dev/null
+++ b/packages/style-equivalence/src/plan/forwarded.ts
@@ -0,0 +1,80 @@
+import type { FileExtraction, RealComponent, StyleElement } from '../extract';
+import type { ForwardApplication, ForwardElement } from '../extract/forward';
+import { counterparts, innerSteps } from './descendants';
+
+export interface ForwardPlan {
+ application: ForwardApplication;
+ base: ForwardElement;
+ head: ForwardElement;
+ prop: string;
+}
+
+type Pair = [StyleElement, StyleElement];
+
+export const renderedTag = (
+ element: ForwardElement,
+ real: Record<string, RealComponent> | undefined,
+) => {
+ if (!element.tagImport) return /^[a-z][\w-]*$/.test(element.tag) ? element.tag : undefined;
+ const component = real?.[element.tagImport.imported];
+ if (!component?.tag || component.source !== element.tagImport.source) return undefined;
+ const value = element.attributes[component.tag.prop];
+ if (value === undefined) return component.tag.default;
+ return typeof value === 'string' ? value : undefined;
+};
+
+export const forwardedDescendants = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Pair[],
+ unpairedHead: StyleElement[],
+ real: Record<string, RealComponent> | undefined,
+) => {
+ const lookup = counterparts(base, head, pairs);
+ const found: Array<{ forward: ForwardPlan; pair: Pair; parent: StyleElement; tag: string }> = [];
+ for (const element of unpairedHead) {
+ const [binding] = element.bindings;
+ if (element.bindings.length !== 1 || binding.spread) continue;
+ const target = element.forwards?.find((entry) => entry.prop === binding.prop)?.target;
+ if (!target?.base) continue;
+ const match = lookup(element);
+ const tag = renderedTag(target, real);
+ if (!match || !tag || renderedTag(target.base, real) !== tag) continue;
+ const steps = innerSteps(match.parent, base.rules);
+ const reaches = steps?.some((step) => !step.child && step.tag === tag);
+ if (!reaches || steps!.some((step) => step.child && step.tag === tag)) continue;
+ const { application, attributes, path, tag: targetTag, tagImport } = target;
+ found.push({
+ forward: {
+ application,
+ base: target.base,
+ head: { attributes, path, tag: targetTag, ...(tagImport ? { tagImport } : {}) },
+ prop: binding.prop,
+ },
+ pair: [match.counterpart, element],
+ parent: match.parent,
+ tag,
+ });
+ }
+ return found;
+};
+
+export const forwardedInside = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Pair[],
+ unpairedHead: StyleElement[],
+) => {
+ const lookup = counterparts(base, head, pairs);
+ return unpairedHead.flatMap((element) => {
+ const match = element.forwardedParam ? lookup(element) : undefined;
+ return match
+ ? [{ pair: [match.counterpart, element] as Pair, param: element.forwardedParam! }]
+ : [];
+ });
+};
+
+export const partlyForwarded = (parent: StyleElement, tag: string, layout: Set<string>) => {
+ const components = (parent.subtreeComponents ?? []).filter((name) => !layout.has(name));
+ return `INNER_TARGET_PARTLY_FORWARDED:${tag}|${components.join(',')}`;
+};
diff --git a/packages/style-equivalence/src/plan/globalRules.test.ts b/packages/style-equivalence/src/plan/globalRules.test.ts
new file mode 100644
index 00000000000..fd8faead0d6
--- /dev/null
+++ b/packages/style-equivalence/src/plan/globalRules.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../extract/adapters/globalCss';
+import { extractFile } from '../extract/index';
+import type { ExtractOptions } from '../extract/types';
+import { carriedClasses, globalRulesChanged } from './globalRules';
+
+const CSS = `::highlight(lobe-comment) {
+ text-decoration-color: var(--lobe-color-warning);
+ text-underline-offset: 3px;
+}
+
+::highlight(lobe-comment-active) {
+ background-color: var(--lobe-color-warning-border);
+}
+`;
+
+const REGISTRY = `export const REGISTRY = { active: 'lobe-comment-active', all: 'lobe-comment' } as const;\n`;
+
+const base = `import './Highlight.css';
+
+const HighlightStyle = () => null;
+
+export default HighlightStyle;
+`;
+
+const head = (
+ offset = '3px',
+ active = `::highlight(\${REGISTRY.active}) {
+ background-color: \${cssVar.colorWarningBorder};
+ }`,
+) => `import { createGlobalStyle, cssVar } from '@lobehub/ui';
+
+import { REGISTRY } from './highlights';
+
+const HighlightStyle = createGlobalStyle\`
+ ::highlight(\${REGISTRY.all}) {
+ text-decoration-color: \${cssVar.colorWarning};
+ text-underline-offset: ${offset};
+ }
+
+ ${active}
+\`;
+
+export default HighlightStyle;
+`;
+
+const options = {
+ adapters: [emotionStaticAdapter, globalCssAdapter],
+ layoutComponents: [],
+ readModule: (_from: string, specifier: string) =>
+ specifier === './highlights' ? REGISTRY : undefined,
+ readStylesheet: (_from: string, specifier: string) =>
+ specifier === './Highlight.css' ? CSS : undefined,
+};
+
+const gaps = (
+ before: string,
+ after: string,
+ css: ExtractOptions['readStylesheet'] = options.readStylesheet,
+) => {
+ const read = { ...options, readStylesheet: css };
+ const pair = [extractFile(before, 'a.tsx', read), extractFile(after, 'a.tsx', options)] as const;
+ const gap = globalRulesChanged(pair[0], pair[1], carriedClasses([...pair]));
+ return gap ? [gap] : [];
+};
+
+describe('global rules that hang on no element', () => {
+ it('proves a global stylesheet restored verbatim into createGlobalStyle', () => {
+ expect(gaps(base, head())).toEqual([]);
+ });
+
+ it('catches a changed declaration', () => {
+ expect(gaps(base, head('4px'))).toEqual(['GLOBAL_RULES_CHANGED:1/1']);
+ });
+
+ it('catches a dropped rule', () => {
+ expect(gaps(base, head(undefined, ''))).toEqual(['GLOBAL_RULES_CHANGED:1/0']);
+ });
+
+ it('catches a changed global style kept in emotion on both sides', () => {
+ expect(gaps(head(), head())).toEqual([]);
+ expect(gaps(head(), head(undefined, ''))).toEqual(['GLOBAL_RULES_CHANGED:1/0']);
+ });
+
+ it('leaves rules on a class an element carries to the element cases', () => {
+ const css = () => '.crumb ol { margin: 0; }\n';
+ const element = `import './Highlight.css';\n\nexport const A = () => <div className="crumb" />;\n`;
+ expect(gaps(element, 'export const A = () => <div className="crumb" />;\n', css)).toEqual([]);
+ });
+
+ it('still compares a rule whose class no element carries', () => {
+ const css = () => '[data-submenu] > [role="menu"]:has(.lobe-skill-search) { width: 1px; }\n';
+ const element = `import './Highlight.css';\n\nexport const A = () => <div />;\n`;
+ expect(gaps(element, 'export const A = () => <div />;\n', css)).toEqual([
+ 'GLOBAL_RULES_CHANGED:1/0',
+ ]);
+ });
+
+ it('leaves a class the file writes outside JSX to the outside-JSX flag', () => {
+ const css = () => '.lobe-input-38d9-editor p { margin: 0; }\n';
+ const outside = `import './Highlight.css';\n\nconst className = \`\${'lobe-input-38d9-editor'}\`;\nexport const A = () => <div />;\n`;
+ expect(gaps(outside, 'export const A = () => <div />;\n', css)).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/globalRules.ts b/packages/style-equivalence/src/plan/globalRules.ts
new file mode 100644
index 00000000000..528cdbaf0ba
--- /dev/null
+++ b/packages/style-equivalence/src/plan/globalRules.ts
@@ -0,0 +1,62 @@
+import ts from 'typescript';
+
+import type { FileExtraction, StyleRule } from '../extract';
+import { literalText } from '../extract/identifiers';
+import { classNamesIn } from '../extract/selectors';
+import { elementsOf } from './descendants';
+import { resolve, signature } from './kept';
+import { normalizeSelector } from './moved';
+
+export const GLOBAL_RULES_CHANGED = 'GLOBAL_RULES_CHANGED';
+
+const literalTokens = (expr: string) => {
+ const tokens: string[] = [];
+ const visit = (node: ts.Node) => {
+ tokens.push(...(literalText(node)?.split(/\s+/).filter(Boolean) ?? []));
+ ts.forEachChild(node, visit);
+ };
+ visit(ts.createSourceFile('t.ts', `(${expr});`, ts.ScriptTarget.Latest, true));
+ return tokens;
+};
+
+export const carriedClasses = (extractions: FileExtraction[]) => {
+ const carried = new Set<string>();
+ for (const extraction of extractions) {
+ extraction.literalClasses?.forEach((token) => carried.add(token));
+ for (const element of elementsOf(extraction)) {
+ for (const slot of element.slots)
+ if (slot.startsWith('global.')) carried.add(slot.slice('global.'.length));
+ for (const binding of element.bindings)
+ for (const expr of [binding.expr, binding.expansion])
+ if (expr) literalTokens(expr).forEach((token) => carried.add(token));
+ }
+ }
+ return carried;
+};
+
+const signatureOf = (rule: StyleRule) => {
+ const selector = normalizeSelector(resolve(rule.selector, rule));
+ return selector === undefined ? `UNPARSED:${rule.selector}` : signature(rule, selector);
+};
+
+export const globalRuleSignatures = (extraction: FileExtraction, carried: Set<string>) =>
+ [
+ ...extraction.rules.filter((rule) => rule.stylesheet && !Object.keys(rule.owned).length),
+ ...(extraction.globalRules ?? []),
+ ]
+ .filter((rule) => rule.declarations?.length || rule.stylesheet?.startsWith('unparsed:'))
+ .filter((rule) => !classNamesIn(rule.selector).some((name) => carried.has(name)))
+ .map(signatureOf);
+
+export const globalRulesChanged = (
+ base: FileExtraction,
+ head: FileExtraction,
+ carried: Set<string>,
+) => {
+ const before = globalRuleSignatures(base, carried);
+ const after = globalRuleSignatures(head, carried);
+ if (JSON.stringify(before) === JSON.stringify(after)) return undefined;
+ const removed = before.filter((item) => !after.includes(item)).length;
+ const added = after.filter((item) => !before.includes(item)).length;
+ return `${GLOBAL_RULES_CHANGED}:${removed}/${added}`;
+};
diff --git a/packages/style-equivalence/src/plan/inlineStyle.test.ts b/packages/style-equivalence/src/plan/inlineStyle.test.ts
new file mode 100644
index 00000000000..a7ba6f5b553
--- /dev/null
+++ b/packages/style-equivalence/src/plan/inlineStyle.test.ts
@@ -0,0 +1,95 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const baseWith = (
+ attributes = 'className={styles.divider} style={{ left: `${view.ratio * 100}%` }}',
+) => `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ divider: css\`width: 4px;\` }));
+
+export const Split = ({ handlers, view }) => (
+ <div ${attributes} />
+);
+`;
+
+const base = baseWith();
+
+const headWith = (call: string, spread = '') => `import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({ divider: { width: '4px' } });
+
+export const Split = ({ handlers, view }) => <div ${spread}{...${call}} />;
+`;
+
+const head = (style = '{ left: `${view.ratio * 100}%` }', spread = '') =>
+ headWith(`sx([styles.divider], undefined, ${style})`, spread);
+
+const plan = (after: string, before = base) => {
+ const pair = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ return { pair, plan: planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] }) };
+};
+
+describe('an inline style moved from the style prop into sx', () => {
+ it('renders neither side with it 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)' },
+ ]);
+ const module = generateModule(pair.head, result, 'head', { layoutComponents: [] });
+ expect(module).not.toContain('view.ratio');
+ });
+
+ it('keeps the variable when the style expression changed', () => {
+ const [entry] = plan(head('{ left: `${view.ratio * 50}%` }')).plan.cases;
+ expect(entry.inlineStyles).toBeUndefined();
+ expect(entry.flags).toContain('VARIABLE_UNMODELED');
+ });
+
+ it('shares the style next to a spread whose order relative to it did not change', () => {
+ const before = baseWith(
+ '{...handlers} className={styles.divider} style={{ left: `${view.ratio * 100}%` }}',
+ );
+ const [entry] = plan(head(undefined, '{...handlers} '), before).plan.cases;
+ expect(entry.inlineStyles?.head).toHaveLength(1);
+ expect(entry.flags).toEqual([]);
+ });
+
+ it('flags a style that moved from before a spread to after it', () => {
+ const before = baseWith(
+ 'className={styles.divider} style={{ left: `${view.ratio * 100}%` }} {...handlers}',
+ );
+ const [entry] = plan(head(undefined, '{...handlers} '), before).plan.cases;
+ expect(entry.inlineStyles?.head).toHaveLength(1);
+ expect(entry.flags).toEqual(['INLINE_STYLE_SPREAD_ORDER']);
+ });
+
+ it('shares a style that differs only by a trailing comma and line breaks', () => {
+ const [entry] = plan(head('{\n left: `${view.ratio * 100}%`,\n}')).plan.cases;
+ expect(entry.inlineStyles?.head).toHaveLength(1);
+ expect(entry.flags).toEqual([]);
+ });
+
+ it('finds the style in a variadic sx call, whatever its position', () => {
+ const style = '{ left: `${view.ratio * 100}%` }';
+ 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')" },
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/inlineStyle.ts b/packages/style-equivalence/src/plan/inlineStyle.ts
new file mode 100644
index 00000000000..cd46222efc9
--- /dev/null
+++ b/packages/style-equivalence/src/plan/inlineStyle.ts
@@ -0,0 +1,80 @@
+import ts from 'typescript';
+
+import type { StyleElement } from '../extract';
+import { valueIdentifiers } from '../extract/identifiers';
+
+const compact = (text: string) => text.replaceAll(/\s+/g, '').replaceAll(/,(?=[)\]}])/g, '');
+
+interface SxStyle {
+ binding: number;
+ names: string[];
+ style: string;
+ without: string;
+}
+
+const sxStyleOf = (element: StyleElement, styleExpr: 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);
+ const [statement] = source.statements;
+ let call = statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;
+ while (call && ts.isParenthesizedExpression(call)) call = call.expression;
+ if (!call || !ts.isCallExpression(call) || compact(call.expression.getText(source)) !== 'sx')
+ continue;
+ const position = call.arguments.findIndex(
+ (argument, index) => index > 0 && compact(argument.getText(source)) === compact(styleExpr),
+ );
+ if (position < 0) continue;
+ const style = call.arguments[position];
+ const 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 kept = new Set(
+ call.arguments
+ .filter((_, index) => index !== position)
+ .flatMap((argument) => [...valueIdentifiers(argument)]),
+ );
+ return {
+ binding: index,
+ names: [...valueIdentifiers(style)].filter((name) => !kept.has(name)),
+ style: compact(style.getText(source)),
+ without,
+ };
+ }
+ return undefined;
+};
+
+export interface SharedStyle {
+ binding: number;
+ index: number;
+ names: string[];
+ reordered: boolean;
+ without: string;
+}
+
+export const sharedInlineStyles = (chains: Record<'base' | 'head', StyleElement[]>) => {
+ const found: Partial<Record<'base' | 'head', SharedStyle[]>> = {};
+ if (chains.base.length !== chains.head.length) return found;
+ chains.base.forEach((left, index) => {
+ const right = chains.head[index];
+ for (const [side, own, other] of [
+ ['head', right, left],
+ ['base', left, right],
+ ] as const) {
+ if (!other.styleExpr || other.runtimeStyle || other.inlineStyle) continue;
+ const sx = sxStyleOf(own, other.styleExpr);
+ if (!sx) continue;
+ (found[side] ??= []).push({
+ binding: sx.binding,
+ index,
+ names: sx.names,
+ reordered:
+ Boolean(own.foreignSpread) !== Boolean(other.foreignSpread) ||
+ Boolean(own.spreadAfterStyle) !== Boolean(other.spreadAfterStyle),
+ without: sx.without,
+ });
+ }
+ });
+ return found;
+};
diff --git a/packages/style-equivalence/src/plan/inner.ts b/packages/style-equivalence/src/plan/inner.ts
new file mode 100644
index 00000000000..3d30767ff59
--- /dev/null
+++ b/packages/style-equivalence/src/plan/inner.ts
@@ -0,0 +1,142 @@
+import { parseSelectorList, type SelectorNode } from './selectorTree';
+
+export interface InnerNode {
+ attributes: Record<string, string>;
+ children: InnerNode[];
+ tag: string;
+}
+
+const VOID_TAGS = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'source', 'wbr']);
+const PSEUDO_ELEMENTS = new Set(['::after', '::before', '::marker', '::placeholder']);
+const ATTRIBUTE_OPERATORS = new Set([undefined, '=', '~=', '|=', '^=', '$=', '*=']);
+
+interface Trie {
+ attributes: Record<string, string>;
+ children: Map<string, Trie>;
+ tag: string;
+}
+
+interface Step {
+ key: string;
+ nodes: SelectorNode[];
+}
+
+const compoundOf = (nodes: SelectorNode[], last: boolean): Trie | undefined => {
+ const node: Trie = { attributes: {}, children: new Map(), tag: 'div' };
+ const classes: string[] = [];
+ for (const [index, part] of nodes.entries()) {
+ const value = part.value ?? '';
+ if (part.type === 'tag') node.tag = value.toLowerCase();
+ else if (part.type === 'universal') continue;
+ else if (part.type === 'class') classes.push(value);
+ else if (part.type === 'id') node.attributes.id = value;
+ else if (part.type === 'attribute' && part.attribute) {
+ if (!ATTRIBUTE_OPERATORS.has(part.operator) || part.attribute in node.attributes)
+ return undefined;
+ node.attributes[part.attribute] = part.operator ? value : '';
+ } else if (part.type === 'pseudo' && value === ':has' && part.nodes?.length === 1) {
+ const [argument] = part.nodes;
+ const parts = argument.nodes ?? [];
+ const [first, ...after] = parts;
+ const relative = first?.type === 'combinator';
+ const inner = relative ? after : parts;
+ if (relative && first.value?.trim() !== '>') return undefined;
+ if (!inner.length || inner.some((item) => item.type === 'combinator')) return undefined;
+ const child = compoundOf(inner, true);
+ if (!child) return undefined;
+ node.children.set(`:has(${String(argument).trim()})`, child);
+ } else if (part.type === 'pseudo' && PSEUDO_ELEMENTS.has(value)) {
+ if (!last || index !== nodes.length - 1) return undefined;
+ } else return undefined;
+ }
+ if (classes.length) node.attributes.className = classes.join(' ');
+ return node;
+};
+
+const pathOf = (selector: SelectorNode[]) => {
+ const steps: Step[] = [];
+ let combinator = '';
+ let current: SelectorNode[] = [];
+ const flush = () => {
+ steps.push({ key: `${combinator}${current.map(String).join('').trim()}`, nodes: current });
+ current = [];
+ };
+ for (const part of selector) {
+ if (part.type === 'combinator') {
+ if (!current.length) return undefined;
+ flush();
+ combinator = part.value?.trim() || ' ';
+ if (![' ', '>'].includes(combinator)) return undefined;
+ continue;
+ }
+ if (part.type === 'nesting' || part.type === 'comment') return undefined;
+ current.push(part);
+ }
+ if (!current.length) return undefined;
+ flush();
+ return steps;
+};
+
+const merge = (into: Map<string, Trie>, steps: Step[]) => {
+ let level = into;
+ for (const [index, step] of steps.entries()) {
+ const fresh = compoundOf(step.nodes, index === steps.length - 1);
+ if (!fresh) return false;
+ const existing = level.get(step.key) ?? fresh;
+ level.set(step.key, existing);
+ level = existing.children;
+ }
+ return true;
+};
+
+const finish = (trie: Map<string, Trie>): InnerNode[] | undefined => {
+ const nodes: InnerNode[] = [];
+ for (const node of trie.values()) {
+ const children = finish(node.children);
+ if (!children || (children.length && VOID_TAGS.has(node.tag))) return undefined;
+ nodes.push({ attributes: node.attributes, children, tag: node.tag });
+ }
+ return nodes;
+};
+
+export const innerTargets = (selectors: string[], scope: string) => {
+ const root = new Map<string, Trie>();
+ for (const text of selectors) {
+ const parsed = parseSelectorList(text);
+ if (!parsed) return undefined;
+ for (const selector of parsed) {
+ const steps = pathOf(selector);
+ const [head, ...rest] = steps ?? [];
+ const scoped =
+ head?.nodes[0]?.type === 'class' &&
+ head.nodes[0].value === scope &&
+ head.nodes.slice(1).every((part) => part.type === 'pseudo');
+ if (!steps || !scoped || (rest.length && !merge(root, rest))) return undefined;
+ }
+ }
+ return finish(root);
+};
+
+const hasArguments = (nodes: SelectorNode[], found: SelectorNode[][]) => {
+ for (const node of nodes) {
+ if (node.type === 'pseudo' && node.value === ':has')
+ for (const argument of node.nodes ?? []) found.push(argument.nodes ?? []);
+ if (node.nodes) hasArguments(node.nodes, found);
+ }
+};
+
+export const hasTargets = (selectors: string[]) => {
+ const found: SelectorNode[][] = [];
+ for (const text of selectors)
+ for (const selector of parseSelectorList(text) ?? []) hasArguments(selector, found);
+ const targets = new Map<string, InnerNode>();
+ for (const parts of found) {
+ const [first, ...after] = parts;
+ const inner = first?.type === 'combinator' && first.value?.trim() === '>' ? after : parts;
+ if (!inner.length || inner.some((item) => item.type === 'combinator')) continue;
+ const trie = compoundOf(inner, true);
+ const nodes = trie && finish(new Map([['', trie]]));
+ if (nodes) for (const node of nodes) targets.set(JSON.stringify(node), node);
+ }
+ return [...targets.values()];
+};
diff --git a/packages/style-equivalence/src/plan/kept.test.ts b/packages/style-equivalence/src/plan/kept.test.ts
new file mode 100644
index 00000000000..48ac33d7841
--- /dev/null
+++ b/packages/style-equivalence/src/plan/kept.test.ts
@@ -0,0 +1,214 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const H1 = `h1 {
+ overflow-wrap: anywhere;
+ white-space: normal;
+ }`;
+
+const base = (nested = H1, className = 'styles.content') => `
+import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css\`
+ padding: 24px;
+ background: \${cssVar.colorBgContainer};
+
+ ${nested}
+ \`,
+}));
+
+export const Embed = ({ open }) => (
+ <Flexbox className={${className}} gap={24}>
+ <Goal />
+ </Flexbox>
+);
+`;
+
+const head = (
+ kept = H1,
+ host = '{...sx(styles.content, fallback.content)}',
+ child = '<Goal />',
+) => `
+import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({
+ content: { padding: '24px', backgroundColor: cssVar.colorBgContainer },
+});
+
+const fallback = createStaticStyles(({ css }) => ({
+ content: css\`
+ ${kept}
+ \`,
+}));
+
+export const Embed = ({ open }) => (
+ <Flexbox gap={24} ${host}>
+ ${child}
+ </Flexbox>
+);
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: ['Flexbox'],
+ }).cases;
+
+const H1_NODE = { attributes: {}, children: [], tag: 'h1' };
+
+const proven = (entry: ReturnType<typeof plan>[number]) => {
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['EMOTION_RULE_KEPT']);
+ expect(entry.inner).toEqual({ 0: [H1_NODE] });
+};
+
+const unproven = (entry: ReturnType<typeof plan>[number]) => {
+ expect(entry.flags).toContain('INNER_TARGET');
+ expect(entry.evidence ?? []).not.toContain('EMOTION_RULE_KEPT');
+};
+
+describe('an emotion rule kept verbatim for descendants StyleX cannot reach', () => {
+ it('proves the rule when the fallback lands on the same element through sx', () => {
+ const [entry] = plan(base(), head());
+ proven(entry);
+ });
+
+ it('proves the rule when the fallback is joined into className with cx', () => {
+ const [entry] = plan(
+ base(),
+ head(undefined, 'className={cx(stylex.props(styles.content).className, fallback.content)}'),
+ );
+ proven(entry);
+ });
+
+ it('proves the rule on a component part reached through classNames', () => {
+ const before = base(undefined, 'styles.content')
+ .replace('<Flexbox className={styles.content}', '<Card classNames={{ body: styles.content }}')
+ .replace('</Flexbox>', '</Card>');
+ const after = head(
+ undefined,
+ 'classNames={{ body: cx(stylex.props(styles.content).className, fallback.content) }}',
+ )
+ .replace('<Flexbox gap={24}', '<Card gap={24}')
+ .replace('</Flexbox>', '</Card>');
+ const [entry] = plan(before, after);
+ expect(entry.flags).not.toContain('INNER_TARGET');
+ expect(entry.evidence).toContain('EMOTION_RULE_KEPT');
+ });
+
+ it('resolves interpolated tokens by expression, not by placeholder position', () => {
+ const rule = `h1 {
+ color: \${cssVar.colorText};
+ }`;
+ const [entry] = plan(base(rule), head(rule));
+ proven(entry);
+ });
+
+ it('proves a rule kept under the same media condition', () => {
+ const rule = `@media (width <= 767px) {
+ h1 {
+ white-space: normal;
+ }
+ }`;
+ const [entry] = plan(base(rule), head(rule));
+ proven(entry);
+ });
+
+ it('keeps the flag when a declaration changed', () => {
+ const [entry] = plan(base(), head(H1.replace('white-space: normal', 'white-space: nowrap')));
+ unproven(entry);
+ });
+
+ it('keeps the flag when an interpolated token changed', () => {
+ const rule = (token: string) => `h1 {
+ color: \${cssVar.${token}};
+ }`;
+ const [entry] = plan(base(rule('colorText')), head(rule('colorTextSecondary')));
+ unproven(entry);
+ });
+
+ it('keeps the flag when one of the rules was dropped', () => {
+ const [entry] = plan(base(`${H1}\n h2 { margin: 0; }`), head());
+ unproven(entry);
+ });
+
+ it('keeps the flag when the fallback is missing altogether', () => {
+ const [entry] = plan(base(), head(undefined, '{...stylex.props(styles.content)}'));
+ unproven(entry);
+ });
+
+ it('keeps the flag when the selector changed', () => {
+ const [entry] = plan(base(), head(H1.replace('h1 {', '> h1 {')));
+ unproven(entry);
+ });
+
+ it('keeps the flag when the media condition changed', () => {
+ const wrap = (query: string) => `@media (${query}) {
+ ${H1}
+ }`;
+ const [entry] = plan(base(wrap('width <= 767px')), head(wrap('width <= 768px')));
+ unproven(entry);
+ });
+
+ it('keeps the flag when an interpolated condition wrapper was dropped', () => {
+ const [entry] = plan(base(`\${responsive.sm} {\n ${H1}\n }`), head());
+ unproven(entry);
+ });
+
+ it('keeps the flag when head adds another nested rule', () => {
+ const [entry] = plan(base(), head(`${H1}\n h2 { margin: 0; }`));
+ unproven(entry);
+ });
+
+ it('keeps the flag when the fallback moved to a different element', () => {
+ const cases = plan(
+ base(),
+ head(undefined, '{...stylex.props(styles.content)}', '<div className={fallback.content} />'),
+ );
+ unproven(cases[0]);
+ });
+
+ it('keeps the flag when only head applies the fallback conditionally', () => {
+ const [entry] = plan(
+ base(),
+ head(undefined, '{...sx(styles.content, open && fallback.content)}'),
+ );
+ unproven(entry);
+ });
+
+ it('keeps the flag when only base applied the rule conditionally', () => {
+ const [entry] = plan(
+ base(undefined, 'open ? styles.content : undefined'),
+ head(undefined, '{...sx(open && styles.content, fallback.content)}'),
+ );
+ unproven(entry);
+ });
+
+ it('keeps the flag when the fallback is defined but not applied', () => {
+ const [entry] = plan(
+ base(),
+ head(undefined, '{...stylex.props(styles.content)} data-fallback={fallback.content}'),
+ );
+ unproven(entry);
+ });
+
+ it('keeps the flag when the fallback goes to a different component part', () => {
+ const before = base()
+ .replace('<Flexbox className={styles.content}', '<Card classNames={{ body: styles.content }}')
+ .replace('</Flexbox>', '</Card>');
+ const after = head(undefined, 'classNames={{ header: fallback.content }}')
+ .replace('<Flexbox gap={24}', '<Card gap={24}')
+ .replace('</Flexbox>', '</Card>');
+ const [entry] = plan(before, after);
+ unproven(entry);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/kept.ts b/packages/style-equivalence/src/plan/kept.ts
new file mode 100644
index 00000000000..1df928c606e
--- /dev/null
+++ b/packages/style-equivalence/src/plan/kept.ts
@@ -0,0 +1,257 @@
+import ts from 'typescript';
+
+import type { FileExtraction, StyleElement, StyleRule } from '../extract';
+import { SELF } from '../extract/css';
+import { literalText } from '../extract/identifiers';
+import { classNamesIn } from '../extract/selectors';
+import { elementsOf } from './descendants';
+import { type InnerNode, innerTargets } from './inner';
+import { normalizeSelector } from './moved';
+import { parseSelectorList } from './selectorTree';
+
+export interface KeptProof {
+ exhaustive: boolean;
+ head: string;
+ nodes: InnerNode[];
+ placement?: string;
+}
+
+const TRANSPARENT = new Set([
+ ts.SyntaxKind.ArrayLiteralExpression,
+ ts.SyntaxKind.AsExpression,
+ ts.SyntaxKind.NonNullExpression,
+ ts.SyntaxKind.ObjectLiteralExpression,
+ ts.SyntaxKind.ParenthesizedExpression,
+ ts.SyntaxKind.SatisfiesExpression,
+ ts.SyntaxKind.SpreadElement,
+ ts.SyntaxKind.TemplateExpression,
+ ts.SyntaxKind.TemplateSpan,
+]);
+
+const JOINERS = new Set(['filter', 'join']);
+
+const compact = (node: ts.Node) => node.getText().replaceAll(/\s+/g, '');
+
+const segmentOf = (node: ts.Node, parent: ts.Node): string | null | undefined => {
+ if (TRANSPARENT.has(parent.kind)) return null;
+ if (ts.isCallExpression(parent)) {
+ if (parent.arguments.includes(node as ts.Expression)) return null;
+ return parent.expression === node && ts.isPropertyAccessExpression(node) ? null : undefined;
+ }
+ if (ts.isPropertyAccessExpression(parent)) {
+ if (ts.isCallExpression(node) && parent.name.text === 'className') return null;
+ return parent.expression === node && JOINERS.has(parent.name.text) ? null : undefined;
+ }
+ if (ts.isPropertyAssignment(parent) && parent.initializer === node) {
+ const { name } = parent;
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? `key:${name.text}` : undefined;
+ }
+ if (ts.isBinaryExpression(parent)) {
+ const operator = parent.operatorToken.kind;
+ if (operator === ts.SyntaxKind.PlusToken) return null;
+ const guarded = [
+ ts.SyntaxKind.AmpersandAmpersandToken,
+ ts.SyntaxKind.BarBarToken,
+ ts.SyntaxKind.QuestionQuestionToken,
+ ].includes(operator);
+ return guarded && parent.right === node
+ ? `${ts.tokenToString(operator)}(${compact(parent.left)})`
+ : undefined;
+ }
+ if (ts.isConditionalExpression(parent)) {
+ if (parent.whenTrue === node) return `?(${compact(parent.condition)})`;
+ if (parent.whenFalse === node) return `!?(${compact(parent.condition)})`;
+ }
+ return undefined;
+};
+
+const pathFrom = (node: ts.Node) => {
+ const segments: string[] = [];
+ for (let current = node; !ts.isExpressionStatement(current.parent); current = current.parent) {
+ const segment = segmentOf(current, current.parent);
+ if (segment === undefined) return undefined;
+ if (segment) segments.unshift(segment);
+ }
+ return segments;
+};
+
+const placementOf = (element: StyleElement, slot: string) => {
+ const found: string[][] = [];
+ for (const binding of element.bindings) {
+ const source = ts.createSourceFile(
+ 't.ts',
+ `(${binding.expansion ?? binding.expr});`,
+ ts.ScriptTarget.Latest,
+ true,
+ );
+ const token = slot.startsWith('global.') ? slot.slice('global.'.length) : undefined;
+ const matches = (node: ts.Node) =>
+ token
+ ? !!literalText(node)?.split(/\s+/).includes(token)
+ : ts.isPropertyAccessExpression(node) && compact(node) === slot;
+ const visit = (node: ts.Node) => {
+ if (matches(node)) {
+ const path = pathFrom(node);
+ if (!path) return found.push(['?']);
+ const keyed = path.some((segment) => segment.startsWith('key:'));
+ const root = binding.spread ? (keyed ? [] : ['key:className']) : [`key:${binding.prop}`];
+ found.push([...root, ...path]);
+ return;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ const [only] = found;
+ return found.length === 1 && only[0] !== '?' ? JSON.stringify(only) : undefined;
+};
+
+export const slotsOf = (rule: StyleRule) =>
+ classNamesIn(rule.selector).flatMap((name) =>
+ [rule.owned[name], rule.stylesheet ? `global.${name}` : undefined].filter(
+ (slot): slot is string => !!slot,
+ ),
+ );
+
+const rulesOn = (element: StyleElement, rules: StyleRule[]) =>
+ rules.filter(
+ (rule) =>
+ rule.declarations?.length && slotsOf(rule).some((slot) => element.slots.includes(slot)),
+ );
+
+const descendant = (rule: StyleRule) =>
+ (parseSelectorList(rule.selector) ?? []).some((nodes) =>
+ nodes.some((node) => node.type === 'combinator'),
+ );
+
+const kebab = (name: string) =>
+ name
+ .replaceAll(/([a-z\d])([A-Z])/g, '$1-$2')
+ .replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
+ .replaceAll(/([a-z])(\d)/g, '$1-$2')
+ .toLowerCase();
+
+const tokenValue = (expression: string) => {
+ const token = /^cssVar\.(\w+)$/.exec(expression);
+ return token ? `var(--lobe-${kebab(token[1])})` : `\${${expression}}`;
+};
+
+export const resolve = (text: string, rule: StyleRule) =>
+ text.replaceAll(/__I(\d+)__/g, (match, index: string) => {
+ const value = rule.interpolationValues?.[Number(index)];
+ if (typeof value === 'string') return value;
+ const expression = rule.interpolations?.[Number(index)];
+ return expression === undefined ? match : tokenValue(expression);
+ });
+
+const hostSlot = (rule: StyleRule, element: StyleElement) => {
+ const slots = [...new Set(slotsOf(rule).filter((slot) => element.slots.includes(slot)))];
+ return slots.length === 1 ? slots[0] : undefined;
+};
+
+const hostSelector = (rule: StyleRule, slot: string) =>
+ rule.stylesheet
+ ? normalizeSelector(rule.selector, slot.slice('global.'.length), SELF)
+ : normalizeSelector(resolve(rule.selector, rule));
+
+export const signature = (rule: StyleRule, selector: string) =>
+ JSON.stringify({
+ conditions: rule.conditions.map((condition) => resolve(condition, rule)),
+ declarations: rule.declarations?.map((declaration) => resolve(declaration, rule)),
+ selector,
+ });
+
+const literalTokens = (element: StyleElement) =>
+ element.bindings.flatMap((binding) => {
+ const source = ts.createSourceFile(
+ 't.ts',
+ `(${binding.expansion ?? binding.expr});`,
+ ts.ScriptTarget.Latest,
+ true,
+ );
+ const tokens: string[] = [];
+ const visit = (node: ts.Node) => {
+ tokens.push(...(literalText(node)?.split(/\s+/).filter(Boolean) ?? []));
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return tokens;
+ });
+
+const placementSwap = (base: StyleElement, head: StyleElement, slots: [string, string]) => {
+ const [binding] = head.bindings;
+ if (base.bindings.length !== 1 || head.bindings.length !== 1 || binding.expansion)
+ return undefined;
+ const escaped = slots[1].replaceAll(/[$.]/g, (char) => `\\${char}`);
+ const parts = binding.expr.split(new RegExp(`(?<![\\w$.])${escaped}(?![\\w$])`));
+ if (parts.length !== 2) return undefined;
+ const own = slots[0].startsWith('global.')
+ ? JSON.stringify(slots[0].slice('global.'.length))
+ : slots[0];
+ return parts.join(own);
+};
+
+interface Context {
+ base: FileExtraction;
+ head: FileExtraction;
+}
+
+const proveElement = (
+ base: StyleElement,
+ head: StyleElement,
+ { base: before, head: after }: Context,
+): KeptProof | undefined => {
+ const all = rulesOn(base, before.rules);
+ const required = all.filter(descendant);
+ const kept = rulesOn(head, after.rules);
+ if (!required.length || required.length !== kept.length) return undefined;
+ const selectors: string[] = [];
+ const slots = new Set<string>();
+ const users = (slot: string) =>
+ elementsOf(before).filter((element) => element.slots.includes(slot)).length;
+ for (const [index, left] of required.entries()) {
+ const right = kept[index];
+ const leftSlot = hostSlot(left, base);
+ const rightSlot = hostSlot(right, head);
+ if (!leftSlot || !rightSlot || !right.slot || right.stylesheet) return undefined;
+ if (left.stylesheet ? !leftSlot.startsWith('global.') || users(leftSlot) !== 1 : !left.slot)
+ return undefined;
+ const selector = hostSelector(left, leftSlot);
+ const placement = placementOf(base, leftSlot);
+ if (
+ !selector ||
+ selector !== hostSelector(right, rightSlot) ||
+ signature(left, selector) !== signature(right, selector) ||
+ !placement ||
+ placement !== placementOf(head, rightSlot)
+ )
+ return undefined;
+ selectors.push(selector);
+ slots.add(`${leftSlot}\n${rightSlot}`);
+ }
+ const nodes = innerTargets(
+ selectors.filter((selector) => innerTargets([selector], SELF)),
+ SELF,
+ );
+ const pairs = [...slots].map((entry) => entry.split('\n') as [string, string]);
+ const globals = new Set(pairs.flatMap(([slot]) => (slot.startsWith('global.') ? [slot] : [])));
+ const exhaustive =
+ all.length === required.length &&
+ literalTokens(base).every((token) => globals.has(`global.${token}`)) &&
+ !literalTokens(head).length;
+ const placement = pairs.length === 1 ? placementSwap(base, head, pairs[0]) : undefined;
+ return { exhaustive, head: head.id, nodes: nodes ?? [], ...(placement ? { placement } : {}) };
+};
+
+export const keptEmotionRules = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Array<[StyleElement, StyleElement]>,
+) => {
+ const proofs = new Map<string, KeptProof>();
+ for (const [left, right] of pairs) {
+ const proof = proveElement(left, right, { base, head });
+ if (proof) proofs.set(left.id, proof);
+ }
+ return proofs;
+};
diff --git a/packages/style-equivalence/src/plan/keptImported.test.ts b/packages/style-equivalence/src/plan/keptImported.test.ts
new file mode 100644
index 00000000000..d1e11c96b26
--- /dev/null
+++ b/packages/style-equivalence/src/plan/keptImported.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../extract/adapters/globalCss';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const TOKEN = 'lobe-crumb-30cd-root';
+
+const component = (css = true) => `${css ? "import './crumb.css';\n" : ''}
+import { Breadcrumb } from '@lobehub/ui';
+
+import { rootClassName } from './crumbStyles';
+
+export const Crumb = () => <Breadcrumb className={rootClassName} items={[]} />;
+`;
+
+const baseModule = `import * as stylex from '@stylexjs/stylex';
+
+const SCOPE = '${TOKEN}';
+
+const crumbStyles = stylex.create({ root: { minWidth: 0 } });
+
+export const rootClassName = [SCOPE, stylex.props(crumbStyles.root).className].join(' ');
+`;
+
+const headModule = (
+ rule = 'flex-wrap: nowrap;',
+ applied = 'fallback.root',
+) => `import { createStaticStyles, cx } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const crumbStyles = stylex.create({ root: { minWidth: 0 } });
+
+const fallback = createStaticStyles(({ css }) => ({
+ root: css\`
+ ol {
+ ${rule}
+ }
+ \`,
+}));
+
+export const rootClassName = cx(stylex.props(crumbStyles.root).className, ${applied});
+`;
+
+const options = (module: string, css?: string) => ({
+ adapters: [emotionStaticAdapter, stylexAdapter, globalCssAdapter],
+ layoutComponents: [],
+ readModule: (_from: string, specifier: string) =>
+ specifier === './crumbStyles' ? module : undefined,
+ readStylesheet: (_from: string, specifier: string) =>
+ specifier === './crumb.css' ? css : undefined,
+});
+
+const CSS = `.${TOKEN} ol {\n flex-wrap: nowrap;\n}\n`;
+
+const plan = (head: string) =>
+ planFile(
+ 'a.tsx',
+ extractFile(component(), 'a.tsx', options(baseModule, CSS)),
+ extractFile(component(false), 'a.tsx', options(head)),
+ { layoutComponents: [] },
+ ).cases;
+
+describe('a class constant imported from a sibling styles module', () => {
+ it('reads the stylesheet class and the fallback through the imported constant', () => {
+ const head = extractFile(component(false), 'a.tsx', options(headModule()));
+ expect(head.elements[0].slots).toEqual([
+ 'rootClassName$crumbStyles.root',
+ 'rootClassName$fallback.root',
+ ]);
+ expect(head.rules.map((rule) => rule.selector)).toEqual(['.__self__ ol']);
+ const base = extractFile(component(), 'a.tsx', options(baseModule, CSS));
+ expect(base.elements[0].slots).toContain(`global.${TOKEN}`);
+ expect(base.elements[0].flags).toEqual(['INNER_TARGET']);
+ });
+
+ it('proves the rule kept verbatim in the sibling module fallback', () => {
+ const [entry] = plan(headModule());
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['PLACEMENT_PRESERVED', 'EMOTION_RULE_KEPT']);
+ expect(entry.inner).toEqual({ 0: [{ attributes: {}, children: [], tag: 'ol' }] });
+ });
+
+ it('keeps the flag when the sibling module changed the declaration', () => {
+ const [entry] = plan(headModule('flex-wrap: wrap;'));
+ expect(entry.flags).toEqual(['INNER_TARGET']);
+ });
+
+ it('keeps the flag when the sibling module no longer applies the fallback', () => {
+ const [entry] = plan(headModule(undefined, "''"));
+ expect(entry.flags).toEqual(['INNER_TARGET']);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/keptRestored.test.ts b/packages/style-equivalence/src/plan/keptRestored.test.ts
new file mode 100644
index 00000000000..7ca17b15ca2
--- /dev/null
+++ b/packages/style-equivalence/src/plan/keptRestored.test.ts
@@ -0,0 +1,348 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../extract/adapters/globalCss';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const TOKEN = 'lobe-tasks-group-config-4e0dc256-form';
+
+const CSS = `.${TOKEN} label,
+.${TOKEN} label * {
+ font-size: 13px !important;
+ color: var(--lobe-color-text-secondary) !important;
+}
+`;
+
+const base = (extra = '') => `import './Config.css';
+
+import { Form } from '@lobehub/ui/form';
+
+export const Config = () => (
+ <>
+ <Form className={'${TOKEN}'} />
+ ${extra}
+ </>
+);
+`;
+
+const head = (
+ rule = `label,
+ label * {
+ font-size: 13px !important;
+ color: \${cssVar.colorTextSecondary} !important;
+ }`,
+) => `import { createStaticStyles } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/form';
+
+const fallback = createStaticStyles(({ css, cssVar }) => ({
+ form: css\`
+ ${rule}
+ \`,
+}));
+
+export const Config = () => (
+ <>
+ <Form className={fallback.form} />
+ </>
+);
+`;
+
+const options = (css: Record<string, string>) => ({
+ adapters: [emotionStaticAdapter, stylexAdapter, globalCssAdapter],
+ layoutComponents: ['Flexbox'],
+ readStylesheet: (_from: string, specifier: string) => css[specifier],
+});
+
+const plan = (before: string, after: string, css = CSS) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({ './Config.css': css })),
+ extractFile(after, 'a.tsx', options({})),
+ { layoutComponents: ['Flexbox'] },
+ ).cases;
+
+describe('a plain stylesheet rule restored verbatim into an emotion fallback', () => {
+ it('proves the rule, resolves the theme token and keeps the component placement', () => {
+ const [entry] = plan(base(), head());
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['PLACEMENT_PRESERVED', 'EMOTION_RULE_KEPT']);
+ expect(entry.inner).toEqual({
+ 0: [
+ { attributes: {}, children: [{ attributes: {}, children: [], tag: 'div' }], tag: 'label' },
+ ],
+ });
+ });
+
+ it('keeps the flags when the token resolves to a different variable', () => {
+ const [entry] = plan(base(), head().replace('colorTextSecondary', 'colorTextTertiary'));
+ expect(entry.flags).toEqual(['INNER_TARGET', 'PLACEMENT_SUBSTITUTED']);
+ });
+
+ it('keeps the flags when the stylesheet class also lands on another element', () => {
+ const [entry] = plan(base(`<div className={'${TOKEN}'} />`), head());
+ expect(entry.flags).toContain('INNER_TARGET');
+ expect(entry.evidence ?? []).not.toContain('EMOTION_RULE_KEPT');
+ });
+
+ it('keeps the flags when one selector of the list was dropped', () => {
+ const rule = `label {
+ font-size: 13px !important;
+ color: \${cssVar.colorTextSecondary} !important;
+ }`;
+ const [entry] = plan(base(), head(rule));
+ expect(entry.flags).toContain('INNER_TARGET');
+ });
+});
+
+describe('a cross-component descendant rule kept verbatim', () => {
+ const chartBase = (host = '') =>
+ `import './Chart.css';
+
+import { SparkAreaChart } from '@lobehub/charts';
+
+export const Chart = () => <SparkAreaChart className={'spark-94e4'} />;
+`.replace("'spark-94e4'", `'spark-94e4${host}'`);
+ const chartCss = (extra = '') => `.spark-94e4 path.recharts-area-area[name='target'] {
+ fill: none;
+}
+${extra}`;
+ const chartHead = `import { createStaticStyles } from '@lobehub/ui';
+import { SparkAreaChart } from '@lobehub/charts';
+
+const fallback = createStaticStyles(({ css }) => ({
+ spark: css\`
+ & path.recharts-area-area[name='target'] {
+ fill: none;
+ }
+ \`,
+}));
+
+export const Chart = () => <SparkAreaChart className={fallback.spark} />;
+`;
+ const run = (before: string, css: string) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({ './Chart.css': css })),
+ extractFile(chartHead, 'a.tsx', options({})),
+ { layoutComponents: [] },
+ ).cases[0];
+
+ it('clears the cross-component flag when every rule on the element was kept', () => {
+ const entry = run(chartBase(), chartCss());
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toContain('EMOTION_RULE_KEPT');
+ });
+
+ it('keeps the cross-component flag when a host rule on a foreign class was not kept', () => {
+ const entry = run(chartBase(), chartCss('.spark-94e4.recharts-wrapper { color: red; }\n'));
+ expect(entry.flags).toContain('CROSS_COMPONENT');
+ });
+});
+
+describe('a restored rule that reads module constants', () => {
+ const CONTENT = 'lobe-comments-2aa3-content';
+ const contentCss = (height = '480px') => `.${CONTENT}
+ img:not(
+ img:is([style^='width:'], [style*=' width:'])
+ ) {
+ width: auto !important;
+ max-height: ${height};
+}
+
+.${CONTENT} [contenteditable='true'] ~ div {
+ margin-block-start: 0 !important;
+}
+`;
+ const contentBase = `import './Comment.css';
+
+export const Content = () => <div className={'${CONTENT}'} />;
+`;
+ const contentHead = (height = '480') => `import { createStaticStyles } from '@lobehub/ui';
+
+const MAX_HEIGHT = ${height};
+const RESIZED_IMAGE = 'img:is([style^="width:"], [style*=" width:"])';
+
+const fallback = createStaticStyles(({ css }) => ({
+ content: css\`
+ & img:not(\${RESIZED_IMAGE}) {
+ width: auto !important;
+ max-height: \${MAX_HEIGHT}px;
+ }
+
+ & [contenteditable='true'] ~ div {
+ margin-block-start: 0 !important;
+ }
+ \`,
+}));
+
+export const Content = () => <div className={fallback.content} />;
+`;
+ const run = (head: string, css = contentCss()) =>
+ planFile(
+ 'a.tsx',
+ extractFile(contentBase, 'a.tsx', options({ './Comment.css': css })),
+ extractFile(head, 'a.tsx', options({})),
+ { layoutComponents: [] },
+ ).cases[0];
+
+ it('folds the constants, ignores quote style and proves selectors it cannot render', () => {
+ const entry = run(contentHead());
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toContain('EMOTION_RULE_KEPT');
+ expect(entry.inner).toBeUndefined();
+ });
+
+ it('keeps the flag when a folded constant differs from the stylesheet value', () => {
+ const entry = run(contentHead('400'));
+ expect(entry.flags).toEqual(['INNER_TARGET']);
+ });
+});
+
+describe('a stylesheet class joined with StyleX classes in an expression', () => {
+ const MD = 'lobe-body-b06f-md';
+ const mdCss = `.${MD} > div {\n padding-block-end: 40px;\n}\n`;
+ const mdBase = (className: string) => `import './Body.css';
+
+import { Markdown } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ md: { overflow: 'hidden' } });
+
+export const Body = () => <Markdown className={${className}}>{text}</Markdown>;
+`;
+ const mdHead = (
+ host = '{...sx(styles.md, fallback.md)}',
+ ) => `import { createStaticStyles, Markdown } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({ md: { overflow: 'hidden' } });
+
+const fallback = createStaticStyles(({ css }) => ({
+ md: css\`
+ & > div {
+ padding-block-end: 40px;
+ }
+ \`,
+}));
+
+export const Body = () => <Markdown ${host}>{text}</Markdown>;
+`;
+ const run = (before: string, after = mdHead()) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({ './Body.css': mdCss })),
+ extractFile(after, 'a.tsx', options({})),
+ { layoutComponents: [] },
+ ).cases[0];
+
+ it('maps the class inside cx to its stylesheet and keeps the placement through sx', () => {
+ const entry = run(mdBase(`cx(stylex.props(styles.md).className, '${MD}')`));
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['PLACEMENT_PRESERVED', 'EMOTION_RULE_KEPT']);
+ });
+
+ it('maps the class inside a template literal', () => {
+ const entry = run(mdBase(`\`\${stylex.props(styles.md).className} \${'${MD}'}\``));
+ expect(entry.flags).not.toContain('INNER_TARGET');
+ expect(entry.evidence).toContain('EMOTION_RULE_KEPT');
+ });
+
+ it('maps the class written in the template text itself', () => {
+ const entry = run(mdBase(`\`\${stylex.props(styles.md).className} ${MD}\``));
+ expect(entry.flags).not.toContain('INNER_TARGET');
+ expect(entry.evidence).toContain('EMOTION_RULE_KEPT');
+ });
+
+ it('keeps the placement flag when head passes the fallback through another prop', () => {
+ const entry = run(
+ mdBase(`cx(stylex.props(styles.md).className, '${MD}')`),
+ mdHead('{...sx(styles.md)} classNames={{ root: fallback.md }}'),
+ );
+ expect(entry.flags).toContain('INNER_TARGET');
+ });
+});
+
+describe('a theme token read through a renamed import', () => {
+ it('resolves cssVar imported under another name', () => {
+ const css = `.docx-f4c0-scroll .docx-wrapper > section.docx {\n box-shadow: var(--lobe-box-shadow-tertiary);\n}\n`;
+ const before = `import './Docx.css';\n\nexport const Docx = () => <div className={'docx-f4c0-scroll'} />;\n`;
+ const after = (
+ token: string,
+ ) => `import { createStaticStyles, cssVar as cssVarValue } from '@lobehub/ui';
+
+const fallback = createStaticStyles(({ css }) => ({
+ scroll: css\`
+ .docx-wrapper > section.docx {
+ box-shadow: \${cssVarValue.${token}};
+ }
+ \`,
+}));
+
+export const Docx = () => <div className={fallback.scroll} />;
+`;
+ const run = (token: string) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({ './Docx.css': css })),
+ extractFile(after(token), 'a.tsx', options({})),
+ { layoutComponents: [] },
+ ).cases[0];
+ expect(run('boxShadowTertiary').flags).toEqual([]);
+ expect(run('boxShadowSecondary').flags).toContain('INNER_TARGET');
+ });
+});
+
+describe('a stylesheet class held in a local constant', () => {
+ it('maps the constant to its stylesheet and proves the rule restored in a fallback', () => {
+ const css = `.kanban-14c7-card * {\n cursor: default;\n}\n\n.kanban-14c7-card:active * {\n cursor: grabbing;\n}\n`;
+ const before = `import './Card.css';
+
+import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const CARD_SCOPE_CLASS = 'kanban-14c7-card';
+
+const styles = stylex.create({ card: { cursor: 'default' } });
+
+export const Card = () => <div {...sx([styles.card], CARD_SCOPE_CLASS)} />;
+`;
+ const after = (rule = 'cursor: grabbing;') => `import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({ card: { cursor: 'default' } });
+
+const fallback = createStaticStyles(({ css }) => ({
+ card: css\`
+ & * {
+ cursor: default;
+ }
+
+ &:active * {
+ ${rule}
+ }
+ \`,
+}));
+
+export const Card = () => <div {...sx([styles.card], fallback.card)} />;
+`;
+ const run = (head: string) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({ './Card.css': css })),
+ extractFile(head, 'a.tsx', options({})),
+ { layoutComponents: [] },
+ ).cases[0];
+ const base = extractFile(before, 'a.tsx', options({ './Card.css': css }));
+ expect(base.elements[0].slots).toContain('global.kanban-14c7-card');
+ expect(run(after()).evidence).toContain('EMOTION_RULE_KEPT');
+ expect(run(after()).flags).toEqual([]);
+ expect(run(after('cursor: move;')).evidence ?? []).not.toContain('EMOTION_RULE_KEPT');
+ });
+});
diff --git a/packages/style-equivalence/src/plan/knobs.test.ts b/packages/style-equivalence/src/plan/knobs.test.ts
new file mode 100644
index 00000000000..eac38228c88
--- /dev/null
+++ b/packages/style-equivalence/src/plan/knobs.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FileExtraction, StyleBinding, StyleElement, VariableUse } from '../extract';
+import { bindKnobs } from './knobs';
+import { planFile } from './planFile';
+
+const cls = (expr: string): StyleBinding => ({ expr, prop: 'className', spread: false });
+const spread = (expr: string): StyleBinding => ({ expr, prop: '...', spread: true });
+
+const el = (
+ id: string,
+ tag: string,
+ binding: StyleBinding,
+ variables: VariableUse[] = [],
+ extra: Partial<StyleElement> = {},
+): StyleElement => ({
+ bindings: [binding],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: id.split('#')[0],
+ slots: [],
+ tag,
+ variables,
+ ...extra,
+});
+
+const extraction = (
+ elements: StyleElement[],
+ slotProperties?: Record<string, string[]>,
+): FileExtraction => ({
+ elements,
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ slotProperties,
+ styleSymbols: ['styles'],
+});
+
+const config = { layoutComponents: ['Flexbox'] };
+const state: VariableUse[] = [{ kind: 'unknown', name: 'state' }];
+const variant: VariableUse[] = [{ kind: 'unknown', name: 'variant' }];
+const STATUS = "state.status === 'succeeded' || state.status === 'partial'";
+const RUNNING = "state.status !== 'running'";
+const CHIP_ARGS = `styles.chip, ${STATUS} ? styles.succeeded : ${RUNNING} && styles.failed`;
+
+const single = (base: StyleElement, head: StyleElement) =>
+ planFile('a.tsx', extraction([base]), extraction([head]), config).cases[0];
+
+describe('planFile condition knobs', () => {
+ it('models each condition of an otherwise unmodeled chain as a knob', () => {
+ const entry = single(
+ el('Chip#0', 'span', cls(`cx(${CHIP_ARGS})`), state),
+ el('Chip#0', 'span', spread(`stylex.props(${CHIP_ARGS})`), state),
+ );
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['CONDITION_KNOBS']);
+ expect(entry.knobs).toEqual([STATUS, RUNNING]);
+ expect(entry.variables).toEqual([]);
+ expect(entry.combos).toEqual([
+ { [RUNNING]: false, [STATUS]: false },
+ { [RUNNING]: false, [STATUS]: true },
+ { [RUNNING]: true, [STATUS]: false },
+ { [RUNNING]: true, [STATUS]: true },
+ ]);
+ });
+
+ it('binds the condition of a layout ancestor for every child case', () => {
+ const root = (expr: string) => el('Card#0', 'Flexbox', cls(expr), variant);
+ const child = (binding: StyleBinding) =>
+ el('Card#1', 'span', binding, [], { parent: 'Card#0' });
+ const [, inner] = planFile(
+ 'a.tsx',
+ extraction([
+ root("cx(styles.root, variant === 'card' ? styles.card : styles.listItem)"),
+ child(cls('styles.hostname')),
+ ]),
+ extraction([
+ root(
+ "cx(stylex.props(styles.root, variant === 'card' ? styles.card : styles.listItem).className)",
+ ),
+ child(spread('stylex.props(styles.hostname)')),
+ ]),
+ config,
+ ).cases;
+ expect(inner.flags).toEqual([]);
+ expect(inner.knobs).toEqual(["variant === 'card'"]);
+ expect(inner.combos).toHaveLength(2);
+ });
+
+ it('keeps the flag when the branches are swapped', () => {
+ const entry = single(
+ el('Row#0', 'div', cls("cx(styles.a, variant === 'card' ? styles.on : styles.off)"), variant),
+ el(
+ 'Row#0',
+ 'div',
+ cls("stylex.props(styles.a, variant === 'card' ? styles.off : styles.on).className"),
+ variant,
+ ),
+ );
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ expect(entry.knobs).toBeUndefined();
+ expect(entry.combos).toEqual([{}]);
+ });
+
+ it('keeps the flag when the conditions differ', () => {
+ const entry = single(
+ el('Row#0', 'div', cls("cx(styles.a, variant === 'card' && styles.on)"), variant),
+ el(
+ 'Row#0',
+ 'div',
+ cls("stylex.props(styles.a, variant !== 'card' && styles.on).className"),
+ variant,
+ ),
+ );
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when an unmodeled value is used as a class rather than a condition', () => {
+ const extra: VariableUse[] = [{ kind: 'unknown', name: 'extra' }];
+ const entry = single(
+ el('Row#0', 'div', cls('cx(styles.a, extra)'), extra),
+ el('Row#0', 'div', cls('cx(stylex.props(styles.a).className, extra)'), extra),
+ );
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when a condition sits in a shape the canonical form does not read', () => {
+ const sizes: VariableUse[] = [{ kind: 'unknown', name: 'size' }];
+ const entry = single(
+ el('Row#0', 'div', cls("cx(styles.a, SIZES[size] ?? (size === 'lg' && styles.b))"), sizes),
+ el(
+ 'Row#0',
+ 'div',
+ cls("stylex.props(styles.a, SIZES[size] ?? (size === 'lg' && styles.b)).className"),
+ sizes,
+ ),
+ );
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('models knobs once the replaced component is proven to receive the class unchanged', () => {
+ const status: VariableUse[] = [{ kind: 'unknown', name: 'status' }];
+ const entry = single(
+ el('Video#0', 'Text', cls("status === 'error' ? styles.error : undefined"), status),
+ el(
+ 'Video#0',
+ 'Text',
+ cls("stylex.props(status === 'error' ? styles.error : undefined).className"),
+ status,
+ ),
+ );
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['PLACEMENT_PRESERVED', 'CONDITION_KNOBS']);
+ expect(entry.knobs).toEqual(["status === 'error'"]);
+ });
+
+ it('keeps the flag when the replaced component does not receive the class the same way', () => {
+ const status: VariableUse[] = [{ kind: 'unknown', name: 'status' }];
+ const entry = single(
+ el('Video#0', 'Text', cls("status === 'error' ? styles.error : undefined"), status),
+ el(
+ 'Video#0',
+ 'Text',
+ cls(
+ "cx(stylex.props(styles.base).className, stylex.props(status === 'error' ? styles.error : undefined).className)",
+ ),
+ status,
+ ),
+ );
+ expect(entry.flags).toContain('VARIABLE_UNMODELED');
+ expect(entry.knobs).toBeUndefined();
+ });
+
+ it('keeps the flag when an ancestor changed its tag', () => {
+ const [, inner] = planFile(
+ 'a.tsx',
+ extraction([
+ el('Row#0', 'div', cls("variant === 'card' ? styles.card : styles.row"), variant, {
+ slots: ['styles.card', 'styles.row'],
+ }),
+ el('Row#1', 'span', cls('styles.label'), [], { parent: 'Row#0', slots: ['styles.label'] }),
+ ]),
+ extraction([
+ el(
+ 'Row#0',
+ 'section',
+ cls("stylex.props(variant === 'card' ? styles.card : styles.row).className"),
+ variant,
+ { slots: ['styles.card', 'styles.row'] },
+ ),
+ el('Row#1', 'span', cls('stylex.props(styles.label).className'), [], {
+ parent: 'Row#0',
+ slots: ['styles.label'],
+ }),
+ ]),
+ config,
+ ).cases;
+ expect(inner.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag for a hand-joined class whose sources overlap', () => {
+ const device: VariableUse[] = [{ kind: 'unknown', name: 'device' }];
+ const properties = {
+ 'styles.dot': ['border-width', 'border-style'],
+ 'styles.online': ['border-style'],
+ };
+ const [entry] = planFile(
+ 'a.tsx',
+ extraction(
+ [
+ el(
+ 'Dot#0',
+ 'span',
+ cls(
+ "[styles.dot, device.state === 'on' ? styles.online : undefined].filter(Boolean).join(' ')",
+ ),
+ device,
+ ),
+ ],
+ properties,
+ ),
+ extraction(
+ [
+ el(
+ 'Dot#0',
+ 'span',
+ cls(
+ "[stylex.props(styles.dot).className, device.state === 'on' ? stylex.props(styles.online).className : undefined].filter(Boolean).join(' ')",
+ ),
+ device,
+ ),
+ ],
+ properties,
+ ),
+ config,
+ ).cases;
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('enumerates more than four knobs pairwise and says so', () => {
+ const names = ['a', 'b', 'c', 'd', 'e'];
+ const args = names.map((name) => `item.${name} === 1 && styles.${name}`).join(', ');
+ const item: VariableUse[] = [{ kind: 'unknown', name: 'item' }];
+ const entry = single(
+ el('Row#0', 'div', cls(`cx(${args})`), item),
+ el('Row#0', 'div', cls(`stylex.props(${args}).className`), item),
+ );
+ expect(entry.knobs).toHaveLength(5);
+ expect(entry.flags).toEqual(['COMBINATIONS_PAIRWISE']);
+ });
+});
+
+describe('bindKnobs', () => {
+ it('replaces each knob expression wherever it appears, whitespace aside', () => {
+ expect(
+ bindKnobs("cx(styles.a, !(variant === 'card') && styles.b)", ["variant === 'card'"]),
+ ).toBe('cx(styles.a, !(__v["variant === \'card\'"]) && styles.b)');
+ });
+
+ it('does not merge knobs whose string literals differ only in spaces', () => {
+ expect(bindKnobs("x === 'a b' && styles.a", ["x === 'ab'"])).toBe("x === 'a b' && styles.a");
+ });
+
+ it('leaves property names alone', () => {
+ expect(bindKnobs('cx(item.active && styles.a, active && styles.b)', ['active'])).toBe(
+ 'cx(item.active && styles.a, __v["active"] && styles.b)',
+ );
+ });
+
+ it('returns undefined for an expression it cannot parse', () => {
+ expect(bindKnobs('cx(styles.a,', ['a'])).toBeUndefined();
+ });
+});
diff --git a/packages/style-equivalence/src/plan/knobs.ts b/packages/style-equivalence/src/plan/knobs.ts
new file mode 100644
index 00000000000..12b7fd31176
--- /dev/null
+++ b/packages/style-equivalence/src/plan/knobs.ts
@@ -0,0 +1,71 @@
+import ts from 'typescript';
+
+const printer = ts.createPrinter({ removeComments: true });
+
+const PREFIX = 'const __knob = (';
+
+const syntaxValid = (code: string) =>
+ !ts.transpileModule(code, {
+ compilerOptions: { jsx: ts.JsxEmit.Preserve },
+ fileName: 'knobs.tsx',
+ reportDiagnostics: true,
+ }).diagnostics?.length;
+
+export const parseExpression = (expr: string) => {
+ const code = `${PREFIX}${expr});`;
+ if (!syntaxValid(code)) return undefined;
+ const source = ts.createSourceFile(
+ 'knobs.tsx',
+ code,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const [statement] = source.statements;
+ if (!statement || !ts.isVariableStatement(statement)) return undefined;
+ const [declaration] = statement.declarationList.declarations;
+ const initializer = declaration?.initializer;
+ if (!initializer || !ts.isParenthesizedExpression(initializer)) return undefined;
+ return { expression: initializer.expression, source };
+};
+
+const isNameOnly = (node: ts.Node) => {
+ const { parent } = node;
+ return (
+ ts.isIdentifier(node) &&
+ ((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
+ (ts.isPropertyAssignment(parent) && parent.name === node))
+ );
+};
+
+export const knobText = (node: ts.Expression) =>
+ printer.printNode(ts.EmitHint.Expression, node, node.getSourceFile());
+
+export const knobReference = (knob: string) => `__v[${JSON.stringify(knob)}]`;
+
+export const bindKnobs = (expr: string, knobs: readonly string[]) => {
+ const parsed = parseExpression(expr);
+ if (!parsed) return undefined;
+ const wanted = new Set(knobs);
+ const replacements: Array<{ end: number; knob: string; start: number }> = [];
+ const visit = (node: ts.Node) => {
+ if (ts.isShorthandPropertyAssignment(node)) return;
+ if (ts.isExpression(node) && !ts.isParenthesizedExpression(node) && !isNameOnly(node)) {
+ const text = knobText(node);
+ if (wanted.has(text)) {
+ replacements.push({
+ end: node.end - PREFIX.length,
+ knob: text,
+ start: node.getStart(parsed.source) - PREFIX.length,
+ });
+ return;
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(parsed.expression);
+ let result = expr;
+ for (const { end, knob, start } of replacements.reverse())
+ result = `${result.slice(0, start)}${knobReference(knob)}${result.slice(end)}`;
+ return result;
+};
diff --git a/packages/style-equivalence/src/plan/moved.test.ts b/packages/style-equivalence/src/plan/moved.test.ts
new file mode 100644
index 00000000000..5bbeb37d80d
--- /dev/null
+++ b/packages/style-equivalence/src/plan/moved.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../extract/adapters/globalCss';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const CLASS = 'lobe-view-1a2b3c4d-tabs';
+
+const TABS_CSS = `/* moved */
+.${CLASS} [role='tablist'] {
+ width: 100%;
+}
+
+.${CLASS} [role='tablist'] > [role='tab']:has([data-replace-all]) {
+ margin-inline-start: auto;
+}
+`;
+
+const tabsBase = (
+ nested = `[role='tablist'] {
+ width: 100%;
+
+ > [role='tab']:has([data-replace-all]) {
+ margin-inline-start: auto;
+ }
+ }`,
+) => `import { createStaticStyles, Tabs } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ tabs: css\`
+ ${nested}
+ \`,
+}));
+
+export const View = () => <Tabs className={styles.tabs} variant="square" />;
+`;
+
+const tabsHead = (className = `'${CLASS}'`) => `import './View.css';
+
+import { Tabs } from '@lobehub/ui';
+
+export const View = () => (
+ <>
+ <Tabs className={${className}} variant="square" />
+ </>
+);
+`;
+
+const embedBase = `import { createStaticStyles, Flexbox } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css\`
+ padding: 24px;
+
+ h1 {
+ white-space: normal;
+ }
+ \`,
+}));
+
+export const Embed = () => <Flexbox className={styles.content} gap={24} />;
+`;
+
+const embedHead = `import './Embed.css';
+
+import { cx, Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ content: { padding: '24px' } });
+
+export const Embed = () => (
+ <Flexbox gap={24} className={cx(stylex.props(styles.content).className, 'lobe-embed-content')} />
+);
+`;
+
+const options = (css: Record<string, string>) => ({
+ adapters: [emotionStaticAdapter, stylexAdapter, globalCssAdapter],
+ layoutComponents: ['Flexbox'],
+ readStylesheet: (_from: string, specifier: string) => css[specifier],
+});
+
+const plan = (before: string, after: string, css: Record<string, string>) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options({})),
+ extractFile(after, 'a.tsx', options(css)),
+ { layoutComponents: ['Flexbox'] },
+ ).cases;
+
+describe('css moved word for word into a plain stylesheet', () => {
+ it('records the declarations of each rule and the stylesheet it came from', () => {
+ const { rules } = extractFile(tabsHead(), 'a.tsx', options({ './View.css': TABS_CSS }));
+ expect(rules[0]).toMatchObject({
+ declarations: ['width: 100%'],
+ selector: `.${CLASS} [role='tablist']`,
+ stylesheet: './View.css',
+ });
+ const [base] = extractFile(tabsBase(), 'a.tsx', options({})).rules;
+ expect(base.declarations).toEqual(['width: 100%']);
+ });
+
+ it('proves the class lands where the emotion class did and renders the targets it selects', () => {
+ const [entry] = plan(tabsBase(), tabsHead(), { './View.css': TABS_CSS });
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['PLACEMENT_PRESERVED', 'STYLESHEET_MOVED']);
+ expect(entry.inner).toEqual({
+ 0: [
+ {
+ attributes: { role: 'tablist' },
+ children: [
+ {
+ attributes: { role: 'tab' },
+ children: [{ attributes: { 'data-replace-all': '' }, children: [], tag: 'div' }],
+ tag: 'div',
+ },
+ ],
+ tag: 'div',
+ },
+ ],
+ });
+ });
+
+ it('clears an inner tag target once the moved rule renders on both sides', () => {
+ const [entry] = plan(embedBase, embedHead, {
+ './Embed.css': '.lobe-embed-content h1 {\n white-space: normal;\n}\n',
+ });
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['STYLESHEET_MOVED']);
+ expect(entry.inner).toEqual({ 0: [{ attributes: {}, children: [], tag: 'h1' }] });
+ });
+
+ it('keeps the flags when a declaration changed on the way', () => {
+ const [entry] = plan(tabsBase(), tabsHead(), {
+ './View.css': TABS_CSS.replace('width: 100%', 'width: 50%'),
+ });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ expect(entry.inner).toBeUndefined();
+ });
+
+ it('keeps the flags when the stylesheet holds a rule nothing moved', () => {
+ const [entry] = plan(tabsBase(), tabsHead(), {
+ './View.css': `${TABS_CSS}\n[role='tab'] { color: red; }\n`,
+ });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ });
+
+ it('keeps the flags when the rules are in a different order', () => {
+ const [first, second] = TABS_CSS.split('\n\n');
+ const [entry] = plan(tabsBase(), tabsHead(), { './View.css': `${second}\n\n${first}\n` });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ });
+
+ it('keeps the flags when the moved rules sit in a cascade layer', () => {
+ const [entry] = plan(tabsBase(), tabsHead(), {
+ './View.css': `@layer app {\n${TABS_CSS}\n}\n`,
+ });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ });
+
+ it('keeps the flags when a selector needs a state the page cannot build', () => {
+ const nested = `[role='tablist']:first-child {
+ width: 100%;
+ }`;
+ const [entry] = plan(tabsBase(nested), tabsHead(), {
+ './View.css': `.${CLASS} [role='tablist']:first-child {\n width: 100%;\n}\n`,
+ });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ });
+
+ it('keeps the flags when the class also lands on another element', () => {
+ const head = tabsHead().replace(' </>', ` <div className={'${CLASS}'} />\n </>`);
+ const [entry] = plan(tabsBase(), head, { './View.css': TABS_CSS });
+ expect(entry.flags).toEqual(['PLACEMENT_SUBSTITUTED']);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/moved.ts b/packages/style-equivalence/src/plan/moved.ts
new file mode 100644
index 00000000000..080f8c47607
--- /dev/null
+++ b/packages/style-equivalence/src/plan/moved.ts
@@ -0,0 +1,158 @@
+import selectorParser from 'postcss-selector-parser';
+import ts from 'typescript';
+
+import type { FileExtraction, StyleElement, StyleRule } from '../extract';
+import { SELF } from '../extract/css';
+import { classNamesIn } from '../extract/selectors';
+import { elementsOf } from './descendants';
+import { type InnerNode, innerTargets } from './inner';
+
+export interface MovedProof {
+ head: string;
+ nodes: InnerNode[];
+ placement?: string;
+ rules: StyleRule[];
+ slots: string[];
+ tokens: string[];
+}
+
+const literalTokens = (element: StyleElement) => {
+ const tokens = new Set<string>();
+ for (const binding of element.bindings) {
+ const source = ts.createSourceFile('t.ts', `(${binding.expr});`, ts.ScriptTarget.Latest, true);
+ const visit = (node: ts.Node) => {
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
+ for (const token of node.text.split(/\s+/)) if (token) tokens.add(token);
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ return tokens;
+};
+
+export const normalizeSelector = (selector: string, from?: string, to?: string) => {
+ let count = 0;
+ let selectors = 0;
+ try {
+ const result = selectorParser((root) => {
+ selectors = root.nodes.length;
+ root.walkAttributes((node) => {
+ if (node.value !== undefined) node.quoteMark = '"';
+ });
+ if (from === undefined) return;
+ root.walkClasses((node) => {
+ if (node.value !== from) return;
+ count += 1;
+ node.value = to!;
+ });
+ }).processSync(selector, { lossless: false });
+ return from === undefined || count === selectors ? result : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const emitted = (rules: StyleRule[]) => rules.filter((rule) => rule.declarations?.length);
+
+const sameRule = (base: StyleRule, head: StyleRule, token: string) => {
+ const selector = normalizeSelector(base.selector, SELF, token);
+ return (
+ !!selector &&
+ selector === normalizeSelector(head.selector) &&
+ !base.conditions.some((condition) => condition.startsWith('@layer')) &&
+ JSON.stringify(base.conditions) === JSON.stringify(head.conditions) &&
+ JSON.stringify(base.declarations) === JSON.stringify(head.declarations)
+ );
+};
+
+const isSlotAccess = (expr: string, slot: string) => expr.replaceAll(/\s+/g, '') === slot;
+
+const placementOf = (base: StyleElement, head: StyleElement, slot: string, token: string) => {
+ const [left] = base.bindings;
+ const [right] = head.bindings;
+ if (base.bindings.length !== 1 || head.bindings.length !== 1) return undefined;
+ if (left.spread || right.spread || left.prop !== 'className' || right.prop !== 'className')
+ return undefined;
+ const literal = ts.createSourceFile('t.ts', `(${right.expr});`, ts.ScriptTarget.Latest, true);
+ const [statement] = literal.statements;
+ const value = statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;
+ const inner = value && ts.isParenthesizedExpression(value) ? value.expression : value;
+ return inner &&
+ ts.isStringLiteralLike(inner) &&
+ inner.text.trim() === token &&
+ isSlotAccess(left.expr, slot)
+ ? left.expr
+ : undefined;
+};
+
+const proveElement = (
+ base: StyleElement,
+ head: StyleElement,
+ rules: { base: StyleRule[]; head: StyleRule[] },
+): MovedProof | undefined => {
+ const tokens = literalTokens(head);
+ const moved: StyleRule[] = [];
+ const selectors: string[] = [];
+ const slots: string[] = [];
+ const used: string[] = [];
+ let placement: string | undefined;
+ for (const slot of base.slots) {
+ const own = emitted(rules.base.filter((rule) => rule.slot === slot));
+ if (!own.length) continue;
+ const token = [...tokens].find((candidate) => {
+ const targets = emitted(
+ rules.head.filter(
+ (rule) => rule.stylesheet && classNamesIn(rule.selector).includes(candidate),
+ ),
+ );
+ return (
+ targets.length === own.length &&
+ own.every((rule, index) => sameRule(rule, targets[index], candidate))
+ );
+ });
+ if (!token) return undefined;
+ slots.push(slot);
+ used.push(token);
+ moved.push(
+ ...rules.head.filter(
+ (rule) => rule.stylesheet && classNamesIn(rule.selector).includes(token),
+ ),
+ );
+ selectors.push(...own.map((rule) => rule.selector));
+ placement = base.slots.length === 1 ? placementOf(base, head, slot, token) : undefined;
+ }
+ if (!moved.length) return undefined;
+ const nodes = innerTargets(selectors, SELF);
+ return nodes && { head: head.id, nodes, placement, rules: moved, slots, tokens: used };
+};
+
+export const movedStylesheets = (
+ base: FileExtraction,
+ head: FileExtraction,
+ pairs: Array<[StyleElement, StyleElement]>,
+) => {
+ const proofs = new Map<string, MovedProof>();
+ const slotUsers = (slot: string) =>
+ elementsOf(base).filter((element) => element.slots.includes(slot)).length;
+ const tokenUsers = new Map<string, number>();
+ for (const element of head.elements)
+ for (const token of literalTokens(element))
+ tokenUsers.set(token, (tokenUsers.get(token) ?? 0) + 1);
+ for (const [left, right] of pairs) {
+ const proof = proveElement(left, right, { base: base.rules, head: head.rules });
+ if (!proof) continue;
+ const unique =
+ proof.slots.every((slot) => slotUsers(slot) === 1) &&
+ proof.tokens.every((token) => tokenUsers.get(token) === 1);
+ if (unique) proofs.set(left.id, proof);
+ }
+ const used = new Set([...proofs.values()].flatMap((proof) => proof.rules));
+ const incomplete = new Set(
+ emitted(head.rules)
+ .filter((rule) => rule.stylesheet && !used.has(rule))
+ .map((rule) => rule.stylesheet),
+ );
+ for (const [id, proof] of proofs)
+ if (proof.rules.some((rule) => incomplete.has(rule.stylesheet))) proofs.delete(id);
+ return proofs;
+};
diff --git a/packages/style-equivalence/src/plan/neutral.test.ts b/packages/style-equivalence/src/plan/neutral.test.ts
new file mode 100644
index 00000000000..ad7d89f2bf5
--- /dev/null
+++ b/packages/style-equivalence/src/plan/neutral.test.ts
@@ -0,0 +1,78 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const base = (element = '<Select className={styles.select} />') => `
+import { createStaticStyles } from '@lobehub/ui';
+import { Select } from './Select';
+
+const styles = createStaticStyles(({ css }) => ({
+ select: css\`width: 100%;\`,
+ popup: css\`padding: 4px;\`,
+}));
+
+export const View = () => ${element};
+`;
+
+const head = (
+ element = '<Select classNames={{ root: stylex.props(styles.select).className }} />',
+) => `
+import * as stylex from '@stylexjs/stylex';
+import { Select } from './Select';
+
+const styles = stylex.create({ select: { width: '100%' }, popup: { padding: '4px' } });
+
+export const View = () => ${element};
+`;
+
+const generated = (before: string, after: string) => {
+ const extractions = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ const plan = planFile('a.tsx', extractions.base, extractions.head, {
+ layoutComponents: ['Flexbox'],
+ });
+ return {
+ base: generateModule(extractions.base, plan, 'base', { layoutComponents: ['Flexbox'] }),
+ head: generateModule(extractions.head, plan, 'head', { layoutComponents: ['Flexbox'] }),
+ plan,
+ };
+};
+
+describe('slot props on a stand-in', () => {
+ it('leaves out slot probes that only one side has, so they do not reshape the stand-in', () => {
+ const { head: module, plan } = generated(base(), head());
+ expect(plan.cases[0].neutralOmitted).toEqual([0]);
+ expect(plan.cases[0].flags).toContain('PLACEMENT_NEUTRAL_PROP');
+ expect(module).not.toContain('__neutral("classNames"');
+ });
+
+ it('keeps slot probes that both sides pass with the same keys', () => {
+ const {
+ base: before,
+ head: after,
+ plan,
+ } = generated(
+ base('<Select classNames={{ popup: styles.popup }} />'),
+ head('<Select classNames={{ popup: stylex.props(styles.popup).className }} />'),
+ );
+ expect(plan.cases[0].neutralOmitted).toBeUndefined();
+ expect(before).toContain('__neutral("classNames"');
+ expect(after).toContain('__neutral("classNames"');
+ });
+
+ it('leaves out probes whose slot keys differ between the sides', () => {
+ const { plan } = generated(
+ base('<Select classNames={{ popup: styles.popup }} />'),
+ head('<Select classNames={{ root: stylex.props(styles.popup).className }} />'),
+ );
+ expect(plan.cases[0].neutralOmitted).toEqual([0]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/neutral.ts b/packages/style-equivalence/src/plan/neutral.ts
new file mode 100644
index 00000000000..95619e782b6
--- /dev/null
+++ b/packages/style-equivalence/src/plan/neutral.ts
@@ -0,0 +1,41 @@
+import ts from 'typescript';
+
+import type { StyleElement } from '../extract';
+import { parseExpression } from './knobs';
+
+type Sides<T> = Record<'base' | 'head', T>;
+
+const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;
+
+const keysOf = (expr: string) => {
+ const parsed = parseExpression(expr);
+ const node = parsed && unwrap(parsed.expression);
+ if (!node || !ts.isObjectLiteralExpression(node)) return '';
+ return node.properties
+ .map((property) => property.name?.getText() ?? '…')
+ .sort()
+ .join(',');
+};
+
+const signatureOf = (element: StyleElement | undefined) =>
+ (element?.bindings ?? [])
+ .filter((binding) => !binding.spread && binding.prop !== 'className')
+ .map(
+ (binding) =>
+ `${binding.prop === 'styles' ? 'classNames' : binding.prop}:${keysOf(binding.expansion ?? binding.expr)}`,
+ )
+ .sort()
+ .join(';');
+
+export const neutralOmitted = (chains: Sides<StyleElement[]>) => {
+ const indices: number[] = [];
+ const length = Math.max(chains.base.length, chains.head.length);
+ for (let index = 0; index < length; index++) {
+ const left = signatureOf(chains.base[index]);
+ const right = signatureOf(chains.head[index]);
+ if ((left || right) && (left !== right || chains.base.length !== chains.head.length))
+ indices.push(index);
+ }
+ return indices;
+};
diff --git a/packages/style-equivalence/src/plan/pair.ts b/packages/style-equivalence/src/plan/pair.ts
new file mode 100644
index 00000000000..cfe0d2e3dbb
--- /dev/null
+++ b/packages/style-equivalence/src/plan/pair.ts
@@ -0,0 +1,48 @@
+import type { StyleElement } from '../extract';
+
+const localSlots = (element: StyleElement) =>
+ new Set(element.slots.map((slot) => slot.slice(slot.indexOf('.') + 1)));
+
+export const matchScore = (a: StyleElement, b: StyleElement) => {
+ const left = localSlots(a);
+ const right = localSlots(b);
+ const shared = [...left].filter((slot) => right.has(slot)).length;
+ const union = new Set([...left, ...right]).size;
+ const overlap = union ? shared / union : 0;
+ if (a.tag !== b.tag && overlap === 0) return 0;
+ return (a.tag === b.tag ? 1 : 0) + overlap * 2;
+};
+
+export const alignElements = (base: StyleElement[], head: StyleElement[]) => {
+ const rows = base.length + 1;
+ const cols = head.length + 1;
+ const score = Array.from({ length: rows }, () => Array.from({ length: cols }, () => 0));
+ for (let i = 1; i < rows; i++)
+ for (let j = 1; j < cols; j++) {
+ const match = matchScore(base[i - 1], head[j - 1]);
+ score[i][j] = Math.max(
+ score[i - 1][j],
+ score[i][j - 1],
+ match > 0 ? score[i - 1][j - 1] + match : -Infinity,
+ );
+ }
+ const pairs: Array<[StyleElement, StyleElement]> = [];
+ let i = base.length;
+ let j = head.length;
+ while (i > 0 && j > 0) {
+ const match = matchScore(base[i - 1], head[j - 1]);
+ if (match > 0 && score[i][j] === score[i - 1][j - 1] + match) {
+ pairs.unshift([base[i - 1], head[j - 1]]);
+ i--;
+ j--;
+ } else if (score[i][j] === score[i - 1][j]) i--;
+ else j--;
+ }
+ const pairedBase = new Set(pairs.map(([a]) => a));
+ const pairedHead = new Set(pairs.map(([, b]) => b));
+ return {
+ pairs,
+ unpairedBase: base.filter((element) => !pairedBase.has(element)),
+ unpairedHead: head.filter((element) => !pairedHead.has(element)),
+ };
+};
diff --git a/packages/style-equivalence/src/plan/placement.test.ts b/packages/style-equivalence/src/plan/placement.test.ts
new file mode 100644
index 00000000000..5c096e43ced
--- /dev/null
+++ b/packages/style-equivalence/src/plan/placement.test.ts
@@ -0,0 +1,540 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractFile, type StyleBinding, type StyleElement } from '../extract';
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { placementPreserved } from './placement';
+import { planFile } from './planFile';
+
+const el = (
+ tag: string,
+ bindings: StyleBinding[],
+ extra: Partial<StyleElement> = {},
+): StyleElement => ({
+ bindings,
+ flags: [],
+ id: 'Row#0',
+ literalProps: {},
+ owner: 'Row',
+ slots: [],
+ tag,
+ variables: [],
+ ...extra,
+});
+
+const cls = (expr: string): StyleBinding => ({ expr, prop: 'className', spread: false });
+const spread = (expr: string): StyleBinding => ({ expr, prop: '...', spread: true });
+const prop = (name: string, expr: string): StyleBinding => ({ expr, prop: name, spread: false });
+
+describe('placementPreserved', () => {
+ it('accepts className rewritten through one stylex.props call', () => {
+ expect(
+ placementPreserved(
+ [el('SkillsIcon', [cls('styles.skillIcon')], { literalProps: { size: 12 } })],
+ [
+ el('SkillsIcon', [cls('stylex.props(styles.skillIcon).className')], {
+ literalProps: { size: 12 },
+ }),
+ ],
+ ),
+ ).toBe(true);
+ });
+
+ it('treats a stylex.props spread as className', () => {
+ expect(
+ placementPreserved(
+ [el('Card', [cls('styles.chip')])],
+ [el('Card', [spread('stylex.props(styles.chip)')])],
+ ),
+ ).toBe(true);
+ });
+
+ describe('variadic sx', () => {
+ const properties = { 'styles.a': ['display'], 'styles.b': ['color'] };
+ const preserved = (head: string, slots: Record<string, string[]> = properties) =>
+ placementPreserved(
+ [el('Text', [cls('cx(styles.a, active && styles.b, className)')])],
+ [el('Text', [spread(head)])],
+ { properties: { base: slots, head: slots } },
+ );
+
+ it('reads StyleX slots and a caller className in any argument', () => {
+ expect(preserved('sx(styles.a, active && styles.b, className)')).toBe(true);
+ expect(preserved('sx([styles.a, active && styles.b], className)')).toBe(true);
+ });
+
+ it('does not treat a class from outside StyleX as a StyleX slot', () => {
+ expect(preserved('sx(styles.a, active && styles.b, fallback.content)')).toBe(false);
+ expect(preserved('sx(styles.a, active && styles.b, className)', {})).toBe(false);
+ });
+
+ it('leaves a call carrying an inline style unproven', () => {
+ expect(preserved('sx(styles.a, active && styles.b, className, { width: 1 })')).toBe(false);
+ expect(preserved('sx(styles.a, active && styles.b, className, {})')).toBe(true);
+ });
+ });
+
+ it('accepts cx terms with conditions rewritten into one stylex.props call', () => {
+ expect(
+ placementPreserved(
+ [el('Text', [cls('cx(styles.a, active && styles.b)')])],
+ [el('Text', [cls('stylex.props(styles.a, active && styles.b).className')])],
+ ),
+ ).toBe(true);
+ });
+
+ it('compares object props key by key', () => {
+ expect(
+ placementPreserved(
+ [
+ el('Checkbox', [
+ prop(
+ 'classNames',
+ '{ text: cx(styles.textPending, isCompleted && styles.textCompleted), wrapper: styles.itemRow }',
+ ),
+ ]),
+ ],
+ [
+ el('Checkbox', [
+ prop(
+ 'classNames',
+ '{ text: cx(stylex.props(styles.textPending, isCompleted && styles.textCompleted).className), wrapper: stylex.props(styles.itemRow).className }',
+ ),
+ ]),
+ ],
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects separate stylex.props calls joined by hand', () => {
+ expect(
+ placementPreserved(
+ [
+ el('Dot', [
+ cls(
+ "[styles.statusDot, online ? styles.statusDotOnline : undefined].filter(Boolean).join(' ')",
+ ),
+ ]),
+ ],
+ [
+ el('Dot', [
+ cls(
+ "[stylex.props(styles.statusDot).className, stylex.props(online ? styles.statusDotOnline : undefined).className].filter(Boolean).join(' ')",
+ ),
+ ]),
+ ],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects two stylex.props calls inside one cx', () => {
+ expect(
+ placementPreserved(
+ [el('Dot', [cls('cx(styles.a, styles.b)')])],
+ [
+ el('Dot', [
+ cls('cx(stylex.props(styles.a).className, stylex.props(styles.b).className)'),
+ ]),
+ ],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a changed tag', () => {
+ expect(
+ placementPreserved(
+ [el('Icon', [cls('styles.a')])],
+ [el('SkillsIcon', [cls('stylex.props(styles.a).className')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a changed prop', () => {
+ expect(
+ placementPreserved(
+ [el('Menu', [cls('styles.a')])],
+ [el('Menu', [prop('rootClassName', 'stylex.props(styles.a).className')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a changed object key', () => {
+ expect(
+ placementPreserved(
+ [el('Checkbox', [prop('classNames', '{ wrapper: styles.w }')])],
+ [el('Checkbox', [prop('classNames', '{ root: stylex.props(styles.w).className }')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects swapped ternary branches', () => {
+ expect(
+ placementPreserved(
+ [el('Row', [cls('active ? styles.on : styles.off')])],
+ [el('Row', [cls('stylex.props(active ? styles.off : styles.on).className')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects reordered terms', () => {
+ expect(
+ placementPreserved(
+ [el('Row', [cls('cx(styles.a, styles.b)')])],
+ [el('Row', [cls('stylex.props(styles.b, styles.a).className')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects changed literal props', () => {
+ expect(
+ placementPreserved(
+ [el('Icon', [cls('styles.a')], { literalProps: { size: 12 } })],
+ [el('Icon', [cls('stylex.props(styles.a).className')], { literalProps: { size: 14 } })],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a bare stylex.props object passed where a class string is expected', () => {
+ expect(
+ placementPreserved(
+ [el('Menu', [prop('itemClassName', 'styles.a')])],
+ [el('Menu', [prop('itemClassName', 'stylex.props(styles.a)')])],
+ ),
+ ).toBe(false);
+ expect(
+ placementPreserved(
+ [el('Checkbox', [prop('classNames', '{ text: styles.a }')])],
+ [el('Checkbox', [prop('classNames', '{ text: stylex.props(styles.a) }')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects style slots left outside the single stylex.props call', () => {
+ expect(
+ placementPreserved(
+ [el('Row', [cls('cx(styles.a, styles.b)')])],
+ [el('Row', [cls('cx(styles.a, stylex.props(styles.b).className)')])],
+ ),
+ ).toBe(false);
+ });
+
+ it('fails closed on shapes it does not understand', () => {
+ expect(
+ placementPreserved(
+ [el('Row', [cls('`${styles.a} extra`')])],
+ [el('Row', [cls('`${stylex.props(styles.a).className} extra`')])],
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('placementPreserved on replaced elements only', () => {
+ const ancestor = (expr: string, tag = 'div') => el(tag, [cls(expr)], { id: 'Row#0' });
+ const icon = (expr: string) =>
+ el('Icon', [cls(expr)], { id: 'Row#1', literalProps: { size: 14 }, parent: 'Row#0' });
+
+ it('ignores a reordered merge on an intrinsic ancestor', () => {
+ expect(
+ placementPreserved(
+ [ancestor('cx(inspectorTextStyles.root, styles.root)'), icon('styles.icon')],
+ [
+ ancestor('cx(stylex.props(styles.root).className, inspectorTextStyles.root)'),
+ icon('stylex.props(styles.icon).className'),
+ ],
+ ),
+ ).toBe(true);
+ });
+
+ it('ignores a changed binding on a layout ancestor', () => {
+ expect(
+ placementPreserved(
+ [ancestor('cx(styles.a, styles.b)', 'Flexbox'), icon('styles.icon')],
+ [
+ ancestor('stylex.props(styles.b, styles.a).className', 'Flexbox'),
+ icon('stylex.props(styles.icon).className'),
+ ],
+ { layoutComponents: ['Flexbox'] },
+ ),
+ ).toBe(true);
+ });
+
+ it('still compares a component ancestor that is not a layout component', () => {
+ expect(
+ placementPreserved(
+ [ancestor('cx(styles.a, styles.b)', 'Flexbox'), icon('styles.icon')],
+ [
+ ancestor('stylex.props(styles.b, styles.a).className', 'Flexbox'),
+ icon('stylex.props(styles.icon).className'),
+ ],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a changed intrinsic ancestor tag', () => {
+ expect(
+ placementPreserved(
+ [ancestor('styles.root'), icon('styles.icon')],
+ [
+ ancestor('stylex.props(styles.root).className', 'span'),
+ icon('stylex.props(styles.icon).className'),
+ ],
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects chains of different length', () => {
+ expect(
+ placementPreserved(
+ [ancestor('styles.root'), icon('styles.icon')],
+ [icon('stylex.props(styles.icon).className')],
+ ),
+ ).toBe(false);
+ });
+
+ it('still compares an intrinsic element that passes a style through a neutral prop', () => {
+ expect(
+ placementPreserved(
+ [el('div', [prop('style', 'styles.a')])],
+ [el('div', [prop('style', 'stylex.props(styles.b).style')])],
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('placementPreserved on hand-joined classes', () => {
+ const disjoint = {
+ base: {
+ 'styles.activated': ['color', 'background'],
+ 'styles.badge': ['display', 'padding-inline', 'border-radius'],
+ },
+ head: {
+ 'styles.activated': ['color', 'background-color', 'background-image'],
+ 'styles.badge': ['display', 'padding-inline', 'border-radius'],
+ },
+ };
+ const badge = (expr: string) => [el('Badge', [cls(expr)])];
+
+ it('accepts an array join of separate stylex.props calls whose slots do not overlap', () => {
+ expect(
+ placementPreserved(
+ badge("[styles.badge, styles.activated].join(' ')"),
+ badge(
+ "[stylex.props(styles.badge).className, stylex.props(styles.activated).className].join(' ')",
+ ),
+ { properties: disjoint },
+ ),
+ ).toBe(true);
+ });
+
+ it('accepts a join on one side and one merge with the same ordered terms on the other', () => {
+ expect(
+ placementPreserved(
+ badge("[styles.badge, styles.activated].join(' ')"),
+ badge('stylex.props(styles.badge, styles.activated).className'),
+ { properties: disjoint },
+ ),
+ ).toBe(true);
+ });
+
+ it('accepts a template literal join with a condition in one source', () => {
+ const properties = {
+ 'styles.code': ['margin-inline-start', 'font-family', 'font-size'],
+ 'styles.error': ['color'],
+ 'styles.success': ['color'],
+ };
+ expect(
+ placementPreserved(
+ badge('`${styles.code} ${success ? styles.success : styles.error}`'),
+ badge(
+ '`${stylex.props(styles.code).className} ${stylex.props(success ? styles.success : styles.error).className}`',
+ ),
+ { properties: { base: properties, head: properties } },
+ ),
+ ).toBe(true);
+ });
+
+ it('accepts cx over the className of separate stylex.props calls', () => {
+ expect(
+ placementPreserved(
+ badge('cx(styles.badge, styles.activated)'),
+ badge('cx(stylex.props(styles.badge).className, stylex.props(styles.activated).className)'),
+ { properties: disjoint },
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects joined sources that set the same property in any branch', () => {
+ const properties = {
+ 'styles.statusDot': ['width', 'border-width', 'border-style', 'border-color'],
+ 'styles.statusDotOnline': ['border-style', 'background-color'],
+ };
+ const base = badge(
+ "[styles.statusDot, online ? styles.statusDotOnline : undefined].filter(Boolean).join(' ')",
+ );
+ const head = badge(
+ "[stylex.props(styles.statusDot).className, online ? stylex.props(styles.statusDotOnline).className : undefined].filter(Boolean).join(' ')",
+ );
+ expect(
+ placementPreserved(base, head, { properties: { base: properties, head: properties } }),
+ ).toBe(false);
+ const apart = { ...properties, 'styles.statusDotOnline': ['background-color'] };
+ expect(placementPreserved(base, head, { properties: { base: apart, head: apart } })).toBe(true);
+ });
+
+ it('rejects joined sources that overlap only through a shorthand', () => {
+ const properties = { 'styles.a': ['padding-inline'], 'styles.b': ['padding-left'] };
+ expect(
+ placementPreserved(
+ badge("[styles.a, styles.b].join(' ')"),
+ badge("[stylex.props(styles.a).className, stylex.props(styles.b).className].join(' ')"),
+ { properties: { base: properties, head: properties } },
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a join when one side does not know what a slot sets', () => {
+ expect(
+ placementPreserved(
+ badge("[styles.badge, styles.activated].join(' ')"),
+ badge(
+ "[stylex.props(styles.badge).className, stylex.props(styles.activated).className].join(' ')",
+ ),
+ { properties: { base: disjoint.base, head: { 'styles.badge': ['display'] } } },
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects joins that do not separate the classes with whitespace', () => {
+ const properties = { base: disjoint.base, head: disjoint.head };
+ expect(
+ placementPreserved(
+ badge('`${styles.badge}${styles.activated}`'),
+ badge(
+ '`${stylex.props(styles.badge).className}${stylex.props(styles.activated).className}`',
+ ),
+ { properties },
+ ),
+ ).toBe(false);
+ expect(
+ placementPreserved(
+ badge("[styles.badge, styles.activated].join('')"),
+ badge(
+ "[stylex.props(styles.badge).className, stylex.props(styles.activated).className].join('')",
+ ),
+ { properties },
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects swapped sources even when they do not overlap', () => {
+ expect(
+ placementPreserved(
+ badge("[styles.badge, styles.activated].join(' ')"),
+ badge(
+ "[stylex.props(styles.activated).className, stylex.props(styles.badge).className].join(' ')",
+ ),
+ { properties: disjoint },
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a joined source that leaves a slot outside its stylex.props call', () => {
+ expect(
+ placementPreserved(
+ badge("[cx(styles.badge, styles.activated)].join(' ')"),
+ badge("[cx(stylex.props(styles.badge).className, styles.activated)].join(' ')"),
+ { properties: disjoint },
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('planFile placement evidence', () => {
+ it('drops placement flags and records evidence for an identical chain', () => {
+ const base = el('SkillsIcon', [cls('styles.skillIcon')], { slots: ['styles.skillIcon'] });
+ const head = el('SkillsIcon', [cls('stylex.props(styles.skillIcon).className')], {
+ slots: ['styles.skillIcon'],
+ });
+ const extraction = (element: StyleElement) => ({
+ elements: [element],
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ styleSymbols: ['styles'],
+ });
+ const [plan] = planFile('a.tsx', extraction(base), extraction(head), {
+ layoutComponents: [],
+ }).cases;
+ expect(plan.flags).toEqual([]);
+ expect(plan.evidence).toEqual(['PLACEMENT_PRESERVED']);
+ });
+
+ it('drops the placement flag when only an intrinsic ancestor of the replaced icon changed', () => {
+ const root = (expr: string) =>
+ el('div', [cls(expr)], { id: 'List#0', owner: 'List', slots: ['styles.root'] });
+ const icon = (expr: string) =>
+ el('Icon', [cls(expr)], {
+ id: 'List#1',
+ literalProps: { size: 14 },
+ owner: 'List',
+ parent: 'List#0',
+ slots: ['styles.icon'],
+ });
+ const extraction = (elements: StyleElement[]) => ({
+ elements,
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ styleSymbols: ['styles'],
+ });
+ const [, plan] = planFile(
+ 'a.tsx',
+ extraction([root('cx(inspectorTextStyles.root, styles.root)'), icon('styles.icon')]),
+ extraction([
+ root('cx(stylex.props(styles.root).className, inspectorTextStyles.root)'),
+ icon('stylex.props(styles.icon).className'),
+ ]),
+ { layoutComponents: [] },
+ ).cases;
+ expect(plan.flags).toEqual([]);
+ expect(plan.evidence).toEqual(['PLACEMENT_PRESERVED']);
+ });
+
+ it('proves a hand-joined class on a replaced component from the extracted declarations', () => {
+ const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+ const base = (online: string) =>
+ extractFile(
+ `import { createStaticStyles } from '@lobehub/ui';
+const styles = createStaticStyles(({ css }) => ({
+ badge: css\`display: inline-flex; padding-inline: 8px;\`,
+ activated: css\`${online}\`,
+}));
+export const A = () => <Badge className={[styles.badge, styles.activated].join(' ')} />;
+`,
+ 'a.tsx',
+ options,
+ );
+ const head = (online: string) =>
+ extractFile(
+ `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({
+ badge: { display: 'inline-flex', paddingInline: '8px' },
+ activated: { ${online} },
+});
+export const A = () => <Badge className={[stylex.props(styles.badge).className, stylex.props(styles.activated).className].join(' ')} />;
+`,
+ 'a.tsx',
+ options,
+ );
+ const plan = (left: string, right: string) =>
+ planFile('a.tsx', base(left), head(right), { layoutComponents: [] }).cases[0];
+ expect(plan('color: green;', "color: 'green'").flags).toEqual([]);
+ expect(plan('padding-left: 4px;', "paddingLeft: '4px'").flags).toEqual([
+ 'PLACEMENT_SUBSTITUTED',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/placement.ts b/packages/style-equivalence/src/plan/placement.ts
new file mode 100644
index 00000000000..1666ee0c5d9
--- /dev/null
+++ b/packages/style-equivalence/src/plan/placement.ts
@@ -0,0 +1,357 @@
+import ts from 'typescript';
+
+import type { StyleBinding, StyleElement } from '../extract';
+import { knobText } from './knobs';
+import { propertiesOverlap } from './properties';
+
+type Canonical = { entries: Record<string, Canonical> } | { terms: string[] };
+
+export type SlotProperties = Record<string, string[]>;
+
+interface Unit {
+ outside: number;
+ propsCalls: number;
+ slots: Set<string>;
+}
+
+interface Context {
+ atoms: string[];
+ depth: number;
+ joins: Array<Array<Set<string>>>;
+ unit: Unit;
+ units: Unit[];
+}
+
+const newUnit = (): Unit => ({ outside: 0, propsCalls: 0, slots: new Set() });
+
+const EMPTY = new Set(['false', 'null', 'undefined']);
+const MERGERS = new Set(['clsx', 'cx']);
+
+const parse = (expr: string) => {
+ const source = ts.createSourceFile('placement.ts', `(${expr});`, ts.ScriptTarget.Latest, true);
+ const [statement] = source.statements;
+ return statement && ts.isExpressionStatement(statement)
+ ? unwrap(statement.expression)
+ : undefined;
+};
+
+const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;
+
+const compact = (node: ts.Node) => node.getText().replaceAll(/\s+/g, '');
+
+const isStylexProps = (node: ts.Expression) =>
+ ts.isCallExpression(node) && compact(node.expression) === 'stylex.props';
+
+const termsOfAll = (nodes: readonly ts.Expression[], ctx: Context) => {
+ const terms: string[] = [];
+ for (const node of nodes) {
+ const part = termsOf(node, ctx);
+ if (!part) return undefined;
+ terms.push(...part);
+ }
+ return terms;
+};
+
+const prefixed = (node: ts.Expression, prefix: string, ctx: Context) =>
+ termsOf(node, ctx)?.map((term) => `${prefix}${term}`);
+
+const propsTerms = (call: ts.CallExpression, ctx: Context) => {
+ ctx.unit.propsCalls += 1;
+ ctx.depth += 1;
+ const terms = termsOfAll(call.arguments, ctx);
+ ctx.depth -= 1;
+ return terms;
+};
+
+const containsProps = (root: ts.Node): boolean =>
+ (ts.isCallExpression(root) && isStylexProps(root)) || !!ts.forEachChild(root, containsProps);
+
+const isSpaceLiteral = (node: ts.Expression | undefined) =>
+ !!node && ts.isStringLiteralLike(node) && node.text === ' ';
+
+const joinedSources = (node: ts.Expression): readonly ts.Expression[] | undefined => {
+ if (ts.isTemplateExpression(node)) {
+ const literals = node.templateSpans.map((span) => span.literal.text);
+ const separated = literals.slice(0, -1).every((text) => /^\s+$/.test(text));
+ return separated && /^\s*$/.test(node.head.text) && /^\s*$/.test(literals.at(-1) ?? '')
+ ? node.templateSpans.map((span) => span.expression)
+ : undefined;
+ }
+ if (!ts.isCallExpression(node)) return undefined;
+ if (ts.isIdentifier(node.expression) && MERGERS.has(node.expression.text))
+ return node.arguments.filter(containsProps).length > 1 ? node.arguments : undefined;
+ if (!ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== 'join')
+ return undefined;
+ if (node.arguments.length !== 1 || !isSpaceLiteral(node.arguments[0])) return undefined;
+ let target = unwrap(node.expression.expression);
+ if (
+ ts.isCallExpression(target) &&
+ ts.isPropertyAccessExpression(target.expression) &&
+ target.expression.name.text === 'filter' &&
+ target.arguments.length === 1 &&
+ compact(target.arguments[0]) === 'Boolean'
+ )
+ target = unwrap(target.expression.expression);
+ if (!ts.isArrayLiteralExpression(target)) return undefined;
+ return target.elements.some(ts.isSpreadElement) ? undefined : target.elements;
+};
+
+const joinTerms = (sources: readonly ts.Expression[], ctx: Context) => {
+ if (ctx.depth > 0) return undefined;
+ const outer = ctx.unit;
+ const groups: Array<Set<string>> = [];
+ const terms: string[] = [];
+ for (const source of sources) {
+ ctx.unit = newUnit();
+ ctx.units.push(ctx.unit);
+ groups.push(ctx.unit.slots);
+ const part = termsOf(source, ctx);
+ ctx.unit = outer;
+ if (!part) return undefined;
+ terms.push(...part);
+ }
+ ctx.joins.push(groups);
+ return terms;
+};
+
+function termsOf(raw: ts.Expression, ctx: Context): string[] | undefined {
+ const node = unwrap(raw);
+ if (EMPTY.has(compact(node))) return [];
+ if (ts.isStringLiteralLike(node))
+ return node.text
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((token) => JSON.stringify(token));
+ if (ts.isIdentifier(node)) {
+ ctx.unit.slots.add(node.text);
+ return [node.text];
+ }
+ const sources = joinedSources(node);
+ if (sources) return joinTerms(sources, ctx);
+ if (ts.isPropertyAccessExpression(node)) {
+ const target = unwrap(node.expression);
+ if (node.name.text === 'className' && ts.isCallExpression(target) && isStylexProps(target))
+ return propsTerms(target, ctx);
+ if (!ts.isIdentifier(target)) return undefined;
+ if (ctx.depth === 0) ctx.unit.outside += 1;
+ ctx.unit.slots.add(compact(node));
+ return [compact(node)];
+ }
+ if (ts.isCallExpression(node)) {
+ if (isStylexProps(node)) return undefined;
+ return ts.isIdentifier(node.expression) && MERGERS.has(node.expression.text)
+ ? termsOfAll(node.arguments, ctx)
+ : undefined;
+ }
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken
+ ) {
+ ctx.atoms.push(knobText(unwrap(node.left)));
+ return prefixed(node.right, `${compact(node.left)}&&`, ctx);
+ }
+ if (ts.isConditionalExpression(node)) {
+ ctx.atoms.push(knobText(unwrap(node.condition)));
+ const condition = compact(node.condition);
+ const whenTrue = prefixed(node.whenTrue, `${condition}?`, ctx);
+ const whenFalse = prefixed(node.whenFalse, `${condition}:`, ctx);
+ return whenTrue && whenFalse ? [...whenTrue, ...whenFalse] : undefined;
+ }
+ return undefined;
+}
+
+const joinsDisjoint = (joins: Context['joins'], properties: SlotProperties | undefined) =>
+ joins.every((groups) => {
+ const sets = groups.map((slots) => [...slots].map((slot) => properties?.[slot]));
+ if (sets.some((set) => set.some((entry) => !entry))) return false;
+ const flat = sets.map((set) => (set as string[][]).flat());
+ return flat.every((left, index) =>
+ flat.slice(index + 1).every((right) => !propertiesOverlap(left, right)),
+ );
+ });
+
+const canonicalOf = (
+ raw: ts.Expression,
+ properties: SlotProperties | undefined,
+ atoms: string[],
+ spread = false,
+): Canonical | undefined => {
+ const node = unwrap(raw);
+ if (ts.isObjectLiteralExpression(node)) {
+ const entries: Record<string, Canonical> = {};
+ for (const property of node.properties) {
+ if (ts.isShorthandPropertyAssignment(property)) {
+ entries[property.name.text] = { terms: [property.name.text] };
+ continue;
+ }
+ if (!ts.isPropertyAssignment(property)) return undefined;
+ const { name } = property;
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) return undefined;
+ const value = canonicalOf(property.initializer, properties, atoms);
+ if (!value) return undefined;
+ entries[name.text] = value;
+ }
+ return { entries };
+ }
+ const unit = newUnit();
+ const ctx: Context = { atoms, depth: 0, joins: [], unit, units: [unit] };
+ const terms =
+ spread && ts.isCallExpression(node) && isStylexProps(node)
+ ? propsTerms(node, ctx)
+ : termsOf(node, ctx);
+ if (!terms) return undefined;
+ const merged = ctx.units.every(
+ (item) => item.propsCalls <= 1 && !(item.propsCalls === 1 && item.outside > 0),
+ );
+ return merged && joinsDisjoint(ctx.joins, properties) ? { terms } : undefined;
+};
+
+const isSx = (node: ts.Expression): node is ts.CallExpression =>
+ ts.isCallExpression(node) && compact(node.expression) === 'sx';
+
+const slotReferences = (root: ts.Node, found: string[] = []): string[] => {
+ if (ts.isPropertyAccessExpression(root) && ts.isIdentifier(unwrap(root.expression)))
+ found.push(compact(root));
+ else ts.forEachChild(root, (child) => void slotReferences(child, found));
+ return found;
+};
+
+const isStylexArgument = (node: ts.Expression, properties: SlotProperties | undefined) => {
+ const references = slotReferences(node);
+ return references.length > 0 && references.every((reference) => !!properties?.[reference]);
+};
+
+const sxArguments = (call: ts.CallExpression) => {
+ const found: Array<{ node: ts.Expression; stylex?: true }> = [];
+ for (const argument of call.arguments) {
+ const node = unwrap(argument);
+ if (!ts.isArrayLiteralExpression(node)) {
+ found.push({ node });
+ continue;
+ }
+ if (node.elements.some(ts.isSpreadElement)) return undefined;
+ for (const element of node.elements) found.push({ node: unwrap(element), stylex: true });
+ }
+ return found;
+};
+
+const sxValue = (
+ call: ts.CallExpression,
+ properties: SlotProperties | undefined,
+ atoms: string[],
+) => {
+ const argumentsOf = sxArguments(call);
+ if (!argumentsOf?.length) return undefined;
+ const unit = newUnit();
+ const ctx: Context = { atoms, depth: 0, joins: [], unit, units: [unit] };
+ ctx.unit.propsCalls += 1;
+ const terms: string[] = [];
+ for (const { node, stylex: inArray } of argumentsOf) {
+ if (ts.isObjectLiteralExpression(node)) {
+ if (node.properties.length === 0) continue;
+ return undefined;
+ }
+ const stylex = inArray || isStylexArgument(node, properties);
+ if (stylex) ctx.depth += 1;
+ const part = termsOf(node, ctx);
+ if (stylex) ctx.depth -= 1;
+ if (!part) return undefined;
+ terms.push(...part);
+ }
+ const merged = ctx.units.every(
+ (item) => item.propsCalls <= 1 && !(item.propsCalls === 1 && item.outside > 0),
+ );
+ return merged && joinsDisjoint(ctx.joins, properties)
+ ? { prop: 'className', value: { terms } }
+ : undefined;
+};
+
+const normalize = (binding: StyleBinding, properties?: SlotProperties, atoms: string[] = []) => {
+ const expression = parse(binding.expr);
+ if (!expression) return undefined;
+ if (binding.spread) {
+ if (isSx(expression)) return sxValue(expression, properties, atoms);
+ if (!isStylexProps(expression)) return undefined;
+ const value = canonicalOf(expression, properties, atoms, true);
+ return value && { prop: 'className', value };
+ }
+ const value = canonicalOf(expression, properties, atoms);
+ return value && { prop: binding.prop, value };
+};
+
+const sortedJson = (value: unknown) =>
+ JSON.stringify(value, (_key, inner) =>
+ inner && typeof inner === 'object' && !Array.isArray(inner)
+ ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => a.localeCompare(b)))
+ : inner,
+ );
+
+const sameElement = (base: StyleElement, head: StyleElement, properties: SideProperties) => {
+ if (base.tag !== head.tag) return false;
+ if (sortedJson(base.literalProps) !== sortedJson(head.literalProps)) return false;
+ if (sortedJson(base.attributes ?? {}) !== sortedJson(head.attributes ?? {})) return false;
+ if (base.bindings.length !== head.bindings.length) return false;
+ return base.bindings.every((binding, index) => {
+ const left = normalize(binding, properties.base);
+ const right = normalize(head.bindings[index], properties.head);
+ return !!left && !!right && sortedJson(left) === sortedJson(right);
+ });
+};
+
+export type SideProperties = Partial<Record<'base' | 'head', SlotProperties>>;
+
+export interface PlacementOptions {
+ layoutComponents?: string[];
+ properties?: SideProperties;
+}
+
+export const isIntrinsicTag = (tag: string) => /^[a-z][\w-]*$/.test(tag);
+
+const placementSensitive = (element: StyleElement, layout: Set<string>) =>
+ (!isIntrinsicTag(element.tag) && !layout.has(element.tag)) ||
+ element.bindings.some((binding) => !binding.spread && binding.prop !== 'className');
+
+export const placementPreserved = (
+ base: StyleElement[],
+ head: StyleElement[],
+ options: PlacementOptions = {},
+) => {
+ const layout = new Set(options.layoutComponents);
+ return (
+ base.length === head.length &&
+ base.every((element, index) => {
+ const other = head[index];
+ if (element.tag !== other.tag) return false;
+ return placementSensitive(element, layout) || placementSensitive(other, layout)
+ ? sameElement(element, other, options.properties ?? {})
+ : true;
+ })
+ );
+};
+
+const canonicalChain = (chain: StyleElement[], properties: SlotProperties | undefined) => {
+ const atoms: string[] = [];
+ const elements = [];
+ for (const element of chain) {
+ const bindings = [];
+ for (const binding of element.bindings) {
+ const value = normalize(binding, properties, atoms);
+ if (!value) return undefined;
+ bindings.push(value);
+ }
+ elements.push({ bindings, tag: element.tag });
+ }
+ return { atoms: [...new Set(atoms)], shape: sortedJson(elements) };
+};
+
+export const sharedConditions = (
+ base: StyleElement[],
+ head: StyleElement[],
+ properties: SideProperties = {},
+) => {
+ const left = canonicalChain(base, properties.base);
+ const right = canonicalChain(head, properties.head);
+ if (!left || !right || left.shape !== right.shape) return undefined;
+ return sortedJson(left.atoms) === sortedJson(right.atoms) ? left.atoms : undefined;
+};
diff --git a/packages/style-equivalence/src/plan/plan.test.ts b/packages/style-equivalence/src/plan/plan.test.ts
new file mode 100644
index 00000000000..c7aefe0ebfe
--- /dev/null
+++ b/packages/style-equivalence/src/plan/plan.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FileExtraction, StyleElement, VariableUse } from '../extract';
+import { pairwiseCombos } from './combos';
+import { planFile } from './planFile';
+
+const element = (
+ id: string,
+ tag: string,
+ slots: string[],
+ variables: VariableUse[] = [],
+ extra: Partial<StyleElement> = {},
+): StyleElement => ({
+ bindings: [{ expr: 'x', prop: 'className', spread: false }],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: id.split('#')[0],
+ slots,
+ tag,
+ variables,
+ ...extra,
+});
+
+const extraction = (elements: StyleElement[]): FileExtraction => ({
+ elements,
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ prelude: '',
+ rules: [],
+ styleSymbols: ['styles'],
+});
+
+const config = { layoutComponents: ['Flexbox'] };
+
+describe('planFile pairing', () => {
+ it('keeps later elements paired when one side gains an element in the middle', () => {
+ const plan = planFile(
+ 'a.tsx',
+ extraction([
+ element('A#0', 'div', ['styles.root']),
+ element('A#1', 'span', ['styles.label']),
+ element('A#2', 'span', ['styles.hint']),
+ ]),
+ extraction([
+ element('A#0', 'div', ['styles.root']),
+ element('A#1', 'button', ['styles.action']),
+ element('A#2', 'span', ['styles.label']),
+ element('A#3', 'span', ['styles.hint']),
+ ]),
+ config,
+ );
+ expect(plan.cases.map((entry) => [entry.elementIds.base, entry.elementIds.head])).toEqual([
+ ['A#0', 'A#0'],
+ ['A#1', 'A#2'],
+ ['A#2', 'A#3'],
+ ]);
+ expect(plan.unpaired).toEqual([{ elementId: 'A#1', side: 'head' }]);
+ });
+
+ it('marks every element of an owner missing on the other side as unpaired', () => {
+ const plan = planFile(
+ 'a.tsx',
+ extraction([element('Old#0', 'div', ['styles.a'])]),
+ extraction([element('New#0', 'div', ['styles.a'])]),
+ config,
+ );
+ expect(plan.cases).toEqual([]);
+ expect(plan.unpaired).toEqual([
+ { elementId: 'Old#0', side: 'base' },
+ { elementId: 'New#0', side: 'head' },
+ ]);
+ });
+});
+
+describe('planFile conditions and flags', () => {
+ it('flags a condition that only one side uses and still enumerates it', () => {
+ const [entry] = planFile(
+ 'a.tsx',
+ extraction([element('L#0', 'Flexbox', ['styles.label'])]),
+ extraction([
+ element(
+ 'L#0',
+ 'Flexbox',
+ ['styles.label', 'styles.labelMuted'],
+ [{ kind: 'boolean', name: 'muted' }],
+ ),
+ ]),
+ config,
+ ).cases;
+ expect(entry.flags).toEqual(['ASYMMETRIC_CONDITION']);
+ expect(entry.combos).toEqual([{ muted: false }, { muted: true }]);
+ });
+
+ it('enumerates modeled kinds, drops pass-through props and flags unmodeled ones', () => {
+ const variables: VariableUse[] = [
+ { kind: 'call', name: 'isActive' },
+ { kind: 'member', name: 'item' },
+ { kind: 'unknown', name: 'size' },
+ { kind: 'unknown', name: 'className' },
+ ];
+ const [entry] = planFile(
+ 'a.tsx',
+ extraction([element('A#0', 'div', ['styles.a'], variables)]),
+ extraction([element('A#0', 'div', ['styles.a'], variables)]),
+ config,
+ ).cases;
+ expect(entry.variables.map((variable) => variable.name)).toEqual(['isActive', 'item']);
+ expect(entry.combos).toHaveLength(4);
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('merges the kinds a variable has along the chain', () => {
+ const chain = () =>
+ extraction([
+ element('A#0', 'div', ['styles.row'], [{ kind: 'boolean', name: 'item' }]),
+ element('A#1', 'span', ['styles.label'], [{ kind: 'member', name: 'item' }], {
+ parent: 'A#0',
+ }),
+ ]);
+ const inner = planFile('a.tsx', chain(), chain(), config).cases[1];
+ expect(inner.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('flags substituted tags, neutral props and changed tags along the chain', () => {
+ const [outer, inner] = planFile(
+ 'a.tsx',
+ extraction([
+ element('A#0', 'SortableList.Item', ['styles.item']),
+ element('A#1', 'div', ['styles.dot'], [], { parent: 'A#0' }),
+ ]),
+ extraction([
+ element('A#0', 'SortableList.Item', ['styles.item'], [], {
+ bindings: [{ expr: 'x', prop: 'itemClassName', spread: false }],
+ }),
+ element('A#1', 'span', ['styles.dot'], [], { parent: 'A#0' }),
+ ]),
+ config,
+ ).cases;
+ expect(outer.flags).toEqual(['PLACEMENT_NEUTRAL_PROP', 'PLACEMENT_SUBSTITUTED']);
+ expect(inner.flags).toEqual(['PLACEMENT_NEUTRAL_PROP', 'PLACEMENT_SUBSTITUTED', 'TAG_CHANGED']);
+ });
+});
+
+describe('pairwiseCombos', () => {
+ it('covers every value pair of six booleans in far fewer than 64 combos', () => {
+ const names = ['a', 'b', 'c', 'd', 'e', 'f'];
+ const combos = pairwiseCombos(names);
+ expect(combos.length).toBeLessThanOrEqual(12);
+ for (const [i, x] of names.entries())
+ for (const y of names.slice(i + 1))
+ for (const vx of [false, true])
+ for (const vy of [false, true])
+ expect(combos.some((combo) => combo[x] === vx && combo[y] === vy)).toBe(true);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/planFile.ts b/packages/style-equivalence/src/plan/planFile.ts
new file mode 100644
index 00000000000..9da21ec0dd5
--- /dev/null
+++ b/packages/style-equivalence/src/plan/planFile.ts
@@ -0,0 +1,425 @@
+import type { FileExtraction, RealComponent, StyleElement, VariableKind } 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 {
+ forwardedDescendants,
+ forwardedInside,
+ type ForwardPlan,
+ partlyForwarded,
+} from './forwarded';
+import { sharedInlineStyles } from './inlineStyle';
+import type { InnerNode } from './inner';
+import { keptEmotionRules } from './kept';
+import { bindKnobs, parseExpression } from './knobs';
+import { movedStylesheets } from './moved';
+import { neutralOmitted } from './neutral';
+import { alignElements } from './pair';
+import {
+ isIntrinsicTag,
+ placementPreserved,
+ sharedConditions,
+ type SideProperties,
+} from './placement';
+import { runtimeStyleProbe, styleDropped } from './probes';
+import { reachableCombos } from './reachable';
+import { realItemsOf, rendersReal, sampleTargets, standInsOf } from './real';
+import { tableDomain } from './tables';
+
+export { isIntrinsicTag } from './placement';
+
+export type Side = 'base' | 'head';
+
+export const PASS_THROUGH_VARIABLES = new Set([
+ 'className',
+ 'classNames',
+ 'cx',
+ 'props',
+ 'style',
+ 'styles',
+]);
+
+export interface PlanVariable {
+ kinds: Partial<Record<Side, VariableKind>>;
+ name: string;
+ probe?: boolean;
+ values?: string[];
+}
+
+export interface PlanCase {
+ chainOmit?: Partial<Record<Side, string[]>>;
+ combos: Combo[];
+ elementIds: Record<Side, string>;
+ evidence?: string[];
+ file: string;
+ flags: string[];
+ forward?: ForwardPlan;
+ forwardedParam?: string;
+ inlineStyles?: Partial<Record<Side, Array<{ binding: number; index: number; without: string }>>>;
+ inner?: Record<string, InnerNode[]>;
+ key: string;
+ knobs?: string[];
+ neutralOmitted?: number[];
+ samples?: InnerNode[];
+ standIns?: Partial<Record<Side, string[]>>;
+ variables: PlanVariable[];
+}
+
+export interface FilePlan {
+ cases: PlanCase[];
+ file: string;
+ gaps: string[];
+ standIns?: Record<string, string[]>;
+ unpaired: Array<{ elementId: string; side: Side }>;
+}
+
+export interface PlanConfig {
+ layoutComponents: string[];
+ realComponents?: Record<string, RealComponent>;
+}
+
+const declarationFree = (element: StyleElement) =>
+ !element.slots.length && !element.forwardedParam && !element.forwards?.length;
+
+export const chainOf = (
+ element: StyleElement,
+ byId: Map<string, StyleElement>,
+ omit?: readonly string[],
+) => {
+ const chain: StyleElement[] = [];
+ let current: StyleElement | undefined = element;
+ while (current) {
+ if (current === element || !omit?.includes(current.id)) chain.unshift(current);
+ current = current.parent ? byId.get(current.parent) : undefined;
+ }
+ return chain;
+};
+
+const boundWithoutVariables = (chain: StyleElement[], knobs: string[]) =>
+ chain.every((element) => {
+ const names = new Set(
+ element.variables
+ .map((variable) => variable.name)
+ .filter((name) => !PASS_THROUGH_VARIABLES.has(name)),
+ );
+ const before = new Set<string>();
+ const unbound = element.bindings.every((binding) => {
+ const original = parseExpression(binding.expr);
+ const bound = bindKnobs(binding.expr, knobs);
+ const parsed = bound === undefined ? undefined : parseExpression(bound);
+ if (!original || !parsed) return false;
+ valueIdentifiers(original.expression).forEach((name) => before.add(name));
+ return [...valueIdentifiers(parsed.expression)].every((name) => !names.has(name));
+ });
+ return unbound && [...names].every((name) => before.has(name));
+ });
+
+const conditionKnobs = (chains: Record<Side, StyleElement[]>, properties: SideProperties) => {
+ const knobs = sharedConditions(chains.base, chains.head, properties);
+ return knobs &&
+ boundWithoutVariables(chains.base, knobs) &&
+ boundWithoutVariables(chains.head, knobs)
+ ? knobs
+ : undefined;
+};
+
+const alignedProofs = <T extends { head: string }>(
+ proofs: Map<string, T>,
+ chains: Record<Side, StyleElement[]>,
+) =>
+ chains.base.length === chains.head.length
+ ? chains.base.flatMap((item, index) => {
+ const proof = proofs.get(item.id);
+ return proof && proof.head === chains.head[index].id ? [{ index, proof }] : [];
+ })
+ : [];
+
+const PACKAGE_STYLESHEET = /^STYLESHEET_UNREADABLE:(@\w[\w.-]*\/)?\w[\w.-]*\//;
+
+const fileGaps = (base: string[], head: string[]) =>
+ [...new Set([...base, ...head])].filter(
+ (gap) => !(PACKAGE_STYLESHEET.test(gap) && base.includes(gap) && head.includes(gap)),
+ );
+
+const groupByOwner = (elements: StyleElement[]) => {
+ const owners = new Map<string, StyleElement[]>();
+ for (const element of elements)
+ owners.set(element.owner, [...(owners.get(element.owner) ?? []), element]);
+ return owners;
+};
+
+export const planFile = (
+ file: string,
+ base: FileExtraction,
+ head: FileExtraction,
+ config: PlanConfig,
+): FilePlan => {
+ const layout = new Set(config.layoutComponents);
+ const byId = {
+ base: new Map(elementsOf(base).map((e) => [e.id, e])),
+ head: new Map(head.elements.map((e) => [e.id, e])),
+ };
+ const baseOwners = groupByOwner(base.elements);
+ const headOwners = groupByOwner(head.elements);
+ const pairs: Array<[StyleElement, StyleElement]> = [];
+ const unpairedBase: StyleElement[] = [];
+ const unpairedHead: StyleElement[] = [];
+ for (const [owner, elements] of baseOwners) {
+ const other = headOwners.get(owner);
+ if (!other) {
+ unpairedBase.push(...elements);
+ continue;
+ }
+ const aligned = alignElements(elements, other);
+ pairs.push(...aligned.pairs);
+ unpairedBase.push(...aligned.unpairedBase);
+ unpairedHead.push(...aligned.unpairedHead);
+ }
+ for (const [owner, elements] of headOwners)
+ if (!baseOwners.has(owner)) unpairedHead.push(...elements);
+ const replaced = replacedDescendants(base, head, pairs, unpairedHead);
+ const replacedHead = new Set(replaced.map(([, right]) => right));
+ unpairedHead.splice(0, unpairedHead.length, ...unpairedHead.filter((e) => !replacedHead.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]));
+ const partial = new Map(
+ forwarded.map((entry) => [entry.parent.id, partlyForwarded(entry.parent, entry.tag, layout)]),
+ );
+ const inside = forwardedInside(base, head, pairs, unpairedHead);
+ const paramOf = new Map(inside.map((entry) => [entry.pair[1], entry.param]));
+ unpairedHead.splice(
+ 0,
+ unpairedHead.length,
+ ...unpairedHead.filter((e) => !forwardOf.has(e) && !paramOf.has(e)),
+ );
+ pairs.push(...forwarded.map((entry) => entry.pair), ...inside.map((entry) => entry.pair));
+ const rendered = new Set(pairs.map(([left]) => left.id));
+ const covered = new Set(
+ [...new Set(replaced.map(([left]) => left.parent!))].filter((id) =>
+ parentCovered(byId.base.get(id)!, base, rendered),
+ ),
+ );
+ const moved = movedStylesheets(base, head, pairs);
+ const kept = keptEmotionRules(base, head, pairs);
+
+ const omittable = {
+ base: unpairedBase.filter(declarationFree).map((element) => element.id),
+ head: unpairedHead.filter(declarationFree).map((element) => element.id),
+ };
+ const cases = pairs.map(([left, right]): PlanCase => {
+ const chains = {
+ base: chainOf(left, byId.base, omittable.base),
+ head: chainOf(right, byId.head, omittable.head),
+ };
+ const chainOmit = Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) => {
+ const full = chainOf(side === 'base' ? left : right, byId[side]);
+ const ids = full.filter((item) => !chains[side].includes(item)).map((item) => item.id);
+ return ids.length ? [[side, ids]] : [];
+ }),
+ );
+ const flags = new Set<string>();
+ const evidence: string[] = [];
+ const isReplaced = replacedHead.has(right);
+ const forward = forwardOf.get(right);
+ const param = paramOf.get(right);
+ const resolved = new Set(forward ? [left, right] : []);
+ const movedAt = alignedProofs(moved, chains);
+ const keptAt = alignedProofs(kept, chains);
+ const provenItems = new Set(
+ [...movedAt, ...keptAt].flatMap(({ index }) => [chains.base[index], chains.head[index]]),
+ );
+ const keptWhole = new Set(
+ keptAt
+ .filter(({ proof }) => proof.exhaustive)
+ .flatMap(({ index }) => [chains.base[index], chains.head[index]]),
+ );
+ if (left.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);
+ 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)
+ flags.add('PLACEMENT_SUBSTITUTED');
+ if (!real && item.bindings.some((binding) => !binding.spread && binding.prop !== 'className'))
+ flags.add('PLACEMENT_NEUTRAL_PROP');
+ const reached =
+ chains.base.includes(item) &&
+ (covered.has(item.id) ||
+ (!!forward && item.id === left.parent) ||
+ (isReplaced && item.id === left.parent && childCovered(item, left, base.rules)));
+ const inner = item.flags.includes('INNER_TARGET') && (reached || provenItems.has(item));
+ if (inner && reached && !isReplaced && !forward && !evidence.includes('DESCENDANT_RENDERED'))
+ evidence.push('DESCENDANT_RENDERED');
+ const cleared = (flag: string) =>
+ (inner && flag === 'INNER_TARGET') || (keptWhole.has(item) && flag === 'CROSS_COMPONENT');
+ item.flags.forEach((flag) => !cleared(flag) && flags.add(flag));
+ }
+ if (isReplaced) evidence.push('DESCENDANT_REPLACED');
+ if (forward) evidence.push('FORWARDED_RENDERED');
+ if (param) evidence.push('FORWARDED_PROP_ABSENT');
+ const partialFlag = partial.get(left.id);
+ if (partialFlag && flags.has('INNER_TARGET')) flags.add(partialFlag);
+ const properties = { base: base.slotProperties, head: head.slotProperties };
+ if (
+ (flags.has('PLACEMENT_SUBSTITUTED') || flags.has('PLACEMENT_NEUTRAL_PROP')) &&
+ placementPreserved(
+ chains.base,
+ chains.head.map((item, index) => {
+ const placement = [...movedAt, ...keptAt].find((entry) => entry.index === index)?.proof
+ .placement;
+ return placement
+ ? { ...item, bindings: [{ ...item.bindings[0], expr: placement }] }
+ : item;
+ }),
+ { layoutComponents: config.layoutComponents, properties },
+ )
+ ) {
+ flags.delete('PLACEMENT_SUBSTITUTED');
+ flags.delete('PLACEMENT_NEUTRAL_PROP');
+ evidence.push('PLACEMENT_PRESERVED');
+ }
+ if (movedAt.length) evidence.push('STYLESHEET_MOVED');
+ if (keptAt.length) evidence.push('EMOTION_RULE_KEPT');
+ if (realItems.size) evidence.push('REAL_COMPONENT_RENDERED');
+ const samples = realItems.size ? sampleTargets(chains, { base, head }) : [];
+ const omitted = neutralOmitted(chains);
+ const standIns = Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) => {
+ const tags = standInsOf(
+ chains[side],
+ (item) => realItems.has(item) || resolved.has(item),
+ layout,
+ );
+ return tags.length ? [[side, tags]] : [];
+ }),
+ );
+ const inner: Record<string, InnerNode[]> = {};
+ 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 variables = new Map<string, PlanVariable>();
+ for (const side of ['base', 'head'] as const)
+ for (const [itemIndex, item] of chains[side].entries())
+ for (const variable of item.variables) {
+ if (PASS_THROUGH_VARIABLES.has(variable.name) || variable.name === param) continue;
+ if (
+ shared[side]?.some(
+ (style) => style.index === itemIndex && style.names.includes(variable.name),
+ )
+ )
+ continue;
+ const entry = variables.get(variable.name) ?? { kinds: {}, name: variable.name };
+ entry.kinds[side] = mergeKinds([entry.kinds[side] ?? variable.kind, variable.kind]);
+ variables.set(variable.name, entry);
+ }
+ const sorted = [...variables.values()].sort((a, b) => a.name.localeCompare(b.name));
+ const tables = { base: base.tables, head: head.tables };
+ const found: Record<string, string[]> = {};
+ const probes = new Set<string>();
+ for (const variable of sorted) {
+ if (!Object.values(variable.kinds).includes('unknown')) continue;
+ const domain = tableDomain(variable.name, chains, tables);
+ if (domain) found[variable.name] = domain;
+ else if (runtimeStyleProbe(variable.name, chains)) probes.add(variable.name);
+ }
+ const model = (domains: Record<string, string[]>) => {
+ const unknown = (variable: PlanVariable) =>
+ !domains[variable.name] &&
+ !probes.has(variable.name) &&
+ Object.values(variable.kinds).includes('unknown');
+ const knobs =
+ sorted.some(unknown) && !structural ? conditionKnobs(chains, properties) : undefined;
+ const modeled: PlanVariable[] = [];
+ const added = new Set<string>();
+ if (!knobs)
+ for (const variable of sorted) {
+ if (unknown(variable)) {
+ added.add('VARIABLE_UNMODELED');
+ continue;
+ }
+ if (probes.has(variable.name)) {
+ modeled.push({ ...variable, probe: true });
+ continue;
+ }
+ if (!variable.kinds.base || !variable.kinds.head) added.add('ASYMMETRIC_CONDITION');
+ const values = domains[variable.name];
+ modeled.push(values ? { ...variable, values } : variable);
+ }
+ const used = Object.fromEntries(
+ modeled.flatMap((variable) => (variable.values ? [[variable.name, variable.values]] : [])),
+ );
+ const names = knobs ?? modeled.map((variable) => variable.name);
+ return { added, knobs, modeled, used, ...combosFor(names, used) };
+ };
+ let modeling = model(found);
+ 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');
+ modeling.added.forEach((flag) => flags.add(flag));
+ if (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');
+ if (pairwise) flags.add('COMBINATIONS_PAIRWISE');
+ if (Object.values(shared).some((list) => list.some((style) => style.reordered)))
+ flags.add('INLINE_STYLE_SPREAD_ORDER');
+ return {
+ combos,
+ elementIds: { base: left.id, head: right.id },
+ ...(evidence.length ? { evidence } : {}),
+ file,
+ flags: [...flags].sort(),
+ ...(forward ? { forward } : {}),
+ ...(param ? { forwardedParam: param } : {}),
+ ...(Object.keys(shared).length
+ ? {
+ inlineStyles: Object.fromEntries(
+ Object.entries(shared).map(([side, list]) => [
+ side,
+ list.map(({ binding, index, without }) => ({ binding, index, without })),
+ ]),
+ ),
+ }
+ : {}),
+ ...(Object.keys(chainOmit).length ? { chainOmit } : {}),
+ ...(Object.keys(inner).length ? { inner } : {}),
+ key: `${file}|${left.id}`,
+ ...(knobs ? { knobs } : {}),
+ ...(omitted.length ? { neutralOmitted: omitted } : {}),
+ ...(samples.length ? { samples } : {}),
+ ...(Object.keys(standIns).length ? { standIns } : {}),
+ variables: modeled,
+ };
+ });
+
+ const unpairedStandIns = Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) =>
+ (side === 'base' ? unpairedBase : unpairedHead).flatMap((element) => {
+ const chain = chainOf(element, byId[side]);
+ const tags = standInsOf(
+ chain,
+ (item, index) => rendersReal(item, index === chain.length - 1, config.realComponents),
+ layout,
+ );
+ return tags.length ? [[`${side}:${element.id}`, tags]] : [];
+ }),
+ ),
+ );
+ return {
+ cases,
+ file,
+ gaps: fileGaps(base.gaps, head.gaps),
+ ...(Object.keys(unpairedStandIns).length ? { standIns: unpairedStandIns } : {}),
+ unpaired: [
+ ...unpairedBase.map((element) => ({ elementId: element.id, side: 'base' as const })),
+ ...unpairedHead.map((element) => ({ elementId: element.id, side: 'head' as const })),
+ ],
+ };
+};
diff --git a/packages/style-equivalence/src/plan/probes.test.ts b/packages/style-equivalence/src/plan/probes.test.ts
new file mode 100644
index 00000000000..c1301855283
--- /dev/null
+++ b/packages/style-equivalence/src/plan/probes.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const base = (
+ lane = '<div className={styles.lane} style={laneStyle}>',
+) => `import { createStaticStyles } from '@lobehub/ui';
+import { sx } from '@/styles/sx';
+
+const styles = createStaticStyles(({ css }) => ({
+ header: css\`height: 44px;\`,
+ lane: css\`display: flex;\`,
+}));
+
+export const Layout = ({ laneStyle }) => (
+ ${lane}
+ <header className={styles.header} />
+ </div>
+);
+`;
+
+const head = (
+ lane = '<div {...sx(styles.lane, undefined, laneStyle)}>',
+ header = '<header {...stylex.props(styles.header)} />',
+) => `import * as stylex from '@stylexjs/stylex';
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({
+ header: { height: '44px' },
+ lane: { display: 'flex' },
+});
+
+export const Layout = ({ laneStyle }) => (
+ ${lane}
+ ${header}
+ </div>
+);
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: ['Flexbox'],
+ }).cases;
+
+describe('runtime style passed through on both sides', () => {
+ it('records an identifier passed straight to style on a styled element', () => {
+ const [lane] = extractFile(base(), 'a.tsx', options).elements;
+ expect(lane.runtimeStyle).toBe('laneStyle');
+ });
+
+ it('probes the value on the element and every descendant case', () => {
+ const cases = plan(base(), head());
+ expect(cases).toHaveLength(2);
+ for (const entry of cases) {
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['RUNTIME_STYLE_PROBED']);
+ expect(entry.variables).toEqual([
+ { kinds: { head: 'unknown' }, name: 'laneStyle', probe: true },
+ ]);
+ expect(entry.combos).toEqual([{ laneStyle: false }, { laneStyle: true }]);
+ }
+ });
+
+ it('keeps the flag when neither side passes the value straight to style', () => {
+ const cases = plan(base('<div {...sx(styles.lane, undefined, laneStyle)}>'), head());
+ expect(cases[0].flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('flags a style that only one side places next to a spread', () => {
+ const cases = plan(base('<div {...props} className={styles.lane} style={laneStyle}>'), head());
+ expect(cases[0].flags).toEqual(['INLINE_STYLE_SPREAD_ORDER']);
+ });
+
+ it('keeps the flag when the other side reads into the value', () => {
+ const cases = plan(base(), head('<div {...sx(styles.lane, undefined, laneStyle.inner)}>'));
+ expect(cases[0].flags).toEqual(['VARIABLE_UNMODELED']);
+ expect(cases[0].evidence).toBeUndefined();
+ });
+
+ it('keeps the flag when the other side hands the value to another element', () => {
+ const cases = plan(
+ base(),
+ head(
+ '<div {...stylex.props(styles.lane)}>',
+ '<header {...sx(styles.header, undefined, laneStyle)} />',
+ ),
+ );
+ expect(cases[1].flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when the other side passes the value twice', () => {
+ const cases = plan(base(), head('<div {...sx(styles.lane, laneStyle, laneStyle)}>'));
+ expect(cases[0].flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/probes.ts b/packages/style-equivalence/src/plan/probes.ts
new file mode 100644
index 00000000000..845e81dde7a
--- /dev/null
+++ b/packages/style-equivalence/src/plan/probes.ts
@@ -0,0 +1,59 @@
+import ts from 'typescript';
+
+import type { StyleElement } from '../extract';
+import { valueIdentifierNodes, valueIdentifiers } from '../extract/identifiers';
+import { parseExpression } from './knobs';
+import { isIntrinsicTag } from './placement';
+
+type Sides<T> = Record<'base' | 'head', T>;
+
+const argumentUses = (element: StyleElement, name: string) => {
+ let count = 0;
+ for (const binding of element.bindings) {
+ const parsed = parseExpression(binding.expr);
+ if (!parsed) return undefined;
+ for (const node of valueIdentifierNodes(parsed.expression)) {
+ if (node.text !== name) continue;
+ let outer: ts.Node = node;
+ while (ts.isParenthesizedExpression(outer.parent)) outer = outer.parent;
+ const { parent } = outer;
+ if (!ts.isCallExpression(parent) || parent.expression === outer) return undefined;
+ count += 1;
+ }
+ }
+ return count;
+};
+
+const mentions = (element: StyleElement, name: string) =>
+ element.variables.some((variable) => variable.name === name);
+
+const anchoredAt = (anchor: StyleElement[], other: StyleElement[], name: string) => {
+ const index = anchor.findIndex((element) => element.runtimeStyle === name);
+ if (index < 0) return false;
+ const target = anchor[index];
+ return (
+ isIntrinsicTag(target.tag) &&
+ target.tag === other[index].tag &&
+ other[index].runtimeStyle === undefined &&
+ anchor.every(
+ (element, at) => !mentions(element, name) && (at === index || element.runtimeStyle !== name),
+ ) &&
+ other.every(
+ (element, at) => element.runtimeStyle !== name && (at === index || !mentions(element, name)),
+ ) &&
+ argumentUses(other[index], name) === 1
+ );
+};
+
+export const runtimeStyleProbe = (name: string, chains: Sides<StyleElement[]>) =>
+ chains.base.length === chains.head.length &&
+ (anchoredAt(chains.base, chains.head, name) || anchoredAt(chains.head, chains.base, name));
+
+export const styleDropped = (base: StyleElement, head: StyleElement, probed: Set<string>) => {
+ if (Boolean(base.styleExpr) === Boolean(head.styleExpr)) return false;
+ const [present, absent] = base.styleExpr ? [base, head] : [head, base];
+ if (present.inlineStyle) return false;
+ const parsed = parseExpression(present.styleExpr!);
+ const names = parsed ? [...valueIdentifiers(parsed.expression)] : [];
+ return !names.some((name) => probed.has(name) || mentions(absent, name));
+};
diff --git a/packages/style-equivalence/src/plan/properties.test.ts b/packages/style-equivalence/src/plan/properties.test.ts
new file mode 100644
index 00000000000..56c027ec713
--- /dev/null
+++ b/packages/style-equivalence/src/plan/properties.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import { propertiesOverlap } from './properties';
+
+describe('propertiesOverlap', () => {
+ it('keeps unrelated properties apart', () => {
+ expect(
+ propertiesOverlap(
+ ['display', 'gap', 'padding-block', 'border-radius', 'font-size', 'line-height'],
+ ['color', 'background-color', 'background-image'],
+ ),
+ ).toBe(false);
+ });
+
+ it('finds the same property', () => {
+ expect(propertiesOverlap(['color'], ['color'])).toBe(true);
+ });
+
+ it('expands shorthands that share a prefix with their longhands', () => {
+ expect(propertiesOverlap(['background'], ['background-color'])).toBe(true);
+ expect(propertiesOverlap(['border'], ['border-top-style'])).toBe(true);
+ expect(propertiesOverlap(['margin'], ['margin-left'])).toBe(true);
+ });
+
+ it('expands shorthands whose longhands have other names', () => {
+ expect(propertiesOverlap(['border-radius'], ['border-top-left-radius'])).toBe(true);
+ expect(propertiesOverlap(['border-width'], ['border-left-width'])).toBe(true);
+ expect(propertiesOverlap(['font'], ['line-height'])).toBe(true);
+ expect(propertiesOverlap(['inset'], ['top'])).toBe(true);
+ expect(propertiesOverlap(['gap'], ['row-gap'])).toBe(true);
+ expect(propertiesOverlap(['place-items'], ['justify-items'])).toBe(true);
+ expect(propertiesOverlap(['flex-flow'], ['flex-wrap'])).toBe(true);
+ expect(propertiesOverlap(['white-space'], ['text-wrap-mode'])).toBe(true);
+ });
+
+ it('maps logical properties onto the physical ones they can set', () => {
+ expect(propertiesOverlap(['padding-inline'], ['padding-left'])).toBe(true);
+ expect(propertiesOverlap(['margin-inline-start'], ['margin-right'])).toBe(true);
+ expect(propertiesOverlap(['border-block-end'], ['border-bottom-color'])).toBe(true);
+ expect(propertiesOverlap(['inset-inline-start'], ['left'])).toBe(true);
+ expect(propertiesOverlap(['inline-size'], ['width'])).toBe(true);
+ expect(propertiesOverlap(['max-block-size'], ['max-height'])).toBe(true);
+ expect(propertiesOverlap(['border-start-start-radius'], ['border-radius'])).toBe(true);
+ expect(propertiesOverlap(['overflow-inline'], ['overflow-x'])).toBe(true);
+ });
+
+ it('treats vendor prefixes, aliases and all as the properties they set', () => {
+ expect(propertiesOverlap(['-webkit-line-clamp'], ['line-clamp'])).toBe(true);
+ expect(propertiesOverlap(['word-wrap'], ['overflow-wrap'])).toBe(true);
+ expect(propertiesOverlap(['grid-gap'], ['column-gap'])).toBe(true);
+ expect(propertiesOverlap(['all'], ['color'])).toBe(true);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/properties.ts b/packages/style-equivalence/src/plan/properties.ts
new file mode 100644
index 00000000000..b1c6796812c
--- /dev/null
+++ b/packages/style-equivalence/src/plan/properties.ts
@@ -0,0 +1,71 @@
+const SIDES = ['top', 'right', 'bottom', 'left'];
+const CORNERS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
+
+const ALIASES: Record<string, string> = {
+ 'grid-column-gap': 'column-gap',
+ 'grid-gap': 'gap',
+ 'grid-row-gap': 'row-gap',
+ 'word-wrap': 'overflow-wrap',
+};
+
+const SHORTHANDS: Record<string, string[]> = {
+ 'border-color': SIDES.map((side) => `border-${side}-color`),
+ 'border-radius': CORNERS.map((corner) => `border-${corner}-radius`),
+ 'border-style': SIDES.map((side) => `border-${side}-style`),
+ 'border-width': SIDES.map((side) => `border-${side}-width`),
+ 'columns': ['column-width', 'column-count'],
+ 'flex-flow': ['flex-direction', 'flex-wrap'],
+ 'font': ['font', 'line-height'],
+ 'gap': ['row-gap', 'column-gap'],
+ 'grid-area': ['grid-row', 'grid-column'],
+ 'inset': SIDES,
+ 'overflow-block': ['overflow-y'],
+ 'overflow-inline': ['overflow-x'],
+ 'place-content': ['align-content', 'justify-content'],
+ 'place-items': ['align-items', 'justify-items'],
+ 'place-self': ['align-self', 'justify-self'],
+ 'white-space': ['white-space', 'text-wrap-mode'],
+};
+
+const LOGICAL_CORNER = /^border-(start|end)-(start|end)-radius$/;
+const LOGICAL_AXIS = /-(inline|block)(?:-start|-end)?(?=-|$)/;
+
+const physical = (property: string): string[] => {
+ if (LOGICAL_CORNER.test(property)) return CORNERS.map((corner) => `border-${corner}-radius`);
+ const sized = property
+ .replace(/(^|-)inline-size$/, '$1width')
+ .replace(/(^|-)block-size$/, '$1height');
+ const match = LOGICAL_AXIS.exec(sized);
+ if (!match || SHORTHANDS[sized]) return [sized];
+ const sides = match[1] === 'inline' ? ['left', 'right'] : ['top', 'bottom'];
+ return sides.flatMap((side) =>
+ physical(`${sized.slice(0, match.index)}-${side}${sized.slice(match.index + match[0].length)}`),
+ );
+};
+
+const expand = (raw: string): string[] => {
+ const unprefixed = raw.toLowerCase().replace(/^-(?:webkit|moz|ms|o)-/, '');
+ const name = ALIASES[unprefixed] ?? unprefixed;
+ return physical(name).flatMap((property) => {
+ const side = /^inset-(top|right|bottom|left)$/.exec(property);
+ if (side) return [side[1]];
+ const longhands = SHORTHANDS[property];
+ return longhands
+ ? [property, ...longhands.flatMap((item) => (item === property ? [item] : expand(item)))]
+ : [property];
+ });
+};
+
+const related = (left: string, right: string) =>
+ left === 'all' ||
+ right === 'all' ||
+ left === right ||
+ left.startsWith(`${right}-`) ||
+ right.startsWith(`${left}-`);
+
+export const propertiesOverlap = (left: Iterable<string>, right: Iterable<string>) => {
+ const expanded = [...right].flatMap(expand);
+ return [...left]
+ .flatMap(expand)
+ .some((property) => expanded.some((other) => related(property, other)));
+};
diff --git a/packages/style-equivalence/src/plan/reachable.test.ts b/packages/style-equivalence/src/plan/reachable.test.ts
new file mode 100644
index 00000000000..81f94ac3ed5
--- /dev/null
+++ b/packages/style-equivalence/src/plan/reachable.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const base = (body: string) => `import { createStaticStyles, cx } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ quote: css\`color: red;\`,
+ clickable: css\`cursor: pointer;\`,
+ orphaned: css\`opacity: 0.5;\`,
+}));
+
+${body}
+`;
+
+const head = (body: string) => `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ quote: { color: 'red' },
+ clickable: { cursor: 'pointer' },
+ orphaned: { opacity: 0.5 },
+});
+
+${body}
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: [],
+ }).cases;
+
+describe('combinations the source cannot reach', () => {
+ it('drops the combination a derived condition rules out on both sides', () => {
+ const [entry] = plan(
+ base(`export const Quote = ({ onLocate, orphaned }) => {
+ const clickable = Boolean(onLocate) && !orphaned;
+ return <div className={cx(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />;
+};`),
+ head(`export const Quote = ({ onLocate, orphaned }) => {
+ const clickable = Boolean(onLocate) && !orphaned;
+ return <div {...stylex.props(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />;
+};`),
+ );
+ expect(entry.combos).toEqual([
+ { clickable: false, orphaned: false },
+ { clickable: true, orphaned: false },
+ { clickable: false, orphaned: true },
+ ]);
+ expect(entry.evidence).toContain('COMBOS_UNREACHABLE_DROPPED');
+ });
+
+ it('drops the combinations an element is never rendered in', () => {
+ const [entry] = plan(
+ base(`export const Quote = ({ collapsed, orphaned }) =>
+ !collapsed && <div className={cx(styles.quote, collapsed && styles.clickable, orphaned && styles.orphaned)} />;`),
+ head(`export const Quote = ({ collapsed, orphaned }) =>
+ !collapsed && <div {...stylex.props(styles.quote, collapsed && styles.clickable, orphaned && styles.orphaned)} />;`),
+ );
+ expect(entry.combos).toEqual([
+ { collapsed: false, orphaned: false },
+ { collapsed: false, orphaned: true },
+ ]);
+ });
+
+ it('keeps every combination one side can still reach', () => {
+ const [entry] = plan(
+ base(`export const Quote = ({ onLocate, orphaned }) => {
+ const clickable = Boolean(onLocate) && !orphaned;
+ return <div className={cx(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />;
+};`),
+ head(`export const Quote = ({ clickable, orphaned }) => (
+ <div {...stylex.props(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />
+);`),
+ );
+ expect(entry.combos).toHaveLength(4);
+ });
+
+ it('treats a value the component does not model as possibly undefined', () => {
+ const [entry] = plan(
+ base(`export const Quote = ({ defaultCollapsed, orphaned }) => {
+ const clickable = defaultCollapsed !== undefined;
+ return <div className={cx(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />;
+};`),
+ head(`export const Quote = ({ defaultCollapsed, orphaned }) => {
+ const clickable = defaultCollapsed !== undefined;
+ return <div {...stylex.props(styles.quote, clickable && styles.clickable, orphaned && styles.orphaned)} />;
+};`),
+ );
+ expect(entry.combos).toHaveLength(4);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/reachable.ts b/packages/style-equivalence/src/plan/reachable.ts
new file mode 100644
index 00000000000..69ea554545c
--- /dev/null
+++ b/packages/style-equivalence/src/plan/reachable.ts
@@ -0,0 +1,112 @@
+import ts from 'typescript';
+
+import type { StyleElement } from '../extract';
+import { valueIdentifiers } from '../extract/identifiers';
+import type { Combo } from './combos';
+
+const FREE_LIMIT = 4;
+
+type Value = boolean | string | null | undefined;
+
+const parse = (text: string) => {
+ const source = ts.createSourceFile('c.ts', `(${text});`, ts.ScriptTarget.Latest, true);
+ const [statement] = source.statements;
+ return statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;
+};
+
+const evaluate = (node: ts.Expression, env: Record<string, Value>): Value => {
+ if (ts.isIdentifier(node)) return node.text === 'undefined' ? undefined : env[node.text];
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
+ return evaluate(node.expression, env);
+ if (ts.isPrefixUnaryExpression(node)) return !evaluate(node.operand, env);
+ if (ts.isCallExpression(node)) return Boolean(evaluate(node.arguments[0], env));
+ if (!ts.isBinaryExpression(node)) throw new Error('unsupported condition');
+ const left = evaluate(node.left, env);
+ switch (node.operatorToken.kind) {
+ case ts.SyntaxKind.AmpersandAmpersandToken: {
+ return left ? evaluate(node.right, env) : left;
+ }
+ case ts.SyntaxKind.BarBarToken: {
+ return left || evaluate(node.right, env);
+ }
+ case ts.SyntaxKind.QuestionQuestionToken: {
+ return left ?? evaluate(node.right, env);
+ }
+ case ts.SyntaxKind.EqualsEqualsEqualsToken: {
+ return left === evaluate(node.right, env);
+ }
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken: {
+ return left !== evaluate(node.right, env);
+ }
+ case ts.SyntaxKind.EqualsEqualsToken: {
+ return left == evaluate(node.right, env);
+ }
+ case ts.SyntaxKind.ExclamationEqualsToken: {
+ return left != evaluate(node.right, env);
+ }
+ default: {
+ throw new Error('unsupported condition');
+ }
+ }
+};
+
+interface Constraint {
+ free: string[];
+ holds: (env: Record<string, Value>) => boolean;
+}
+
+const constraintsOf = (chain: StyleElement[], names: Set<string>) => {
+ const found: Constraint[] = [];
+ const add = (text: string, check: (value: Value, env: Record<string, Value>) => boolean) => {
+ const node = parse(text);
+ if (!node) return;
+ found.push({
+ free: [...valueIdentifiers(node)].filter((name) => !names.has(name) && name !== 'undefined'),
+ holds: (env) => check(evaluate(node, env), env),
+ });
+ };
+ for (const element of chain) {
+ for (const guard of element.guards ?? []) add(guard, (value) => Boolean(value));
+ for (const [name, text] of Object.entries(element.derived ?? {}))
+ if (names.has(name)) add(text, (value, env) => Boolean(value) === Boolean(env[name]));
+ }
+ return found;
+};
+
+const FREE_VALUES: Value[] = [false, true, null, undefined];
+
+const satisfiable = (combo: Combo, constraints: Constraint[]) => {
+ const free = [...new Set(constraints.flatMap((constraint) => constraint.free))];
+ if (free.length > FREE_LIMIT) return true;
+ for (let index = 0; index < FREE_VALUES.length ** free.length; index++) {
+ const env: Record<string, Value> = { ...combo };
+ let rest = index;
+ for (const name of free) {
+ env[name] = FREE_VALUES[rest % FREE_VALUES.length];
+ rest = Math.floor(rest / FREE_VALUES.length);
+ }
+ try {
+ if (constraints.every((constraint) => constraint.holds(env))) return true;
+ } catch {
+ return true;
+ }
+ }
+ return false;
+};
+
+export const reachableCombos = (
+ combos: Combo[],
+ chains: Record<'base' | 'head', StyleElement[]>,
+) => {
+ if (combos.length < 2) return combos;
+ const names = new Set(Object.keys(combos[0]));
+ const sides = [chains.base, chains.head].map((chain) => constraintsOf(chain, names));
+ if (sides.every((constraints) => !constraints.length)) return combos;
+ const kept = combos.filter((combo) =>
+ sides.some((constraints) => satisfiable(combo, constraints)),
+ );
+ return kept.length ? kept : combos;
+};
diff --git a/packages/style-equivalence/src/plan/real.test.ts b/packages/style-equivalence/src/plan/real.test.ts
new file mode 100644
index 00000000000..d5f2cfe174b
--- /dev/null
+++ b/packages/style-equivalence/src/plan/real.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import type { RealComponent } from '../extract/types';
+import { generateModule } from '../generate/module';
+import { planFile } from './planFile';
+
+const realComponents: Record<string, RealComponent> = {
+ Tabs: {
+ leaf: true,
+ sample: (content) => `items={[{ key: 'a', label: 'a' }, { key: 'b', label: <>${content}</> }]}`,
+ source: '@lobehub/ui',
+ },
+ Text: { source: '@lobehub/ui', tag: { default: 'div', prop: 'as' } },
+};
+
+const options = {
+ adapters: [emotionStaticAdapter, stylexAdapter],
+ layoutComponents: ['Flexbox'],
+ realComponents,
+};
+
+const base = (
+ source = '@lobehub/ui',
+ element = '<Tabs className={styles.tabs} variant="square" items={items} />',
+) => `
+import { createStaticStyles } from '@lobehub/ui';
+import { Tabs } from '${source}';
+
+const styles = createStaticStyles(({ css }) => ({
+ tabs: css\`
+ [role='tablist'] {
+ width: 100%;
+
+ > [role='tab']:has([data-replace-all]) {
+ margin-inline-start: auto;
+ }
+ }
+ \`,
+}));
+
+export const View = ({ items }) => ${element};
+`;
+
+const head = (
+ source = '@lobehub/ui',
+ element = `<Tabs variant="square" classNames={{ list: stylex.props(styles.tabList).className, tab: stylex.props(styles.tab).className }} items={items} />`,
+) => `
+import * as stylex from '@stylexjs/stylex';
+import { Tabs } from '${source}';
+
+const styles = stylex.create({
+ tab: { marginInlineStart: { default: null, ':has([data-replace-all])': 'auto' } },
+ tabList: { width: '100%' },
+});
+
+export const View = ({ items }) => ${element};
+`;
+
+const config = { layoutComponents: ['Flexbox'], realComponents };
+
+const both = (before: string, after: string) => {
+ const extractions = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ return { extractions, plan: planFile('a.tsx', extractions.base, extractions.head, config) };
+};
+
+describe('a real library component rendered in place of the stand-in', () => {
+ it('marks an element whose tag is imported from the configured source', () => {
+ const [tabs] = extractFile(head(), 'a.tsx', options).elements;
+ expect(tabs.real).toBe(true);
+ expect(extractFile(head(), 'a.tsx', options).prelude).toContain(
+ "import { Tabs } from '@lobehub/ui';",
+ );
+ });
+
+ it('proves a className to classNames move by rendering the real component', () => {
+ const { plan } = both(base(), head());
+ expect(plan.cases[0].flags).toEqual([]);
+ expect(plan.cases[0].evidence).toEqual(['REAL_COMPONENT_RENDERED']);
+ expect(plan.cases[0].samples).toEqual([
+ { attributes: { 'data-replace-all': '' }, children: [], tag: 'div' },
+ ]);
+ });
+
+ it('passes the slot object to the real component and adds sample items', () => {
+ const { extractions, plan } = both(base(), head());
+ const module = generateModule(extractions.head, plan, 'head', {
+ layoutComponents: [],
+ realComponents,
+ });
+ expect(module).toContain('classNames={{ list: stylex.props(styles.tabList).className');
+ expect(module).toContain("items={[{ key: 'a', label: 'a' }");
+ expect(module).toContain('{...{"data-replace-all":""}}');
+ expect(module).not.toContain('__neutral("classNames"');
+ });
+
+ it('keeps the stand-in for a same-named component from another module', () => {
+ const { plan } = both(base('./Tabs'), head('./Tabs'));
+ expect(plan.cases[0].flags).toEqual(['PLACEMENT_NEUTRAL_PROP', 'PLACEMENT_SUBSTITUTED']);
+ expect(plan.cases[0].evidence).toBeUndefined();
+ expect(plan.cases[0].standIns).toEqual({ base: ['Tabs'], head: ['Tabs'] });
+ });
+
+ it('records no stand-in when every component on the chain renders for real', () => {
+ expect(both(base(), head()).plan.cases[0].standIns).toBeUndefined();
+ });
+
+ it('records the stand-ins of an element that exists on one side only', () => {
+ const { plan } = both(
+ base(undefined, '<div className={styles.tabs} />'),
+ head(undefined, '<Select {...stylex.props(styles.tab)} />'),
+ );
+ expect(plan.standIns).toEqual({ 'head:View#0': ['Select'] });
+ });
+
+ it('keeps the stand-in when a leaf component would have to host a styled child', () => {
+ const child = (props: string) => `<Tabs className={styles.tabs}><span ${props}>x</span></Tabs>`;
+ const { plan } = both(
+ base(undefined, child('className={styles.tabs}')),
+ head(
+ undefined,
+ child('{...stylex.props(styles.tab)}').replace(
+ 'className={styles.tabs}',
+ '{...stylex.props(styles.tabList)}',
+ ),
+ ),
+ );
+ expect(plan.cases.at(-1)?.flags).toContain('PLACEMENT_SUBSTITUTED');
+ });
+});
diff --git a/packages/style-equivalence/src/plan/real.ts b/packages/style-equivalence/src/plan/real.ts
new file mode 100644
index 00000000000..4a114bfb309
--- /dev/null
+++ b/packages/style-equivalence/src/plan/real.ts
@@ -0,0 +1,48 @@
+import type { FileExtraction, RealComponent, StyleElement } from '../extract';
+import { hasTargets } from './inner';
+
+type Sides<T> = Record<'base' | 'head', T>;
+
+export const rendersReal = (
+ element: StyleElement,
+ last: boolean,
+ real: Record<string, RealComponent> | undefined,
+) => !!element.real && !!real?.[element.tag] && (last || !real[element.tag].leaf);
+
+export const realItemsOf = (
+ chains: Sides<StyleElement[]>,
+ real: Record<string, RealComponent> | undefined,
+) =>
+ new Set(
+ (['base', 'head'] as const).flatMap((side) =>
+ chains[side].filter((item, index) =>
+ rendersReal(item, index === chains[side].length - 1, real),
+ ),
+ ),
+ );
+
+export const sampleTargets = (
+ chains: Sides<StyleElement[]>,
+ extractions: Sides<FileExtraction>,
+) => {
+ const selectors: string[] = [];
+ for (const side of ['base', 'head'] as const) {
+ const slots = new Set(chains[side].flatMap((item) => item.slots));
+ const { rules, slotConditions } = extractions[side];
+ for (const rule of rules) if (rule.slot && slots.has(rule.slot)) selectors.push(rule.selector);
+ for (const slot of slots) selectors.push(...(slotConditions?.[slot] ?? []));
+ }
+ return hasTargets(selectors);
+};
+
+export const standInsOf = (
+ chain: StyleElement[],
+ rendered: (item: StyleElement, index: number) => boolean,
+ layout: Set<string>,
+) =>
+ chain
+ .filter(
+ (item, index) =>
+ !/^[a-z][\w-]*$/.test(item.tag) && !layout.has(item.tag) && !rendered(item, index),
+ )
+ .map((item) => item.tag);
diff --git a/packages/style-equivalence/src/plan/renderedStyle.test.ts b/packages/style-equivalence/src/plan/renderedStyle.test.ts
new file mode 100644
index 00000000000..05b22887e56
--- /dev/null
+++ b/packages/style-equivalence/src/plan/renderedStyle.test.ts
@@ -0,0 +1,102 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const plan = (before: string, after: string) => {
+ const pair = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ const result = planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] });
+ const module = (side: 'base' | 'head') =>
+ generateModule(pair[side], result, side, { layoutComponents: [] });
+ return { module, result };
+};
+
+describe('an inline style the synthetic page can evaluate', () => {
+ it('renders a style chosen by a boolean on the side that passes it to the style prop', () => {
+ const { module, result } = plan(
+ `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ overlay: css\`opacity: 0;\` }));
+
+export const Row = ({ uploading }) => (
+ <div className={styles.overlay} style={uploading ? { opacity: 1 } : undefined} />
+);
+`,
+ `import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({ overlay: { opacity: 0 } });
+
+export const Row = ({ uploading }) => <div {...sx(styles.overlay, uploading && { opacity: 1 })} />;
+`,
+ );
+ const [entry] = result.cases;
+ expect(entry.flags).toEqual([]);
+ expect(entry.variables).toEqual([
+ { kinds: { base: 'boolean', head: 'boolean' }, name: 'uploading' },
+ ]);
+ expect(module('base')).toContain('style={(uploading ? { opacity: 1 } : undefined)}');
+ });
+
+ it('keeps a style that reads an imported constant and renders it on a stand-in', () => {
+ const { module, result } = plan(
+ `import { controlHeight, createStaticStyles, Select } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ trigger: css\`min-height: \${controlHeight.middle}px;\`,
+}));
+
+export const Filter = () => (
+ <Select className={styles.trigger} style={{ maxWidth: 260, minWidth: 160 }} />
+);
+`,
+ `import { controlHeight, Select } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ trigger: { borderRadius: 6 } });
+
+export const Filter = () => (
+ <Select
+ className={stylex.props(styles.trigger).className}
+ style={{ maxWidth: 260, minHeight: controlHeight.middle, minWidth: 160 }}
+ />
+);
+`,
+ );
+ const [entry] = result.cases;
+ expect(entry.flags).not.toContain('RUNTIME_STYLE_DROPPED');
+ const head = module('head');
+ expect(head).toMatch(/import \{[^}]*controlHeight[^}]*\} from '@lobehub\/ui'/);
+ expect(head).toContain(
+ 'style={({ maxWidth: 260, minHeight: controlHeight.middle, minWidth: 160 })}',
+ );
+ expect(module('base')).toContain('style={{"maxWidth":260,"minWidth":160}}');
+ });
+
+ it('leaves a style that reads a local value it cannot model unrendered', () => {
+ const { module } = plan(
+ `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ bar: css\`opacity: 0;\` }));
+
+export const Bar = ({ width }) => <div className={styles.bar} style={{ width }} />;
+`,
+ `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ bar: { opacity: 0 } });
+
+export const Bar = ({ width }) => <div {...stylex.props(styles.bar)} style={{ width }} />;
+`,
+ );
+ expect(module('base')).not.toContain('style={(');
+ });
+});
diff --git a/packages/style-equivalence/src/plan/selectorTree.ts b/packages/style-equivalence/src/plan/selectorTree.ts
new file mode 100644
index 00000000000..5e08e98b20e
--- /dev/null
+++ b/packages/style-equivalence/src/plan/selectorTree.ts
@@ -0,0 +1,23 @@
+import selectorParser from 'postcss-selector-parser';
+
+export interface SelectorNode {
+ attribute?: string;
+ nodes?: SelectorNode[];
+ operator?: string;
+ type: string;
+ value?: string;
+}
+
+export const parseSelectorList = (text: string): SelectorNode[][] | undefined => {
+ let selectors: SelectorNode[][] = [];
+ try {
+ selectorParser((root) => {
+ // Reading .nodes through the library types trips TS5115 (circular Container/Diff instantiation).
+ const { nodes } = root as unknown as { nodes: Array<{ nodes: SelectorNode[] }> };
+ selectors = nodes.map((selector) => selector.nodes);
+ }).processSync(text);
+ } catch {
+ return undefined;
+ }
+ return selectors;
+};
diff --git a/packages/style-equivalence/src/plan/stateAttribute.test.ts b/packages/style-equivalence/src/plan/stateAttribute.test.ts
new file mode 100644
index 00000000000..48a6969a745
--- /dev/null
+++ b/packages/style-equivalence/src/plan/stateAttribute.test.ts
@@ -0,0 +1,71 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const base = (value = 'true') => `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ day: css\`
+ color: red;
+
+ &[data-rate-limited='${value}'] [data-day-secondary] {
+ color: inherit;
+ }
+ \`,
+ tokens: css\`color: gray;\`,
+}));
+
+export const Day = ({ rateLimited }) => (
+ <div className={styles.day} data-rate-limited={rateLimited}>
+ <span data-day-secondary className={styles.tokens} />
+ </div>
+);
+`;
+
+const head = `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ day: { color: 'red' },
+ inheritColor: { color: 'inherit' },
+ tokens: { color: 'gray' },
+});
+
+export const Day = ({ rateLimited }) => (
+ <div {...stylex.props(styles.day)} data-rate-limited={rateLimited}>
+ <span data-day-secondary {...stylex.props(styles.tokens, rateLimited && styles.inheritColor)} />
+ </div>
+);
+`;
+
+const plan = (before: string) => {
+ const pair = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(head, 'a.tsx', options),
+ };
+ return { pair, plan: planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] }) };
+};
+
+describe('a state attribute driven by the variable a StyleX condition reads', () => {
+ it('models the attribute with the variable on the side that styles through it', () => {
+ const { pair, plan: result } = plan(base());
+ const tokens = result.cases.find((entry) => entry.key === 'a.tsx|Day#1');
+ expect(tokens?.flags).not.toContain('ASYMMETRIC_CONDITION');
+ expect(tokens?.variables).toEqual([
+ { kinds: { base: 'boolean', head: 'boolean' }, name: 'rateLimited' },
+ ]);
+ expect(generateModule(pair.base, result, 'base', { layoutComponents: [] })).toContain(
+ 'data-rate-limited={rateLimited}',
+ );
+ });
+
+ it('leaves an attribute whose selectors compare it with other values unmodeled', () => {
+ const tokens = plan(base('open')).plan.cases.find((entry) => entry.key === 'a.tsx|Day#1');
+ expect(tokens?.flags).toContain('ASYMMETRIC_CONDITION');
+ });
+});
diff --git a/packages/style-equivalence/src/plan/stylesProp.test.ts b/packages/style-equivalence/src/plan/stylesProp.test.ts
new file mode 100644
index 00000000000..67dd170f01b
--- /dev/null
+++ b/packages/style-equivalence/src/plan/stylesProp.test.ts
@@ -0,0 +1,52 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const base = `import { controlHeight, createStaticStyles, Segmented } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ filterItem: css\`height: \${controlHeight.small}px;\`,
+}));
+
+export const Filters = () => <Segmented classNames={{ item: styles.filterItem }} size={'small'} />;
+`;
+
+const head = (prop: string) => `import { controlHeight, Segmented } from '@lobehub/ui';
+
+const segmentedStyles = { item: { height: controlHeight.small } };
+
+export const Filters = () => <Segmented size={'small'} styles={${prop}} />;
+`;
+
+const plan = (after: string) => {
+ const pair = {
+ base: extractFile(base, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ const result = planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] });
+ return { module: generateModule(pair.head, result, 'head', { layoutComponents: [] }), result };
+};
+
+describe("a component's styles prop", () => {
+ it('pairs with the classNames slot it replaces and renders the slot style', () => {
+ const { module, result } = plan(head('segmentedStyles'));
+ expect(result.unpaired).toEqual([]);
+ expect(result.cases.map((entry) => entry.elementIds)).toEqual([
+ { base: 'Filters#0', head: 'Filters#0' },
+ ]);
+ expect(module).toContain('const segmentedStyles = { item: { height: controlHeight.small } };');
+ expect(module).toContain('__neutral("styles", segmentedStyles)');
+ expect(module).toContain('style={value as any}');
+ });
+
+ it('accepts an inline object of slot styles', () => {
+ const { result } = plan(head('{ item: { height: controlHeight.small } }'));
+ expect(result.unpaired).toEqual([]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/tables.test.ts b/packages/style-equivalence/src/plan/tables.test.ts
new file mode 100644
index 00000000000..b618d2d0a26
--- /dev/null
+++ b/packages/style-equivalence/src/plan/tables.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { combosFor } from './combos';
+import { planFile } from './planFile';
+import { ABSENT_KEY } from './tables';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };
+
+const base = (
+ table = `{
+ added: styles.kindAdded,
+ deleted: styles.kindDeleted,
+}`,
+) => `import { createStaticStyles, cx } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ kindAdded: css\`background: green;\`,
+ kindDeleted: css\`background: red;\`,
+ kindDot: css\`width: 8px;\`,
+}));
+
+const KIND_CLASS: Record<Kind, string> = ${table};
+
+export const KindDot = ({ className, kind }) => (
+ <span className={cx(styles.kindDot, KIND_CLASS[kind], className)} />
+);
+`;
+
+const head = (lookup = 'KIND_STYLE[kind]') => `import { cx } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ kindAdded: { backgroundColor: 'green' },
+ kindDeleted: { backgroundColor: 'red' },
+ kindDot: { width: '8px' },
+});
+
+const KIND_STYLE = {
+ added: styles.kindAdded,
+ deleted: styles.kindDeleted,
+} as const satisfies Record<Kind, unknown>;
+
+export const KindDot = ({ className, kind }) => (
+ <span className={cx(stylex.props(styles.kindDot, ${lookup}).className, className)} />
+);
+`;
+
+const plan = (before: string, after: string) =>
+ planFile('a.tsx', extractFile(before, 'a.tsx', options), extractFile(after, 'a.tsx', options), {
+ layoutComponents: ['Flexbox'],
+ }).cases[0];
+
+describe('fixed table lookups', () => {
+ it('records the key set of every top-level const object literal that is only read', () => {
+ expect(extractFile(base(), 'a.tsx', options).tables).toEqual({
+ KIND_CLASS: ['added', 'deleted'],
+ });
+ expect(extractFile(head(), 'a.tsx', options).tables).toEqual({
+ KIND_STYLE: ['added', 'deleted'],
+ });
+ });
+
+ it('skips a table that is written to, spread from or keyed by a computed name', () => {
+ const written = `${base()}\nKIND_CLASS.added = 'x';`;
+ expect(extractFile(written, 'a.tsx', options).tables).toEqual({});
+ const spread = base(`{ ...OTHER, added: styles.kindAdded }`);
+ expect(extractFile(spread, 'a.tsx', options).tables).toEqual({});
+ const computed = base(`{ [KEY]: styles.kindAdded }`);
+ expect(extractFile(computed, 'a.tsx', options).tables).toEqual({});
+ });
+
+ it('models a lookup key over the shared key set and every key renders', () => {
+ const entry = plan(base(), head());
+ expect(entry.flags).toEqual([]);
+ expect(entry.evidence).toEqual(['TABLE_KEYS']);
+ expect(entry.variables).toEqual([
+ {
+ kinds: { base: 'unknown', head: 'unknown' },
+ name: 'kind',
+ values: ['added', 'deleted', ABSENT_KEY],
+ },
+ ]);
+ expect(entry.combos).toEqual([{ kind: 'added' }, { kind: 'deleted' }, { kind: ABSENT_KEY }]);
+ });
+
+ it('keeps the flag when the two tables have different keys', () => {
+ const entry = plan(
+ base(`{ added: styles.kindAdded, deleted: styles.kindDeleted, renamed: styles.kindAdded }`),
+ head(),
+ );
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ expect(entry.evidence).toBeUndefined();
+ });
+
+ it('keeps the flag when the key is also used outside the lookup', () => {
+ const entry = plan(base(), head(`kind === 'added' && KIND_STYLE[kind]`));
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when the looked-up value is read further', () => {
+ const entry = plan(base(), head('KIND_STYLE[kind].x'));
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+
+ it('keeps the flag when the table is not a local const literal', () => {
+ const entry = plan(base(), head('IMPORTED[kind]'));
+ expect(entry.flags).toEqual(['VARIABLE_UNMODELED']);
+ });
+});
+
+describe('combosFor with value domains', () => {
+ it('crosses every boolean combination with every domain value', () => {
+ expect(combosFor(['on', 'tone'], { tone: ['a', 'b'] }).combos).toEqual([
+ { on: false, tone: 'a' },
+ { on: false, tone: 'b' },
+ { on: true, tone: 'a' },
+ { on: true, tone: 'b' },
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/plan/tables.ts b/packages/style-equivalence/src/plan/tables.ts
new file mode 100644
index 00000000000..4578bc74f13
--- /dev/null
+++ b/packages/style-equivalence/src/plan/tables.ts
@@ -0,0 +1,66 @@
+import ts from 'typescript';
+
+import type { StyleElement } from '../extract';
+import { valueIdentifierNodes } from '../extract/identifiers';
+import { parseExpression } from './knobs';
+
+export const ABSENT_KEY = '__style_equivalence_absent__';
+
+type Sides<T> = Record<'base' | 'head', T>;
+
+const outerOf = (node: ts.Node) => {
+ let current = node;
+ while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
+ return current;
+};
+
+const tablesRead = (chain: StyleElement[], name: string) => {
+ const tables: string[] = [];
+ for (const element of chain)
+ for (const binding of element.bindings) {
+ const parsed = parseExpression(binding.expr);
+ if (!parsed) return undefined;
+ for (const node of valueIdentifierNodes(parsed.expression)) {
+ if (node.text !== name) continue;
+ const access = node.parent;
+ if (
+ !ts.isElementAccessExpression(access) ||
+ access.argumentExpression !== node ||
+ !ts.isIdentifier(access.expression)
+ )
+ return undefined;
+ const outer = outerOf(access);
+ const { parent } = outer;
+ if (
+ (ts.isPropertyAccessExpression(parent) ||
+ ts.isElementAccessExpression(parent) ||
+ ts.isCallExpression(parent)) &&
+ parent.expression === outer
+ )
+ return undefined;
+ tables.push(access.expression.text);
+ }
+ }
+ return tables;
+};
+
+export const tableDomain = (
+ name: string,
+ chains: Sides<StyleElement[]>,
+ tables: Partial<Sides<Record<string, string[]> | undefined>>,
+) => {
+ const keySets: string[][] = [];
+ for (const side of ['base', 'head'] as const) {
+ const used = tablesRead(chains[side], name);
+ if (!used?.length) return undefined;
+ for (const table of used) {
+ const keys = tables[side]?.[table];
+ if (!keys?.length) return undefined;
+ keySets.push(keys);
+ }
+ }
+ const [first] = keySets;
+ const signature = (keys: string[]) => JSON.stringify([...new Set(keys)].sort());
+ if (keySets.some((keys) => signature(keys) !== signature(first))) return undefined;
+ return [...new Set(first)].sort().concat(ABSENT_KEY);
+};
diff --git a/packages/style-equivalence/src/plan/unsupported.test.ts b/packages/style-equivalence/src/plan/unsupported.test.ts
new file mode 100644
index 00000000000..4507195f3f8
--- /dev/null
+++ b/packages/style-equivalence/src/plan/unsupported.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { extractFile } from '../extract/index';
+import { categorizeCase } from '../verdict/categorize';
+import { planFile } from './planFile';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const base = (rule = 'all: unset;') => `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ close: css\`${rule}\` }));
+
+export const Close = () => <button className={styles.close} />;
+`;
+
+const head = (close: string) => `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({ close: ${close} });
+
+export const Close = () => <button {...stylex.props(styles.close)} />;
+`;
+
+const plan = (close: string, before = base()) =>
+ planFile(
+ 'a.tsx',
+ extractFile(before, 'a.tsx', options),
+ extractFile(head(close), 'a.tsx', options),
+ {
+ layoutComponents: [],
+ },
+ ).cases[0];
+
+describe('a StyleX key the compiler drops', () => {
+ it('blocks a case whose head style uses all, at any depth', () => {
+ const entry = plan("{ all: 'unset' }");
+ expect(entry.flags).toEqual(['STYLEX_UNSUPPORTED:all']);
+ expect(categorizeCase(entry, { gaps: [], status: 'equal' })).toBe('blocking');
+ const nested = plan(
+ "{ cursor: { default: 'pointer', ':hover': { all: 'unset' } } }",
+ base('cursor: pointer;'),
+ );
+ expect(nested?.flags).toContain('STYLEX_UNSUPPORTED:all');
+ });
+
+ it('leaves all alone in an emotion template', () => {
+ expect(plan("{ cursor: 'pointer' }", base('cursor: pointer;')).flags).toEqual([]);
+ const emotion = extractFile(base(), 'a.tsx', options);
+ expect(emotion.unsupported).toBeUndefined();
+ });
+});
diff --git a/packages/style-equivalence/src/plan/wrapper.test.ts b/packages/style-equivalence/src/plan/wrapper.test.ts
new file mode 100644
index 00000000000..3c2f41db984
--- /dev/null
+++ b/packages/style-equivalence/src/plan/wrapper.test.ts
@@ -0,0 +1,124 @@
+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';
+
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const base = `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ player: css\`width: 4px;\` }));
+
+export const Player = ({ width }) => (
+ <div style={{ maxWidth: width }}>
+ <div className={styles.player} />
+ </div>
+);
+`;
+
+const head = `import * as stylex from '@stylexjs/stylex';
+
+import { sx } from '@/styles/sx';
+
+const hostMarker = stylex.defineMarker();
+const styles = stylex.create({ player: { width: '4px' } });
+
+export const Player = ({ width }) => (
+ <div {...sx([hostMarker], undefined, { maxWidth: width })}>
+ <div {...stylex.props(styles.player)} />
+ </div>
+);
+`;
+
+describe('a wrapper that only carries a marker and an inline style', () => {
+ it('pairs the styled child without the wrapper on either side', () => {
+ const pair = {
+ base: extractFile(base, 'a.tsx', options),
+ head: extractFile(head, 'a.tsx', options),
+ };
+ expect(pair.head.elements.map((element) => element.id)).toEqual(['Player#0', 'Player#1']);
+ const plan = planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] });
+ expect(plan.cases.map((entry) => entry.elementIds)).toEqual([
+ { base: 'Player#0', head: 'Player#1' },
+ ]);
+ const module = generateModule(pair.head, plan, 'head', { layoutComponents: [] });
+ const render = module.split('\n').find((line) => line.startsWith('"a.tsx|Player#0"'));
+ expect(render).toContain('data-synthetic-element="Player#1"');
+ expect(render).not.toContain('hostMarker');
+ });
+
+ it('leaves out a component ancestor whose className only adds a marker', () => {
+ const before = `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({ actions: css\`width: 4px;\` }));
+
+export const Group = () => (
+ <AccordionHeader className={'accordion-header'}>
+ <span className={styles.actions} />
+ </AccordionHeader>
+);
+`;
+ const after = `import { cx } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+
+const headerMarker = stylex.defineMarker();
+const styles = stylex.create({ actions: { width: '4px' } });
+
+export const Group = () => (
+ <AccordionHeader className={cx('accordion-header', stylex.props(headerMarker).className)}>
+ <span {...stylex.props(styles.actions)} />
+ </AccordionHeader>
+);
+`;
+ const pair = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ expect(pair.head.elements.map((element) => element.tag)).toEqual(['AccordionHeader', 'span']);
+ const plan = planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] });
+ const module = generateModule(pair.head, plan, 'head', { layoutComponents: [] });
+ const render = module.split('\n').find((line) => line.startsWith('"a.tsx|Group#0"'));
+ expect(render).toContain('data-synthetic-element="Group#1"');
+ expect(render).not.toContain('data-synthetic-element="Group#0"');
+ });
+
+ it('keeps a marker-only ancestor that pairs with a styled one on the other side', () => {
+ const before = `import { createStaticStyles } from '@lobehub/ui';
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css\`padding: 4px;\`,
+ toggle: css\`width: 4px;\`,
+}));
+
+export const Goal = () => (
+ <div className={styles.card}>
+ <span className={styles.toggle} />
+ </div>
+);
+`;
+ const after = `import * as stylex from '@stylexjs/stylex';
+
+const cardMarker = stylex.defineMarker();
+const styles = stylex.create({ toggle: { width: '4px' } });
+
+export const Goal = () => (
+ <div {...stylex.props(cardMarker)}>
+ <span {...stylex.props(styles.toggle)} />
+ </div>
+);
+`;
+ const pair = {
+ base: extractFile(before, 'a.tsx', options),
+ head: extractFile(after, 'a.tsx', options),
+ };
+ const plan = planFile('a.tsx', pair.base, pair.head, { layoutComponents: [] });
+ const toggle = plan.cases.find((entry) => entry.key === 'a.tsx|Goal#1');
+ expect(toggle?.chainOmit).toBeUndefined();
+ const module = generateModule(pair.head, plan, 'head', { layoutComponents: [] });
+ const render = module.split('\n').find((line) => line.startsWith('"a.tsx|Goal#1"'));
+ expect(render).toContain('data-synthetic-element="Goal#0"');
+ });
+});
diff --git a/packages/style-equivalence/src/report/api.ts b/packages/style-equivalence/src/report/api.ts
new file mode 100644
index 00000000000..653f6e9bf74
--- /dev/null
+++ b/packages/style-equivalence/src/report/api.ts
@@ -0,0 +1,251 @@
+import type { ReportCase } from './data';
+
+export interface VerdictEntry {
+ category: string;
+ file: string;
+ flags: string[];
+ hash: string;
+ key: string;
+ signedReasons?: string[];
+ signoff: 'missing' | 'not-needed' | 'stale' | 'valid';
+}
+
+export interface FollowInfo {
+ base: string;
+ head: string;
+ pinned: boolean;
+ requested: string;
+ runId: string;
+ startedAt?: string;
+}
+
+let servedRun = '';
+
+const remember = <T extends { follow?: FollowInfo }>(payload: T) => {
+ if (payload.follow) servedRun = payload.follow.runId;
+ return payload;
+};
+
+export interface RunPayload {
+ calibration: Array<{
+ detail: string;
+ file: string;
+ fixture: string;
+ fixtureId: string;
+ status: string;
+ synthetic: string;
+ }>;
+ cases: ReportCase[];
+ follow?: FollowInfo;
+ mutation: {
+ caught: number;
+ equivalent: number;
+ evaluated: number;
+ mutants: Array<{
+ caseKey: string;
+ description: string;
+ expected: string[];
+ detected: string[];
+ gaps?: string[];
+ operator: string;
+ outcome: string;
+ }>;
+ passed: boolean;
+ requested: number;
+ };
+ run: {
+ base: string;
+ conditions?: string[];
+ durationMs?: number;
+ head: string;
+ runId: string;
+ verifierVersion?: string;
+ widths?: number[];
+ };
+ verdict: { items: VerdictEntry[]; mergeable: boolean; reasons: string[] };
+}
+
+export const fetchRun = async (): Promise<RunPayload> => {
+ const response = await fetch('/api/run');
+ if (!response.ok) throw new Error(`/api/run ${response.status}`);
+ return remember(await response.json());
+};
+
+export const fetchCurrent = async (): Promise<FollowInfo> => {
+ const response = await fetch('/api/current');
+ if (!response.ok) throw new Error(`/api/current ${response.status}`);
+ return response.json();
+};
+
+export interface HashedElement {
+ bindings: Array<{ expr: string; prop: string; spread: boolean }>;
+ literalProps: Record<string, unknown>;
+ slots: string[];
+ tag: string;
+}
+
+export interface CaseDetail {
+ case?: ReportCase & {
+ plan: ReportCase['plan'] & {
+ combos: Array<Record<string, boolean | string>>;
+ variables: Array<{ kinds: Record<string, string>; name: string }>;
+ };
+ result: ReportCase['result'] & { unstableConditions: string[] };
+ };
+ evidence?: {
+ declarations: Partial<Record<'base' | 'head', Record<string, string>>>;
+ elements: Partial<Record<'base' | 'head', HashedElement[]>>;
+ };
+ extraction?: Partial<
+ Record<
+ 'base' | 'head',
+ { rules: Array<{ conditions: string[]; selector: string; slot?: string }> }
+ >
+ >;
+ item?: VerdictEntry;
+}
+
+export interface SideSnapshot {
+ error?: string;
+ target?: { box: number[]; key: string; tag: string; values: Record<string, string> };
+ targetKey?: string;
+}
+
+export interface CaseSnapshot {
+ base: SideSnapshot;
+ differences: Array<{ after?: string; before?: string; key: string; property: string }>;
+ head: SideSnapshot;
+ ignored: Array<{ key: string; property: string; reason: string }>;
+}
+
+const caseUrl = (key: string, action = '') => `/api/case/${encodeURIComponent(key)}${action}`;
+
+export const fetchCase = async (key: string): Promise<CaseDetail> => {
+ const response = await fetch(caseUrl(key));
+ if (!response.ok) throw new Error(`${response.status} ${(await response.json()).error ?? ''}`);
+ return response.json();
+};
+
+export const fetchSnapshot = async (
+ key: string,
+ condition: string,
+ combo: number,
+): Promise<CaseSnapshot> => {
+ const response = await fetch(
+ `${caseUrl(key, '/snapshot')}?condition=${encodeURIComponent(condition)}&combo=${combo}`,
+ );
+ if (!response.ok) throw new Error(`${response.status} ${(await response.json()).error ?? ''}`);
+ return response.json();
+};
+
+export const shotUrl = (key: string, side: 'base' | 'head', condition: string, combo: number) =>
+ `${caseUrl(key, '/shot')}?side=${side}&condition=${encodeURIComponent(condition)}&combo=${combo}&run=${encodeURIComponent(servedRun)}`;
+
+export interface CorpusEntry {
+ actual: string;
+ detail: string[];
+ expected: string;
+ feature: string;
+ id: string;
+ passed: boolean;
+}
+
+export interface SelfTestPayload {
+ css: CorpusEntry[];
+ passed: boolean;
+ ranAt: string;
+ source: CorpusEntry[];
+ verifierVersion: string;
+}
+
+export const fetchMethod = async (): Promise<{ selfTest: SelfTestPayload | null }> => {
+ const response = await fetch('/api/method');
+ if (!response.ok) throw new Error(`/api/method ${response.status}`);
+ return response.json();
+};
+
+export const cropShotUrl = (key: string, side: 'base' | 'head', condition: string, combo: number) =>
+ `${shotUrl(key, side, condition, combo)}&crop=1&reveal=1`;
+
+export type ReviewState = 'changed' | 'passed' | 'reworked' | 'todo' | 'waiting-agent';
+
+export interface ReviewView {
+ ask: string;
+ canPass: boolean;
+ category: string;
+ comboDifferences: Array<{ combo: number; condition: string; summary: string[] }>;
+ combos: Array<{ index: number; label: string }>;
+ component?: string;
+ differingConditions: string[];
+ errors: string[];
+ file: string;
+ flags: string[];
+ hash: string;
+ key: string;
+ needsAgent: boolean;
+ note?: { finding: string; suggestion: 'pass' | 'rework' };
+ rework?: { at: string; note: string; reviewer: string };
+ standIns: Partial<Record<'base' | 'head', string[]>>;
+ state: ReviewState;
+ styles: {
+ blocks: Array<{
+ rows: Array<{
+ after: string[];
+ before: string[];
+ differs: boolean;
+ label: string;
+ oneSided: boolean;
+ }>;
+ slot: string;
+ standIn?: string;
+ }>;
+ source: Partial<Record<'base' | 'head', Record<string, string>>>;
+ usage: Partial<Record<'base' | 'head', string[]>>;
+ };
+ summary: string[];
+ title: string;
+}
+
+export interface ReviewPayload {
+ conditions: string[];
+ counts: Record<ReviewState | 'proven' | 'total', number>;
+ follow?: FollowInfo;
+ items: ReviewView[];
+ pr?: { branch: string; number: number; title: string };
+ resolved: Array<{ key: string; note: string; resolvedAt: string }>;
+ run: { base: string; head: string; runId: string };
+ verdict: { mergeable: boolean; reasons: string[] };
+}
+
+export const fetchReview = async (): Promise<ReviewPayload> => {
+ const response = await fetch('/api/review');
+ if (!response.ok) throw new Error(`/api/review ${response.status}`);
+ return remember(await response.json());
+};
+
+export interface CaseReview {
+ conditions: string[];
+ item: ReviewView;
+ queued: boolean;
+}
+
+export const fetchCaseReview = async (key: string): Promise<CaseReview> => {
+ const response = await fetch(`/api/case/${encodeURIComponent(key)}/review`);
+ if (!response.ok) throw new Error(`/api/case review ${response.status}`);
+ return response.json();
+};
+
+export const postReview = async (body: {
+ action: 'pass' | 'rework';
+ key: string;
+ note: string;
+}): Promise<ReviewPayload> => {
+ const response = await fetch('/api/review', {
+ body: JSON.stringify(body),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+ const payload = await response.json();
+ if (!response.ok) throw new Error(payload.error ?? `/api/review ${response.status}`);
+ return remember(payload);
+};
diff --git a/packages/style-equivalence/src/report/data.test.ts b/packages/style-equivalence/src/report/data.test.ts
new file mode 100644
index 00000000000..31d5c1bb399
--- /dev/null
+++ b/packages/style-equivalence/src/report/data.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildTree, conditionColumns, fileMatrix, overviewRows, type ReportCase } from './data';
+
+const entry = (
+ key: string,
+ category: ReportCase['category'],
+ differing: string[] = [],
+ flags: string[] = [],
+): ReportCase => ({
+ category,
+ key,
+ plan: { file: key.split('|')[0], flags },
+ result: { differingConditions: differing, gaps: [], rootCauses: [] },
+});
+
+const cases = [
+ entry('src/a/Controls.tsx|A#0', 'difference', ['light/375/default']),
+ entry(
+ 'src/a/Controls.tsx|A#1',
+ 'difference',
+ ['light/375/default', 'dark/375/default'],
+ ['CROSS_COMPONENT'],
+ ),
+ entry('src/a/Controls.tsx|A#2', 'equal'),
+ entry('src/b/List.tsx|L#0', 'needs-signoff', [], ['PLACEMENT_SUBSTITUTED']),
+ entry('src/b/Item.tsx|I#0', 'equal'),
+];
+
+describe('buildTree', () => {
+ it('groups files by directory with their worst status and counts', () => {
+ expect(
+ buildTree(cases, [{ file: 'src/b/List.tsx', key: 'src/b/List.tsx|unpaired:base:L#9' }]),
+ ).toEqual([
+ {
+ directory: 'src/a',
+ files: [
+ {
+ file: 'src/a/Controls.tsx',
+ name: 'Controls.tsx',
+ open: 2,
+ status: 'difference',
+ total: 3,
+ },
+ ],
+ },
+ {
+ directory: 'src/b',
+ files: [
+ { file: 'src/b/Item.tsx', name: 'Item.tsx', open: 0, status: 'equal', total: 1 },
+ { file: 'src/b/List.tsx', name: 'List.tsx', open: 2, status: 'needs-signoff', total: 2 },
+ ],
+ },
+ ]);
+ });
+});
+
+describe('conditionColumns', () => {
+ it('orders columns by theme, then width, then state, with variants last', () => {
+ expect(
+ conditionColumns([
+ 'dark/375/default',
+ 'light/1280/default',
+ 'light/375/hover-chain',
+ 'light/375/default',
+ 'light/1280/default/rtl',
+ ]),
+ ).toEqual([
+ {
+ label: 'light/375/default',
+ state: 'default',
+ theme: 'light',
+ variant: undefined,
+ width: 375,
+ },
+ {
+ label: 'light/375/hover-chain',
+ state: 'hover-chain',
+ theme: 'light',
+ variant: undefined,
+ width: 375,
+ },
+ {
+ label: 'light/1280/default',
+ state: 'default',
+ theme: 'light',
+ variant: undefined,
+ width: 1280,
+ },
+ {
+ label: 'light/1280/default/rtl',
+ state: 'default',
+ theme: 'light',
+ variant: 'rtl',
+ width: 1280,
+ },
+ {
+ label: 'dark/375/default',
+ state: 'default',
+ theme: 'dark',
+ variant: undefined,
+ width: 375,
+ },
+ ]);
+ });
+});
+
+describe('fileMatrix', () => {
+ it('counts differing cases per condition and tells unflagged from flagged differences', () => {
+ const columns = conditionColumns([
+ 'light/375/default',
+ 'dark/375/default',
+ 'light/1280/default',
+ ]);
+ expect(fileMatrix(cases.slice(0, 3), columns)).toEqual([
+ { count: 2, label: 'light/375/default', status: 'difference' },
+ { count: 0, label: 'light/1280/default', status: 'equal' },
+ { count: 1, label: 'dark/375/default', status: 'flagged-difference' },
+ ]);
+ expect(
+ fileMatrix([entry('x.tsx|X#0', 'blocking')], columns).map((cell) => cell.status),
+ ).toEqual(['unknown', 'unknown', 'unknown']);
+ });
+});
+
+describe('overviewRows', () => {
+ it('lists files with open cases first, most open first, and folds fully equal files', () => {
+ const columns = conditionColumns(['light/375/default']);
+ const { equal, open } = overviewRows(cases, columns);
+ expect(open.map((row) => [row.file, row.open])).toEqual([
+ ['src/a/Controls.tsx', 2],
+ ['src/b/List.tsx', 1],
+ ]);
+ expect(open[0].matrix.map((cell) => cell.status)).toEqual(['difference']);
+ expect(equal.map((row) => row.file)).toEqual(['src/b/Item.tsx']);
+ });
+});
diff --git a/packages/style-equivalence/src/report/data.ts b/packages/style-equivalence/src/report/data.ts
new file mode 100644
index 00000000000..a74c38a7064
--- /dev/null
+++ b/packages/style-equivalence/src/report/data.ts
@@ -0,0 +1,168 @@
+export type ReportCategory = 'blocking' | 'difference' | 'equal' | 'needs-signoff';
+export type FileStatus = ReportCategory;
+export type CellStatus = 'difference' | 'equal' | 'flagged-difference' | 'unknown';
+
+export interface RootCause {
+ after?: string;
+ before?: string;
+ key: string;
+ property: string;
+}
+
+export interface ReportCase {
+ category: ReportCategory;
+ key: string;
+ plan: {
+ combos?: unknown[];
+ elementIds?: { base: string; head: string };
+ file: string;
+ flags: string[];
+ };
+ result: {
+ comboDifferences?: Array<{ combo: number; condition: string; rootCauses: RootCause[] }>;
+ differingConditions: string[];
+ errors?: string[];
+ gaps: string[];
+ rootCauses: RootCause[];
+ status?: string;
+ unstableConditions?: string[];
+ };
+}
+
+export interface UnpairedEntry {
+ file: string;
+ key: string;
+}
+
+export interface TreeFile {
+ file: string;
+ name: string;
+ open: number;
+ status: FileStatus;
+ total: number;
+}
+
+const RANK: Record<FileStatus, number> = {
+ 'blocking': 3,
+ 'difference': 2,
+ 'equal': 0,
+ 'needs-signoff': 1,
+};
+
+export const buildTree = (cases: ReportCase[], unpaired: UnpairedEntry[]) => {
+ const files = new Map<string, TreeFile>();
+ const touch = (file: string) => {
+ const existing = files.get(file);
+ if (existing) return existing;
+ const created: TreeFile = {
+ file,
+ name: file.slice(file.lastIndexOf('/') + 1),
+ open: 0,
+ status: 'equal',
+ total: 0,
+ };
+ files.set(file, created);
+ return created;
+ };
+ for (const entry of cases) {
+ const file = touch(entry.plan.file);
+ file.total++;
+ if (entry.category !== 'equal') file.open++;
+ if (RANK[entry.category] > RANK[file.status]) file.status = entry.category;
+ }
+ for (const entry of unpaired) {
+ const file = touch(entry.file);
+ file.total++;
+ file.open++;
+ if (RANK[file.status] < RANK['needs-signoff']) file.status = 'needs-signoff';
+ }
+ const directories = new Map<string, TreeFile[]>();
+ for (const file of files.values()) {
+ const directory = file.file.slice(0, Math.max(file.file.lastIndexOf('/'), 0));
+ directories.set(directory, [...(directories.get(directory) ?? []), file]);
+ }
+ return [...directories.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([directory, list]) => ({
+ directory,
+ files: list.sort((a, b) => a.name.localeCompare(b.name)),
+ }));
+};
+
+export interface ConditionColumn {
+ label: string;
+ state: string;
+ theme: string;
+ variant?: string;
+ width: number;
+}
+
+const BASE_STATES = ['default', 'hover-chain', 'hover-target', 'focus-visible'];
+const themeRank = (theme: string) => (theme === 'light' ? 0 : theme === 'dark' ? 1 : 2);
+const stateRank = (state: string) => {
+ const index = BASE_STATES.indexOf(state);
+ return index === -1 ? BASE_STATES.length : index;
+};
+
+export const conditionColumns = (labels: string[]): ConditionColumn[] =>
+ [...new Set(labels)]
+ .map((label) => {
+ const [theme, width, state, variant] = label.split('/');
+ return { label, state, theme, variant, width: Number(width) };
+ })
+ .sort(
+ (a, b) =>
+ themeRank(a.theme) - themeRank(b.theme) ||
+ a.theme.localeCompare(b.theme) ||
+ a.width - b.width ||
+ Number(Boolean(a.variant)) - Number(Boolean(b.variant)) ||
+ stateRank(a.state) - stateRank(b.state) ||
+ a.state.localeCompare(b.state) ||
+ (a.variant ?? '').localeCompare(b.variant ?? ''),
+ );
+
+const isFlagged = (entry: ReportCase) =>
+ entry.plan.flags.length > 0 || entry.result.gaps.length > 0;
+
+export const fileMatrix = (cases: ReportCase[], columns: ConditionColumn[]) => {
+ const measured = cases.filter((entry) => entry.category !== 'blocking');
+ return columns.map(({ label }) => {
+ if (!measured.length) return { count: 0, label, status: 'unknown' as CellStatus };
+ const differing = measured.filter((entry) => entry.result.differingConditions.includes(label));
+ const status: CellStatus = !differing.length
+ ? 'equal'
+ : differing.some((entry) => !isFlagged(entry))
+ ? 'difference'
+ : 'flagged-difference';
+ return { count: differing.length, label, status };
+ });
+};
+
+export const caseStrip = (entry: ReportCase, columns: ConditionColumn[]) =>
+ columns.map(({ label }) => ({
+ label,
+ status: (entry.category === 'blocking'
+ ? 'unknown'
+ : entry.result.differingConditions.includes(label)
+ ? isFlagged(entry)
+ ? 'flagged-difference'
+ : 'difference'
+ : 'equal') as CellStatus,
+ }));
+
+export const overviewRows = (cases: ReportCase[], columns: ConditionColumn[]) => {
+ const files = [...new Set(cases.map((entry) => entry.plan.file))].map((file) => {
+ const list = cases.filter((entry) => entry.plan.file === file);
+ return {
+ file,
+ matrix: fileMatrix(list, columns),
+ open: list.filter((entry) => entry.category !== 'equal').length,
+ };
+ });
+ return {
+ equal: files.filter((file) => !file.open),
+ open: files
+ .filter((file) => file.open)
+ .sort((a, b) => b.open - a.open || a.file.localeCompare(b.file)),
+ };
+};
diff --git a/packages/style-equivalence/src/report/declared.test.ts b/packages/style-equivalence/src/report/declared.test.ts
new file mode 100644
index 00000000000..c0173a6c1a0
--- /dev/null
+++ b/packages/style-equivalence/src/report/declared.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { declaredProperties } from './declared';
+
+describe('declaredProperties', () => {
+ it('reads property names from stylex objects and css templates and expands shorthands', () => {
+ expect(
+ declaredProperties([
+ "unreadDot: { flexShrink: 0, width: '8px', backgroundColor: { default: cssVar.colorInfo, ':hover': 'red' } }",
+ 'label: css`\n padding: 4px;\n &:hover { color: red; }\n`',
+ ]),
+ ).toEqual([
+ 'background-color',
+ 'color',
+ 'flex-shrink',
+ 'padding-bottom',
+ 'padding-left',
+ 'padding-right',
+ 'padding-top',
+ 'width',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/report/declared.ts b/packages/style-equivalence/src/report/declared.ts
new file mode 100644
index 00000000000..4d72e89347f
--- /dev/null
+++ b/packages/style-equivalence/src/report/declared.ts
@@ -0,0 +1,85 @@
+const SIDES = ['top', 'right', 'bottom', 'left'];
+const CORNERS = ['top-left', 'top-right', 'bottom-right', 'bottom-left'];
+
+const SHORTHANDS: Record<string, string[]> = {
+ 'animation': [
+ 'animation-name',
+ 'animation-duration',
+ 'animation-timing-function',
+ 'animation-delay',
+ 'animation-iteration-count',
+ 'animation-direction',
+ 'animation-fill-mode',
+ ],
+ 'background': [
+ 'background-color',
+ 'background-image',
+ 'background-position',
+ 'background-size',
+ 'background-repeat',
+ 'background-attachment',
+ 'background-origin',
+ 'background-clip',
+ ],
+ 'border': SIDES.flatMap((side) =>
+ ['width', 'style', 'color'].map((part) => `border-${side}-${part}`),
+ ),
+ 'border-color': SIDES.map((side) => `border-${side}-color`),
+ 'border-radius': CORNERS.map((corner) => `border-${corner}-radius`),
+ 'border-style': SIDES.map((side) => `border-${side}-style`),
+ 'border-width': SIDES.map((side) => `border-${side}-width`),
+ 'flex': ['flex-grow', 'flex-shrink', 'flex-basis'],
+ 'font': [
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'font-variant',
+ 'font-stretch',
+ 'line-height',
+ ],
+ 'gap': ['row-gap', 'column-gap'],
+ 'inset': SIDES,
+ 'margin': SIDES.map((side) => `margin-${side}`),
+ 'margin-block': ['margin-top', 'margin-bottom'],
+ 'margin-inline': ['margin-left', 'margin-right'],
+ 'overflow': ['overflow-x', 'overflow-y'],
+ 'padding': SIDES.map((side) => `padding-${side}`),
+ 'padding-block': ['padding-top', 'padding-bottom'],
+ 'padding-inline': ['padding-left', 'padding-right'],
+ 'transition': [
+ 'transition-property',
+ 'transition-duration',
+ 'transition-timing-function',
+ 'transition-delay',
+ ],
+};
+
+const IGNORED = new Set(['default']);
+
+const kebab = (name: string) =>
+ name.includes('-')
+ ? name.toLowerCase()
+ : name.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
+
+export const declaredProperties = (texts: string[]) => {
+ const found = new Set<string>();
+ for (const text of texts) {
+ const names = [...text.matchAll(/(?<![\w$:'"-])['"]?([A-Za-z][\w-]*)['"]?\s*:(?!:)/g)].map(
+ (match) => match[1],
+ );
+ for (const name of names.slice(1)) {
+ if (IGNORED.has(name)) continue;
+ const property = kebab(name);
+ for (const longhand of SHORTHANDS[property] ?? [property]) found.add(longhand);
+ }
+ }
+ return [...found].sort();
+};
+
+export const shorthandsIn = (text: string) =>
+ Object.keys(SHORTHANDS).filter((name) =>
+ new RegExp(`(?<![\\w-])${name}\\s*:`).test(
+ text.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`),
+ ),
+ );
diff --git a/packages/style-equivalence/src/report/index.html b/packages/style-equivalence/src/report/index.html
new file mode 100644
index 00000000000..6d7980bbe0b
--- /dev/null
+++ b/packages/style-equivalence/src/report/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>style-equivalence</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/packages/style-equivalence/src/report/knownGaps.ts b/packages/style-equivalence/src/report/knownGaps.ts
new file mode 100644
index 00000000000..e6cb5bf3894
--- /dev/null
+++ b/packages/style-equivalence/src/report/knownGaps.ts
@@ -0,0 +1,18 @@
+export const UNMODELED_SHAPES: Array<{ text: string; title: string }> = [
+ {
+ text: '改之前用 `& + &`(相邻同类元素)加分隔样式,改之后改成调用方传的 separated 这类属性。合成环境每个元素只挂一份,也不知道哪个调用点传了属性,两侧对不上会报成差异。',
+ title: '兄弟选择器换成调用方属性',
+ },
+ {
+ text: '合成环境只挂当前这一行,:last-child、:nth-child 这类位置选择器命中的结果和真实列表不同。改之后换成显式属性时,会报成差异。',
+ title: '位置伪类依赖真实列表',
+ },
+ {
+ text: '改之前用 `.table th`、`.kv dt` 这类嵌套标签规则写样式,合成环境里的占位子元素没有这些标签,会和没有样式的占位元素配对。',
+ title: '嵌套标签规则',
+ },
+ {
+ text: '组件把 xstyle 继续传给子组件时,工具不会跟进到子组件里去渲染,样式落在哪个节点没有被比较。',
+ title: 'xstyle 继续往下传',
+ },
+];
diff --git a/packages/style-equivalence/src/report/labels.test.ts b/packages/style-equivalence/src/report/labels.test.ts
new file mode 100644
index 00000000000..d3d961f2023
--- /dev/null
+++ b/packages/style-equivalence/src/report/labels.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { flagExplanation, flagLabel } from './labels';
+
+describe('flag labels', () => {
+ it('labels a file gap by its kind and keeps the stylesheet it names', () => {
+ expect(flagLabel('STYLESHEET_UNREADABLE:pkg/reset.css')).toBe('样式表读不到:pkg/reset.css');
+ expect(flagExplanation('STYLESHEET_UNREADABLE:pkg/reset.css')).toContain('读不到');
+ });
+
+ it('names a runtime style present on one side only in plain words', () => {
+ expect(flagLabel('RUNTIME_STYLE_DROPPED')).toBe('运行时 style 只在一侧');
+ expect(flagExplanation('RUNTIME_STYLE_DROPPED')).toContain('style=');
+ });
+
+ 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');
+ expect(flagExplanation(flag)).toContain('AcceptanceGoal、AcceptanceIdentity');
+ });
+
+ it('names the callers of a forwarded prop that were not compared', () => {
+ const flag = 'FORWARDED_CALLER_UNCHECKED:a.tsx,b.tsx';
+ expect(flagLabel(flag)).toBe('有调用方没比较:a.tsx、b.tsx');
+ expect(flagExplanation(flag)).toContain('a.tsx、b.tsx');
+ });
+
+ it('falls back to the raw flag when it has no label', () => {
+ expect(flagLabel('SOMETHING_NEW')).toBe('SOMETHING_NEW');
+ });
+});
diff --git a/packages/style-equivalence/src/report/labels.ts b/packages/style-equivalence/src/report/labels.ts
new file mode 100644
index 00000000000..1ec630abf4c
--- /dev/null
+++ b/packages/style-equivalence/src/report/labels.ts
@@ -0,0 +1,137 @@
+export const CATEGORY_LABELS: Record<string, string> = {
+ 'blocking': '阻塞',
+ 'difference': '差异',
+ 'equal': '已证明相等',
+ 'needs-signoff': '需签收',
+ 'unpaired': '未配对',
+};
+
+export const THEME_LABELS: Record<string, string> = { dark: '暗色', light: '亮色' };
+
+const STATE_LABELS: Record<string, string> = {
+ 'default': '默认',
+ 'focus-visible': 'focus',
+ 'hover-chain': 'hover 链',
+ 'hover-target': 'hover',
+};
+
+const VARIANT_LABELS: Record<string, string> = { 'reduced-motion': '减弱动效', 'rtl': 'RTL' };
+
+export const stateLabel = (state: string, variant?: string) =>
+ variant
+ ? (VARIANT_LABELS[variant] ?? variant)
+ : (STATE_LABELS[state] ?? state.replace(/^force(-chain)?:/, ''));
+
+export const FLAG_LABELS: Record<string, string> = {
+ ASYMMETRIC_CONDITION: '条件只在一侧',
+ COMBINATIONS_PAIRWISE: '组合两两覆盖',
+ CONTAINER_UNMODELED: '容器查询未建模',
+ CROSS_COMPONENT: '跨组件选择器',
+ DIFFERENCE_NOT_REPRODUCED: '差异没有复现',
+ INLINE_STYLE_SPREAD_ORDER: 'style 与展开属性顺序变了',
+ INNER_TARGET: '命中组件内部',
+ MEDIA_UNMODELED: '媒体条件未建模',
+ PLACEMENT_NEUTRAL_PROP: '非 className 属性',
+ PLACEMENT_SUBSTITUTED: '组件替换成 div',
+ PSEUDO_UNMODELED: '伪元素读不到',
+ RUNTIME_STYLE_DROPPED: '运行时 style 只在一侧',
+ STATE_UNMODELED: '状态伪类未建模',
+ STYLE_OUTSIDE_JSX: 'JSX 外的样式引用',
+ TAG_CHANGED: '标签变了',
+ TOOL_FALSE_POSITIVE: '工具误报',
+ UNPAIRED: '两侧配不上',
+ VARIABLE_UNMODELED: '变量无法枚举',
+};
+
+const GAP_LABELS: Record<string, string> = {
+ STYLESHEET_UNPARSEABLE: '样式表解析失败',
+ STYLESHEET_UNREADABLE: '样式表读不到',
+};
+
+const listed = (text: string) => text.split(',').filter(Boolean).join('、');
+
+export const partlyForwardedDetail = (detail: string) => {
+ const [tag, components = ''] = detail.split('|');
+ return { components: listed(components), tag };
+};
+
+const globalCounts = (detail: string) => {
+ const [removed = '0', added = '0'] = detail.split('/');
+ return { added, removed };
+};
+
+const DETAIL_LABELS: Record<string, (detail: string) => string> = {
+ STYLEX_UNSUPPORTED: (detail) => `StyleX 不支持 ${detail} 属性`,
+ GLOBAL_RULES_CHANGED: (detail) => {
+ const { added, removed } = globalCounts(detail);
+ return `全局样式规则变了(少了 ${removed} 条,多了 ${added} 条)`;
+ },
+ FORWARDED_CALLER_UNCHECKED: (detail) => `有调用方没比较:${listed(detail)}`,
+ INNER_TARGET_PARTLY_FORWARDED: (detail) =>
+ `只证明了传进组件的那个 ${partlyForwardedDetail(detail).tag}`,
+};
+
+const DETAIL_EXPLANATIONS: Record<string, (detail: string) => string> = {
+ STYLEX_UNSUPPORTED: (detail) =>
+ `stylex.create 里写了 ${detail},StyleX 编译时会把它丢掉,不生成任何样式(比如 all: 'unset' 不会重置按钮的原生外观)。改成逐条写出要重置的属性。`,
+ GLOBAL_RULES_CHANGED: (detail) => {
+ const { added, removed } = globalCounts(detail);
+ return `文件里不挂在任何元素上的全局规则(createGlobalStyle、引入的全局 CSS)两侧不一致:改之前有 ${removed} 条在改之后找不到原样的对应,改之后有 ${added} 条是新的。原样保留的规则会自动证明,这里要确认差别是有意的。`;
+ },
+ FORWARDED_CALLER_UNCHECKED: (detail) =>
+ `组件内部这个元素按「调用方没有传这个样式」渲染并比较了。仓库里还有这些文件提到了这个属性,但工具没有逐一比较它们传进来的样式:${listed(detail)}。`,
+ INNER_TARGET_PARTLY_FORWARDED: (detail) => {
+ const { components, tag } = partlyForwardedDetail(detail);
+ return `旧规则命中容器里所有的 ${tag};新代码只把样式交给了组件里的那一个 ${tag},这一处已单独渲染证明。其余地方的 ${tag}(${components || '容器里的其它内容'} 里渲染的)迁移后不再有这条样式,工具没有证明它们不存在。`;
+ },
+};
+
+export const flagLabel = (flag: string) => {
+ const [name, detail] = flag.split(/:(.*)/s);
+ if (FLAG_LABELS[flag]) return FLAG_LABELS[flag];
+ if (DETAIL_LABELS[name] && detail !== undefined) return DETAIL_LABELS[name](detail);
+ return GAP_LABELS[name] ? `${GAP_LABELS[name]}:${detail}` : flag;
+};
+
+export const shortKey = (key: string) => key.slice(key.indexOf('|') + 1);
+
+export const FLAG_EXPLANATIONS: Record<string, string> = {
+ ASYMMETRIC_CONDITION: '某个条件变量只出现在一侧,两侧的组合没法一一对应。',
+ COMBINATIONS_PAIRWISE: '条件变量的组合超过 16 种,只做了两两覆盖,不是全组合。',
+ CONTAINER_UNMODELED: '两侧命中这个元素的 @container 规则不同,容器尺寸没有建模。',
+ CROSS_COMPONENT:
+ '别的组件的选择器会命中这个元素(比如 .muted .control-label),合成环境里没有那个外层组件,这条规则的效果没有被比较。',
+ DIFFERENCE_NOT_REPRODUCED:
+ '一些条件下出现过差异,单独重跑这些用例时没有复现。可能是渲染时序造成的抖动,也可能只在整页组合下出现,需要人工确认。',
+ INLINE_STYLE_SPREAD_ORDER:
+ '两侧传的 style={…} 写法一样,但它和 {...props} 这类展开属性的先后顺序两侧不同,或者只有一侧有展开属性。展开对象里如果带 style,两侧谁覆盖谁就不同;工具不知道展开对象里有什么。',
+ INNER_TARGET:
+ '全局 CSS 的选择器指向组件内部的元素(比如 Image 里的 img),合成渲染看不到组件内部。',
+ MEDIA_UNMODELED:
+ '两侧命中这个元素的媒体条件不同,而且不是宽度条件(比如 hover: none),没有建模。',
+ PLACEMENT_NEUTRAL_PROP:
+ '样式通过 itemClassName、classNames 这类非 className 的属性传进组件,落到哪个节点由组件决定。',
+ PLACEMENT_SUBSTITUTED:
+ '元素是非布局组件,合成时换成了 div,只证明了样式槽本身等价,没证明组件把样式放在哪里。',
+ PSEUDO_UNMODELED:
+ '两侧命中这个元素的伪元素规则不同(比如 ::selection、::-webkit-scrollbar),读不到计算样式。',
+ RUNTIME_STYLE_DROPPED:
+ '同一个元素一侧传了 style={…}(运行时才知道的值),另一侧完全没有传,也没有把这个值交给样式调用。工具不渲染运行时值,左右截图一致不能说明 style 没丢。',
+ STATE_UNMODELED:
+ '两侧命中这个元素的状态伪类规则不同(比如 :checked、:disabled、:invalid),采集时元素不在这些状态,这部分样式没有被比较。',
+ STYLE_OUTSIDE_JSX:
+ '文件在 JSX 之外引用了样式(比如先算出 className 再传给元素),合成环境不知道它落在哪个元素上,这部分样式没有被比较。',
+ STYLESHEET_UNPARSEABLE: '文件引入的样式表解析失败,里面的规则没有被比较。',
+ STYLESHEET_UNREADABLE: '文件引入的样式表读不到(比如包里的 CSS),里面的规则没有被比较。',
+ TAG_CHANGED: '两侧的标签不同,浏览器默认样式和语义可能不同。',
+ TOOL_FALSE_POSITIVE:
+ '比较器报了差异,但这个用例带有上面的某个标记;签收表示确认差异是合成环境造成的,不是真实回归。',
+ UNPAIRED: '一侧多出或少了带样式的元素,没有可以比较的对象,只能逐条确认。',
+ VARIABLE_UNMODELED: '样式值依赖 props 或运行时数据,没法枚举取值。',
+};
+
+export const flagExplanation = (flag: string) => {
+ const [name, detail] = flag.split(/:(.*)/s);
+ if (DETAIL_EXPLANATIONS[name] && detail !== undefined) return DETAIL_EXPLANATIONS[name](detail);
+ return FLAG_EXPLANATIONS[flag] ?? FLAG_EXPLANATIONS[name];
+};
diff --git a/packages/style-equivalence/src/report/main.tsx b/packages/style-equivalence/src/report/main.tsx
new file mode 100644
index 00000000000..97bf0513484
--- /dev/null
+++ b/packages/style-equivalence/src/report/main.tsx
@@ -0,0 +1,22 @@
+import '@lobehub/ui/theme.css';
+import '@lobehub/ui/global.css';
+import '@lobehub/ui/style.css';
+import './report.css';
+
+import { ConfigProvider, setLobeTheme } from '@lobehub/ui';
+import { domAnimation, LazyMotion } from 'motion/react';
+import * as motion from 'motion/react-m';
+import { createRoot } from 'react-dom/client';
+
+import { App } from './ui/App';
+import { initialAppearance } from './ui/ThemeToggle';
+
+setLobeTheme({ appearance: initialAppearance() });
+
+createRoot(document.getElementById('root')!).render(
+ <LazyMotion features={domAnimation}>
+ <ConfigProvider motion={motion}>
+ <App />
+ </ConfigProvider>
+ </LazyMotion>,
+);
diff --git a/packages/style-equivalence/src/report/method.test.ts b/packages/style-equivalence/src/report/method.test.ts
new file mode 100644
index 00000000000..bfd44135877
--- /dev/null
+++ b/packages/style-equivalence/src/report/method.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ReportCase } from './data';
+import { aaSummary, conditionScope } from './method';
+
+const entry = (key: string, unstable: string[] = []): ReportCase => ({
+ category: unstable.length ? 'blocking' : 'equal',
+ key,
+ plan: { file: 'src/A.tsx', flags: [] },
+ result: { differingConditions: [], gaps: [], rootCauses: [], unstableConditions: unstable },
+});
+
+describe('aaSummary', () => {
+ it('counts self-comparisons and lists the unstable ones per case', () => {
+ expect(
+ aaSummary([entry('src/A.tsx|A#0'), entry('src/A.tsx|A#1', ['light/600/force:active'])], 3),
+ ).toEqual({
+ checks: 6,
+ unstable: [{ conditions: ['light/600/force:active'], key: 'src/A.tsx|A#1' }],
+ });
+ });
+});
+
+describe('conditionScope', () => {
+ it('says all conditions when a mutation was expected everywhere, otherwise names them', () => {
+ expect(conditionScope(['a', 'b'], 2)).toBe('全部 2 种条件');
+ expect(conditionScope(['a#0', 'a#1', 'b#0'], 2)).toBe('全部 2 种条件');
+ expect(conditionScope(['dark/375/default'], 12)).toBe('dark/375/default');
+ expect(conditionScope(['a', 'b', 'c', 'd'], 12)).toBe('12 种条件里的 4 种');
+ });
+});
diff --git a/packages/style-equivalence/src/report/method.ts b/packages/style-equivalence/src/report/method.ts
new file mode 100644
index 00000000000..240edf91b78
--- /dev/null
+++ b/packages/style-equivalence/src/report/method.ts
@@ -0,0 +1,15 @@
+import type { ReportCase } from './data';
+
+export const aaSummary = (cases: ReportCase[], conditionCount: number) => ({
+ checks: cases.length * conditionCount,
+ unstable: cases
+ .filter((entry) => entry.result.unstableConditions?.length)
+ .map((entry) => ({ conditions: entry.result.unstableConditions!, key: entry.key })),
+});
+
+export const conditionScope = (labels: string[], total: number) => {
+ const expected = [...new Set(labels.map((label) => label.split('#')[0]))];
+ if (expected.length === total) return `全部 ${total} 种条件`;
+ if (expected.length <= 3) return expected.join('、');
+ return `${total} 种条件里的 ${expected.length} 种`;
+};
diff --git a/packages/style-equivalence/src/report/plain.test.ts b/packages/style-equivalence/src/report/plain.test.ts
new file mode 100644
index 00000000000..1db0781af60
--- /dev/null
+++ b/packages/style-equivalence/src/report/plain.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from 'vitest';
+
+import { askSentence, comboLabel, differenceSummary } from './plain';
+
+const cause = (property: string, before: string, after: string) => ({
+ after,
+ before,
+ key: 'root.0',
+ property,
+});
+
+describe('differenceSummary', () => {
+ it('describes a border that appeared in one line', () => {
+ const lines = differenceSummary([
+ cause('border-block-end-color', 'rgb(102, 102, 102)', 'rgb(176, 176, 176)'),
+ cause('border-block-end-style', 'none', 'solid'),
+ cause('border-block-end-width', '0px', '1px'),
+ cause('border-top-style', 'none', 'solid'),
+ ]);
+ expect(lines).toEqual(['边框 无 → 1px solid rgb(176, 176, 176)']);
+ });
+
+ it('names a text colour change', () => {
+ expect(differenceSummary([cause('color', 'rgb(102, 102, 102)', 'rgb(138, 138, 138)')])).toEqual(
+ ['文字颜色 rgb(102, 102, 102) → rgb(138, 138, 138)'],
+ );
+ });
+
+ it('shows two families and counts the rest', () => {
+ const lines = differenceSummary([
+ cause('color', 'a', 'b'),
+ cause('padding-top', '0px', '8px'),
+ cause('font-feature-settings', '"tnum"', 'normal'),
+ cause('box-shadow', 'none', '0 0 1px red'),
+ cause('animation-duration', '0s', '1s'),
+ ]);
+ expect(lines).toEqual(['文字颜色 a → b', '间距 0px → 8px', '另有 3 处']);
+ });
+
+ it('describes a missing element', () => {
+ expect(differenceSummary([cause('node', 'DIV', 'undefined')])).toEqual(['元素 DIV → 不存在']);
+ });
+});
+
+describe('comboLabel', () => {
+ it('turns booleans into 是 / 否', () => {
+ expect(comboLabel({ device: true })).toBe('device:是');
+ expect(comboLabel({ active: false, open: true })).toBe('active:否 · open:是');
+ expect(comboLabel({})).toBe('默认');
+ });
+
+ it('shows a table key as it is', () => {
+ expect(comboLabel({ kind: 'added', open: false })).toBe('kind:added · open:否');
+ });
+});
+
+describe('askSentence', () => {
+ it('asks about each value of an unmodeled variable', () => {
+ expect(
+ askSentence(
+ { category: 'needs-signoff', flags: ['VARIABLE_UNMODELED'] },
+ { variables: ['device'] },
+ ),
+ ).toContain('取决于 device');
+ });
+
+ it('names the component and prop for placement', () => {
+ expect(
+ askSentence(
+ { category: 'needs-signoff', flags: ['PLACEMENT_SUBSTITUTED'] },
+ { component: 'SkillsIcon', prop: 'className', variables: [] },
+ ),
+ ).toContain('交给 SkillsIcon 的 className');
+ });
+
+ it('explains a difference and a blocking item plainly', () => {
+ expect(askSentence({ category: 'difference', flags: [] }, { variables: [] })).toContain(
+ '不一样',
+ );
+ expect(askSentence({ category: 'blocking', flags: [] }, { variables: [] })).toContain('出错');
+ });
+
+ it('asks whether a runtime style was lost on purpose', () => {
+ const text = askSentence(
+ { category: 'needs-signoff', flags: ['RUNTIME_STYLE_DROPPED'] },
+ { variables: [] },
+ );
+ expect(text).toContain('style=');
+ expect(text).not.toContain('拿不准');
+ });
+
+ it('says which components a partly forwarded rule may still reach', () => {
+ const text = askSentence(
+ {
+ category: 'needs-signoff',
+ flags: ['INNER_TARGET', 'INNER_TARGET_PARTLY_FORWARDED:h1|AcceptanceGoal,ReadChecks'],
+ },
+ { variables: [] },
+ );
+ expect(text).toContain('AcceptanceGoal、ReadChecks');
+ expect(text).toContain('h1');
+ expect(text).not.toMatch(/[A-Z]{3,}_[A-Z]/);
+ });
+
+ it('names a caller of a forwarded prop that was not compared', () => {
+ const text = askSentence(
+ { category: 'needs-signoff', flags: ['FORWARDED_CALLER_UNCHECKED:src/Other.tsx'] },
+ { variables: [] },
+ );
+ expect(text).toContain('src/Other.tsx');
+ });
+
+ it('never prints flag codes', () => {
+ const text = askSentence(
+ { category: 'needs-signoff', flags: ['CROSS_COMPONENT', 'MEDIA_UNMODELED'] },
+ { variables: [] },
+ );
+ expect(text).not.toMatch(/[A-Z]{3,}_[A-Z]/);
+ });
+});
diff --git a/packages/style-equivalence/src/report/plain.ts b/packages/style-equivalence/src/report/plain.ts
new file mode 100644
index 00000000000..36ae1c8a550
--- /dev/null
+++ b/packages/style-equivalence/src/report/plain.ts
@@ -0,0 +1,131 @@
+import type { Combo } from '../plan/combos';
+import { partlyForwardedDetail } from './labels';
+
+interface Cause {
+ after?: string;
+ before?: string;
+ property: string;
+}
+
+const FAMILIES: Array<[string, RegExp]> = [
+ ['元素', /^(node|tag|text)$/],
+ ['边框', /^border/],
+ ['轮廓', /^outline/],
+ ['背景', /^background/],
+ ['文字颜色', /^color$/],
+ ['阴影', /shadow$/],
+ ['动画', /^(animation|transition)/],
+ ['字体', /^(font|line-height|letter-spacing|text-|white-space|word-)/],
+ ['间距', /^(padding|margin|gap|row-gap|column-gap)/],
+ ['位置', /^(inset|top|right|bottom|left|position|z-index|transform)/],
+ ['尺寸', /(width|height|-size)$|^(inline-size|block-size)/],
+ ['布局', /^(display|flex|align|justify|grid|order|place)/],
+];
+
+const familyOf = (property: string) =>
+ FAMILIES.find(([, pattern]) => pattern.test(property))?.[0] ?? '其他';
+
+const shown = (value: string | undefined) =>
+ value === undefined || value === 'undefined' ? '不存在' : value;
+
+const borderLine = (causes: Cause[]) => {
+ const edge = causes[0].property.replace(/-(width|style|color)$/, '');
+ const part = (name: string) => causes.find((cause) => cause.property === `${edge}-${name}`);
+ const [width, style, color] = [part('width'), part('style'), part('color')];
+ if (!width && !style) return undefined;
+ const describe = (side: 'after' | 'before') => {
+ if (style?.[side] === 'none' || width?.[side] === '0px') return '无';
+ return [width?.[side], style?.[side], color?.[side]].filter(Boolean).join(' ');
+ };
+ return `边框 ${describe('before')} → ${describe('after')}`;
+};
+
+const familyLine = (family: string, causes: Cause[]) => {
+ const border = family === '边框' ? borderLine(causes) : undefined;
+ if (border) return border;
+ const [first] = causes;
+ return `${family} ${shown(first.before)} → ${shown(first.after)}`;
+};
+
+export const differenceSummary = (causes: Cause[], limit = 2) => {
+ const families = new Map<string, Cause[]>();
+ for (const cause of causes) {
+ const family = familyOf(cause.property);
+ families.set(family, [...(families.get(family) ?? []), cause]);
+ }
+ const lines = [...families].slice(0, limit).map(([family, list]) => familyLine(family, list));
+ const rest = families.size - limit;
+ return rest > 0 ? [...lines, `另有 ${rest} 处`] : lines;
+};
+
+export const comboLabel = (combo: Combo) => {
+ const entries = Object.entries(combo);
+ return entries.length
+ ? entries
+ .map(
+ ([name, value]) => `${name}:${typeof value === 'string' ? value : value ? '是' : '否'}`,
+ )
+ .join(' · ')
+ : '默认';
+};
+
+const GAPS: Record<string, string> = {
+ CONTAINER_UNMODELED: '容器查询',
+ MEDIA_UNMODELED: '媒体查询',
+ PSEUDO_UNMODELED: '伪元素',
+ STATE_UNMODELED: '工具触发不了的交互状态',
+};
+
+export interface AskContext {
+ component?: string;
+ prop?: string;
+ variables: string[];
+}
+
+export const askSentence = (item: { category: string; flags: string[] }, context: AskContext) => {
+ if (item.category === 'blocking') return '工具渲染这个元素时出错了,没有截图可看。';
+ if (item.category === 'unpaired') return '这个元素只在一侧出现,看一下是不是本来就该删掉或新增。';
+ if (item.category === 'difference' && !item.flags.length)
+ return '工具发现左右不一样,看一下是不是迁移造成的。';
+ const names = new Set(item.flags.map((flag) => flag.split(':')[0]));
+ const lines: string[] = [];
+ if (names.has('VARIABLE_UNMODELED'))
+ lines.push(
+ `这个元素的样子取决于 ${context.variables.join('、') || '运行时数据'},工具没法自己枚举。看一下每种取值下左右是不是一样。`,
+ );
+ if (names.has('PLACEMENT_SUBSTITUTED') || names.has('PLACEMENT_NEUTRAL_PROP'))
+ lines.push(
+ `样式交给 ${context.component ?? '组件'} 的 ${context.prop ?? 'className'} 处理,组件内部怎么用它工具看不到。`,
+ );
+ const partly = item.flags.find((flag) => flag.startsWith('INNER_TARGET_PARTLY_FORWARDED:'));
+ if (partly) {
+ const { components, tag } = partlyForwardedDetail(partly.slice(partly.indexOf(':') + 1));
+ lines.push(
+ `旧代码给容器里所有的 ${tag} 加了样式,新代码只把它传给了组件里的那一个 ${tag}(已单独证明)。${components ? `看一下 ${components} 里还会不会渲染 ${tag},` : ''}如果会,那些 ${tag} 迁移后就没有这条样式了。`,
+ );
+ }
+ const callers = item.flags.find((flag) => flag.startsWith('FORWARDED_CALLER_UNCHECKED:'));
+ if (callers)
+ lines.push(
+ `这个元素的样式由调用方传进来。没传的情况已比较过;${callers
+ .slice(callers.indexOf(':') + 1)
+ .split(',')
+ .join('、')} 也提到了这个属性,工具没有比较它们传的样式。`,
+ );
+ if (names.has('RUNTIME_STYLE_DROPPED'))
+ lines.push(
+ '改之前和改之后只有一侧给这个元素传了 style={…},另一侧把它去掉了。截图里看不出运行时样式,看一下代码里是不是漏传了。',
+ );
+ if (names.has('INLINE_STYLE_SPREAD_ORDER'))
+ lines.push(
+ '两侧的 style 一样,只是和 {...展开属性} 的先后顺序换了,或者只有一侧有展开属性。确认展开的对象里没有 style,就没有影响。',
+ );
+ if (names.has('STYLE_OUTSIDE_JSX')) lines.push('这个文件在 JSX 之外也用到了样式,工具比较不了。');
+ if (names.has('GLOBAL_RULES_CHANGED'))
+ lines.push('这个文件的全局样式规则两侧对不上,看一下少掉或改掉的那几条是不是有意的。');
+ const gaps = [...names].filter((name) => GAPS[name]).map((name) => GAPS[name]);
+ if (gaps.length) lines.push(`这条样式只在${gaps.join('、')}下生效,工具触发不了。`);
+ if (!lines.length) lines.push('工具对这一项有拿不准的地方,看一下左右是不是一样。');
+ if (item.category === 'difference') lines.unshift('工具发现左右不一样。');
+ return lines.join('');
+};
diff --git a/packages/style-equivalence/src/report/properties.test.ts b/packages/style-equivalence/src/report/properties.test.ts
new file mode 100644
index 00000000000..6cd360f62ee
--- /dev/null
+++ b/packages/style-equivalence/src/report/properties.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import type { CaseSnapshot } from './api';
+import { propertyRows } from './properties';
+
+const target = (values: Record<string, string>) => ({
+ box: [],
+ key: 'root.0',
+ tag: 'SPAN',
+ values,
+});
+
+const snapshot: CaseSnapshot = {
+ base: {
+ target: target({
+ 'border-top-color': 'black',
+ 'color': 'rgb(0, 0, 0)',
+ 'cursor': 'auto',
+ 'width': '8px',
+ }),
+ targetKey: 'root.0',
+ },
+ differences: [
+ { after: 'rgb(255, 0, 0)', before: 'rgb(0, 0, 0)', key: 'root.0', property: 'color' },
+ { after: '2px', before: '1px', key: 'root.0.1', property: 'width' },
+ ],
+ head: {
+ target: target({
+ 'border-top-color': 'red',
+ 'color': 'rgb(255, 0, 0)',
+ 'cursor': 'auto',
+ 'width': '8px',
+ }),
+ targetKey: 'root.0',
+ },
+ ignored: [{ key: 'root.0', property: 'border-top-color', reason: 'nonpainting border color' }],
+};
+
+const declared = ['border-top-color', 'color', 'width'];
+
+describe('propertyRows', () => {
+ it("marks only the target element's differences and shows ignored ones with their reason", () => {
+ expect(propertyRows(snapshot, declared, 'declared')).toEqual([
+ {
+ base: 'black',
+ head: 'red',
+ mark: 'ignored',
+ name: 'border-top-color',
+ reason: 'nonpainting border color',
+ },
+ { base: 'rgb(0, 0, 0)', head: 'rgb(255, 0, 0)', mark: 'different', name: 'color' },
+ { base: '8px', head: '8px', mark: 'same', name: 'width' },
+ ]);
+ });
+
+ it('lists every computed property or only the differing ones', () => {
+ expect(propertyRows(snapshot, declared, 'all').map((row) => row.name)).toEqual([
+ 'border-top-color',
+ 'color',
+ 'cursor',
+ 'width',
+ ]);
+ expect(propertyRows(snapshot, declared, 'diff').map((row) => row.name)).toEqual(['color']);
+ });
+});
diff --git a/packages/style-equivalence/src/report/properties.ts b/packages/style-equivalence/src/report/properties.ts
new file mode 100644
index 00000000000..8cc93649fb2
--- /dev/null
+++ b/packages/style-equivalence/src/report/properties.ts
@@ -0,0 +1,45 @@
+import type { CaseSnapshot } from './api';
+
+export type PropertyMode = 'all' | 'declared' | 'diff';
+
+export interface PropertyRow {
+ base?: string;
+ head?: string;
+ mark: 'different' | 'ignored' | 'same';
+ name: string;
+ reason?: string;
+}
+
+export const propertyRows = (
+ snapshot: CaseSnapshot,
+ declared: string[],
+ mode: PropertyMode,
+): PropertyRow[] => {
+ const targetKey = snapshot.base.targetKey;
+ const differing = new Set(
+ snapshot.differences.filter((item) => item.key === targetKey).map((item) => item.property),
+ );
+ const ignored = new Map(
+ snapshot.ignored
+ .filter((item) => item.key === targetKey)
+ .map((item) => [item.property, item.reason]),
+ );
+ const baseValues = snapshot.base.target?.values ?? {};
+ const headValues = snapshot.head.target?.values ?? {};
+ const names =
+ mode === 'all'
+ ? [...new Set([...Object.keys(baseValues), ...Object.keys(headValues)])].sort()
+ : mode === 'diff'
+ ? [...differing].sort()
+ : declared.filter((name) => name in baseValues || name in headValues);
+ return names.map((name) => {
+ const reason = ignored.get(name);
+ return {
+ base: baseValues[name],
+ head: headValues[name],
+ mark: differing.has(name) ? 'different' : reason ? 'ignored' : 'same',
+ name,
+ ...(reason && !differing.has(name) ? { reason } : {}),
+ };
+ });
+};
diff --git a/packages/style-equivalence/src/report/report.css b/packages/style-equivalence/src/report/report.css
new file mode 100644
index 00000000000..980a5bde4e6
--- /dev/null
+++ b/packages/style-equivalence/src/report/report.css
@@ -0,0 +1,10 @@
+:root {
+ --lh-stylex: 1;
+}
+
+html,
+body,
+#root {
+ height: 100%;
+ margin: 0;
+}
diff --git a/packages/style-equivalence/src/report/review.test.ts b/packages/style-equivalence/src/report/review.test.ts
new file mode 100644
index 00000000000..a59ce02af86
--- /dev/null
+++ b/packages/style-equivalence/src/report/review.test.ts
@@ -0,0 +1,377 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ cellVerdict,
+ completionText,
+ conditionName,
+ defaultReworkNote,
+ describeConditions,
+ groupDifferences,
+ hasRenderedDifference,
+ hasScreenshots,
+ keyAction,
+ nextOpen,
+ nextSelection,
+ reviewGrid,
+ shotNotes,
+ standInNote,
+} from './review';
+
+const item = (key: string, state: string) => ({ key, state });
+
+describe('nextOpen', () => {
+ const items = [
+ item('a', 'passed'),
+ item('b', 'todo'),
+ item('c', 'reworked'),
+ item('d', 'waiting-agent'),
+ item('e', 'changed'),
+ ];
+
+ it('moves to the next item that still needs the reviewer', () => {
+ expect(nextOpen(items, 'b')).toBe('e');
+ });
+
+ it('wraps around and returns undefined when nothing is left', () => {
+ expect(nextOpen(items, 'e')).toBe('b');
+ expect(nextOpen([item('a', 'passed')], 'a')).toBeUndefined();
+ });
+
+ it('starts from the first open item without a current one', () => {
+ expect(nextOpen(items, undefined)).toBe('b');
+ });
+});
+
+describe('nextSelection', () => {
+ it('leaves nothing selected once every item is handled, so the completion state shows', () => {
+ expect(nextSelection([item('a', 'passed'), item('b', 'reworked')], 'b')).toBeUndefined();
+ expect(nextSelection([item('a', 'passed')], undefined)).toBeUndefined();
+ expect(nextSelection([item('a', 'passed'), item('b', 'todo')], 'a')).toBe('b');
+ });
+});
+
+describe('keyAction', () => {
+ it('maps J K Y N outside text inputs', () => {
+ expect(keyAction('j', false)).toBe('next');
+ expect(keyAction('k', false)).toBe('previous');
+ expect(keyAction('y', false)).toBe('pass');
+ expect(keyAction('n', false)).toBe('rework');
+ expect(keyAction('x', false)).toBeUndefined();
+ });
+
+ it('ignores every shortcut while the reviewer is typing', () => {
+ for (const key of ['j', 'k', 'y', 'n']) expect(keyAction(key, true)).toBeUndefined();
+ });
+
+ it('ignores every shortcut while a panel covers the queue', () => {
+ for (const key of ['j', 'k', 'y', 'n']) expect(keyAction(key, false, true)).toBeUndefined();
+ expect(keyAction('j', false, false)).toBe('next');
+ });
+});
+
+describe('reviewGrid', () => {
+ const conditions = [
+ 'light/375/default',
+ 'light/1280/default',
+ 'light/1280/hover-target',
+ 'dark/1280/default',
+ 'dark/375/default',
+ 'light/1280/default/rtl',
+ ];
+ const combos = [
+ { index: 0, label: 'online:否' },
+ { index: 1, label: 'online:是' },
+ ];
+
+ it('uses theme columns at the default width and combo rows', () => {
+ const grid = reviewGrid(combos, conditions, [
+ { combo: 1, condition: 'light/1280/default', summary: ['边框 无 → 1px solid'] },
+ ]);
+ expect(grid.columns.map((column) => [column.label, column.title])).toEqual([
+ ['light/1280/default', '亮色'],
+ ['dark/1280/default', '暗色'],
+ ]);
+ expect(grid.rows[1].cells[0]).toMatchObject({
+ differs: true,
+ summary: ['边框 无 → 1px solid'],
+ });
+ expect(grid.rows[0].cells[0].differs).toBe(false);
+ });
+
+ it('shows the interaction states of the light theme at the same width', () => {
+ const grid = reviewGrid(
+ combos,
+ [...conditions, 'light/1280/focus-visible', 'dark/1280/hover-target'],
+ [{ combo: 0, condition: 'light/1280/focus-visible', summary: ['描边 无 → 2px'] }],
+ );
+ expect(grid.states.columns.map((column) => [column.label, column.title])).toEqual([
+ ['light/1280/hover-target', '鼠标悬停'],
+ ['light/1280/focus-visible', '键盘聚焦'],
+ ]);
+ expect(grid.states.rows[0].cells[1]).toMatchObject({
+ differs: true,
+ summary: ['描边 无 → 2px'],
+ });
+ expect(grid.restDifferences).toEqual([]);
+ });
+
+ it('counts the other conditions and lists only the ones that differ', () => {
+ const grid = reviewGrid(combos, conditions, [
+ { combo: 0, condition: 'light/375/default', summary: ['间距 0px → 8px'] },
+ ]);
+ expect(grid.restCount).toBe(6);
+ expect(grid.restDifferences).toEqual([
+ {
+ combo: 0,
+ condition: 'light/375/default',
+ label: 'online:否',
+ summary: ['间距 0px → 8px'],
+ },
+ ]);
+ });
+
+ it('falls back to the widest width when 1280 is absent', () => {
+ const grid = reviewGrid(
+ [{ index: 0, label: '默认' }],
+ ['light/375/default', 'light/991/default'],
+ [],
+ );
+ expect(grid.columns.map((column) => column.label)).toEqual(['light/991/default']);
+ });
+});
+
+describe('completionText', () => {
+ const counts = (extra: object) => ({
+ 'changed': 0,
+ 'passed': 0,
+ 'reworked': 0,
+ 'todo': 0,
+ 'waiting-agent': 0,
+ ...extra,
+ });
+
+ it('says the PR can merge when nothing is left', () => {
+ expect(completionText(counts({ passed: 13 }), { mergeable: true, reasons: [] })).toEqual([
+ '全部看完了,可以合并。',
+ ]);
+ });
+
+ it('counts each send-back once and says who acts next', () => {
+ expect(
+ completionText(counts({ passed: 12, reworked: 1 }), {
+ mergeable: false,
+ reasons: ['needs sign-off 1', 'rework open 1'],
+ }),
+ ).toEqual(['全部看完了。', '1 项已打回,等 agent 改完会回到这里请你复看。']);
+ });
+
+ it('turns tool problems into plain sentences', () => {
+ expect(
+ completionText(counts({ passed: 3 }), {
+ mergeable: false,
+ reasons: ['mutation not fully caught', 'calibration mismatch 2'],
+ }),
+ ).toEqual([
+ '全部看完了。',
+ '工具自检没通过:注入的已知改动没有全部被发现。',
+ '工具自检没通过:2 处合成渲染和真实挂载不一致。',
+ ]);
+ });
+});
+
+describe('cellVerdict', () => {
+ const key = 'a.tsx|A#0';
+
+ it('says whether the two sides match', () => {
+ expect(cellVerdict(key, { differs: false, summary: [] })).toEqual({ text: '一致', tone: 'ok' });
+ expect(cellVerdict(key, { differs: true, summary: ['颜色 红 → 蓝'] })).toEqual({
+ text: '不一样:颜色 红 → 蓝',
+ tone: 'error',
+ });
+ });
+
+ it('names the only side of a one-sided element instead of claiming a match', () => {
+ expect(cellVerdict('a.tsx|unpaired:head:A#2', { differs: false, summary: [] })).toEqual({
+ text: '只有改之后,没有可对比的',
+ tone: 'neutral',
+ });
+ expect(cellVerdict('a.tsx|unpaired:base:A#2', { differs: false, summary: [] })).toEqual({
+ text: '只有改之前,改之后不见了',
+ tone: 'neutral',
+ });
+ });
+});
+
+describe('standInNote', () => {
+ it('says plainly that a screenshot shows a placeholder, naming the component', () => {
+ expect(standInNote(['Tabs', 'Select'])).toBe(
+ '替身:这里画的是占位块,不是真实组件(Tabs、Select)',
+ );
+ });
+
+ it('says nothing when the screenshot shows real elements', () => {
+ expect(standInNote(undefined)).toBeUndefined();
+ expect(standInNote([])).toBeUndefined();
+ });
+});
+
+describe('shotNotes', () => {
+ it('says the inner elements a descendant rule targets are not drawn', () => {
+ expect(
+ shotNotes(
+ { flags: ['INNER_TARGET', 'INNER_TARGET_PARTLY_FORWARDED:h1|A,B'], standIns: {} },
+ 'head',
+ ),
+ ).toEqual(['只画了容器本身:规则要命中的 h1 在组件内部,截图里没有']);
+ expect(shotNotes({ flags: ['INNER_TARGET'], standIns: {} }, 'base')).toEqual([
+ '只画了容器本身:规则要命中的内部元素在组件里,截图里没有',
+ ]);
+ });
+
+ it('combines a stand-in note with the inner-target note', () => {
+ expect(
+ shotNotes({ flags: ['INNER_TARGET'], standIns: { base: ['Tabs'] } }, 'base'),
+ ).toHaveLength(2);
+ expect(shotNotes({ flags: [], standIns: { base: ['Tabs'] } }, 'head')).toEqual([]);
+ });
+});
+
+describe('hasScreenshots', () => {
+ it('shows screenshots for an element but not for a whole-file item or a render failure', () => {
+ expect(hasScreenshots({ category: 'needs-signoff', key: 'a.tsx|A#0' })).toBe(true);
+ expect(hasScreenshots({ category: 'needs-signoff', key: 'a.tsx|file' })).toBe(false);
+ expect(hasScreenshots({ category: 'blocking', key: 'a.tsx|A#0' })).toBe(false);
+ });
+});
+
+describe('groupDifferences', () => {
+ const entry = (condition: string, summary: string, label = '默认') => ({
+ combo: 0,
+ condition,
+ label,
+ summary: [summary],
+ });
+
+ it('folds conditions that show the same difference into one group, in first-seen order', () => {
+ const groups = groupDifferences([
+ entry('light/375/default', '颜色 红 → 蓝'),
+ entry('dark/375/default', '颜色 黑 → 白'),
+ entry('light/575/default', '颜色 红 → 蓝'),
+ ]);
+ expect(
+ groups.map((group) => [group.summary, group.entries.map((item) => item.condition)]),
+ ).toEqual([
+ [['颜色 红 → 蓝'], ['light/375/default', 'light/575/default']],
+ [['颜色 黑 → 白'], ['dark/375/default']],
+ ]);
+ });
+
+ it('keeps different combos apart even when the difference reads the same', () => {
+ const groups = groupDifferences([
+ entry('light/375/default', '间距 0 → 8px', 'online:否'),
+ entry('light/375/default', '间距 0 → 8px', 'online:是'),
+ ]);
+ expect(groups).toHaveLength(2);
+ });
+});
+
+describe('describeConditions', () => {
+ it('merges widths that share the same states into one line per theme', () => {
+ const labels = ['light/375', 'light/575'].flatMap((prefix) =>
+ ['default', 'hover-target'].map((state) => `${prefix}/${state}`),
+ );
+ expect(describeConditions([...labels, 'dark/375/default'])).toEqual([
+ '亮色 · 375、575(默认、hover)',
+ '暗色 · 375(默认)',
+ ]);
+ });
+
+ it('lists widths with different states separately', () => {
+ expect(
+ describeConditions([
+ 'light/375/default',
+ 'light/375/hover-target',
+ 'light/575/default',
+ 'light/768/default',
+ 'light/768/hover-target',
+ ]),
+ ).toEqual(['亮色 · 375、768(默认、hover);575(默认)']);
+ });
+
+ it('names a single condition for a tag', () => {
+ expect(conditionName('dark/1280/focus-visible')).toBe('暗色 1280 focus');
+ expect(conditionName('light/1280/default/rtl')).toBe('亮色 1280 RTL');
+ });
+});
+
+describe('rework reason', () => {
+ const view = (overrides: object = {}) => ({
+ category: 'needs-signoff',
+ comboDifferences: [] as Array<{ combo: number; condition: string; summary: string[] }>,
+ combos: [{ index: 0, label: '默认' }],
+ differingConditions: [] as string[],
+ summary: [] as string[],
+ ...overrides,
+ });
+
+ it('needs no typed reason only when the item has a rendered difference', () => {
+ expect(hasRenderedDifference(view({ category: 'difference' }))).toBe(true);
+ expect(hasRenderedDifference(view({ differingConditions: ['light/375/default'] }))).toBe(true);
+ expect(hasRenderedDifference(view())).toBe(false);
+ expect(hasRenderedDifference(view({ category: 'unpaired' }))).toBe(false);
+ });
+
+ it('records a single difference the way the screenshots read', () => {
+ const summary = ['文字颜色 rgb(102, 102, 102) → rgb(176, 176, 176)'];
+ expect(
+ defaultReworkNote(
+ view({
+ category: 'difference',
+ comboDifferences: [{ combo: 0, condition: 'light/1280/default', summary }],
+ summary,
+ }),
+ ),
+ ).toBe('不一样:文字颜色 rgb(102, 102, 102) → rgb(176, 176, 176)(亮色 1280 默认)');
+ });
+
+ it('counts conditions per distinct difference', () => {
+ const light = ['文字颜色 红 → 蓝'];
+ const dark = ['文字颜色 黑 → 白'];
+ expect(
+ defaultReworkNote(
+ view({
+ category: 'difference',
+ comboDifferences: [
+ { combo: 0, condition: 'light/375/default', summary: light },
+ { combo: 0, condition: 'light/575/default', summary: light },
+ { combo: 0, condition: 'dark/375/default', summary: dark },
+ ],
+ }),
+ ),
+ ).toBe('不一样:文字颜色 红 → 蓝(2 个条件);文字颜色 黑 → 白(暗色 375 默认)');
+ });
+
+ it('names the combo when the element has several', () => {
+ expect(
+ defaultReworkNote(
+ view({
+ category: 'difference',
+ comboDifferences: [
+ { combo: 1, condition: 'light/1280/default', summary: ['边框 无 → 1px'] },
+ ],
+ combos: [
+ { index: 0, label: 'online:否' },
+ { index: 1, label: 'online:是' },
+ ],
+ }),
+ ),
+ ).toBe('不一样:online:是 · 边框 无 → 1px(亮色 1280 默认)');
+ });
+
+ it('falls back to the case summary and stays empty without a difference', () => {
+ expect(defaultReworkNote(view({ category: 'difference', summary: ['间距 0 → 8px'] }))).toBe(
+ '不一样:间距 0 → 8px',
+ );
+ expect(defaultReworkNote(view())).toBe('');
+ });
+});
diff --git a/packages/style-equivalence/src/report/review.ts b/packages/style-equivalence/src/report/review.ts
new file mode 100644
index 00000000000..6914baa6d5e
--- /dev/null
+++ b/packages/style-equivalence/src/report/review.ts
@@ -0,0 +1,222 @@
+import { conditionColumns } from './data';
+import { stateLabel, THEME_LABELS } from './labels';
+
+export const OPEN_STATES = new Set(['changed', 'todo']);
+
+export const nextOpen = (
+ items: Array<{ key: string; state: string }>,
+ current: string | undefined,
+) => {
+ const start = current ? items.findIndex((item) => item.key === current) : -1;
+ for (let step = 1; step <= items.length; step += 1) {
+ const candidate = items[(start + step + items.length) % items.length];
+ if (candidate && candidate.key !== current && OPEN_STATES.has(candidate.state))
+ return candidate.key;
+ }
+ return undefined;
+};
+
+export const nextSelection = (
+ items: Array<{ key: string; state: string }>,
+ current: string | undefined,
+): string | undefined => nextOpen(items, current);
+
+const KEYS: Record<string, 'next' | 'pass' | 'previous' | 'rework'> = {
+ j: 'next',
+ k: 'previous',
+ n: 'rework',
+ y: 'pass',
+};
+
+export const keyAction = (key: string, typing: boolean, covered = false) =>
+ typing || covered ? undefined : KEYS[key.toLowerCase()];
+
+export interface ComboDifference {
+ combo: number;
+ condition: string;
+ summary: string[];
+}
+
+const DEFAULT_WIDTH = 1280;
+
+const THEME_TITLES: Record<string, string> = { dark: '暗色', light: '亮色' };
+
+const STATE_TITLES: Array<[string, string]> = [
+ ['hover-target', '鼠标悬停'],
+ ['hover-chain', '悬停在外层'],
+ ['focus-visible', '键盘聚焦'],
+];
+
+export const reviewGrid = (
+ combos: Array<{ index: number; label: string }>,
+ conditions: string[],
+ differences: ComboDifference[],
+) => {
+ const all = conditionColumns(conditions).filter((column) => !column.variant);
+ const plain = all.filter((column) => column.state === 'default');
+ const widths = plain.map((column) => column.width);
+ const width = widths.includes(DEFAULT_WIDTH) ? DEFAULT_WIDTH : Math.max(...widths);
+ const columns = plain
+ .filter((column) => column.width === width)
+ .map((column) => ({ ...column, title: THEME_TITLES[column.theme] ?? column.theme }));
+ const stateColumns = STATE_TITLES.flatMap(([state, title]) =>
+ all
+ .filter(
+ (column) => column.theme === 'light' && column.width === width && column.state === state,
+ )
+ .map((column) => ({ ...column, title })),
+ );
+ const differenceOf = (combo: number, condition: string) =>
+ differences.find((entry) => entry.combo === combo && entry.condition === condition);
+ const rowsFor = (shownColumns: typeof columns) =>
+ combos.map((combo) => ({
+ ...combo,
+ cells: shownColumns.map((column) => {
+ const difference = differenceOf(combo.index, column.label);
+ return {
+ combo: combo.index,
+ condition: column.label,
+ differs: Boolean(difference),
+ summary: difference?.summary ?? [],
+ theme: column.theme,
+ };
+ }),
+ }));
+ const shown = new Set([...columns, ...stateColumns].map((column) => column.label));
+ const labels = new Map(combos.map((combo) => [combo.index, combo.label]));
+ return {
+ columns,
+ restCount: (new Set(conditions).size - shown.size) * combos.length,
+ restDifferences: differences
+ .filter((entry) => !shown.has(entry.condition))
+ .map((entry) => ({ ...entry, label: labels.get(entry.combo) ?? '默认' })),
+ rows: rowsFor(columns),
+ states: { columns: stateColumns, rows: rowsFor(stateColumns) },
+ };
+};
+
+const TOOL_REASONS: Array<[RegExp, (count: string) => string]> = [
+ [/^mutation not fully caught$/, () => '工具自检没通过:注入的已知改动没有全部被发现。'],
+ [
+ /^calibration mismatch (\d+)$/,
+ (count) => `工具自检没通过:${count} 处合成渲染和真实挂载不一致。`,
+ ],
+];
+
+export const cellVerdict = (key: string, cell: { differs: boolean; summary: string[] }) => {
+ const side = /\|unpaired:(base|head):/.exec(key)?.[1];
+ if (side === 'head') return { text: '只有改之后,没有可对比的', tone: 'neutral' as const };
+ if (side === 'base') return { text: '只有改之前,改之后不见了', tone: 'neutral' as const };
+ return cell.differs
+ ? { text: `不一样:${cell.summary.join(';')}`, tone: 'error' as const }
+ : { text: '一致', tone: 'ok' as const };
+};
+
+export const completionText = (
+ counts: Record<string, number>,
+ verdict: { mergeable: boolean; reasons: string[] },
+) => {
+ if (verdict.mergeable) return ['全部看完了,可以合并。'];
+ const lines = ['全部看完了。'];
+ if (counts.reworked) lines.push(`${counts.reworked} 项已打回,等 agent 改完会回到这里请你复看。`);
+ if (counts.changed) lines.push(`${counts.changed} 项已修改,在左侧队列里复看。`);
+ if (counts['waiting-agent']) lines.push(`${counts['waiting-agent']} 项等 agent 读完代码。`);
+ for (const reason of verdict.reasons)
+ for (const [pattern, text] of TOOL_REASONS) {
+ const match = pattern.exec(reason);
+ if (match) lines.push(text(match[1] ?? ''));
+ }
+ return lines;
+};
+
+export const standInNote = (tags: string[] | undefined) =>
+ tags?.length ? `替身:这里画的是占位块,不是真实组件(${tags.join('、')})` : undefined;
+
+export const shotNotes = (
+ item: { flags: string[]; standIns?: Partial<Record<'base' | 'head', string[]>> },
+ side: 'base' | 'head',
+) => {
+ const notes: string[] = [];
+ const standIn = standInNote(item.standIns?.[side]);
+ if (standIn) notes.push(standIn);
+ if (item.flags.includes('INNER_TARGET')) {
+ const partly = item.flags.find((flag) => flag.startsWith('INNER_TARGET_PARTLY_FORWARDED:'));
+ const tag = partly?.slice(partly.indexOf(':') + 1).split('|')[0];
+ notes.push(
+ `只画了容器本身:规则要命中的${tag ? ` ${tag} ` : '内部元素'}在组件${tag ? '内部' : '里'},截图里没有`,
+ );
+ }
+ return notes;
+};
+
+export const hasScreenshots = (item: { category: string; key: string }) =>
+ item.category !== 'blocking' && !item.key.endsWith('|file');
+
+export const groupDifferences = <T extends { label: string; summary: string[] }>(entries: T[]) => {
+ const groups = new Map<string, { entries: T[]; key: string; label: string; summary: string[] }>();
+ for (const entry of entries) {
+ const key = `${entry.label}\n${entry.summary.join(';')}`;
+ const group = groups.get(key);
+ if (group) group.entries.push(entry);
+ else groups.set(key, { entries: [entry], key, label: entry.label, summary: entry.summary });
+ }
+ return [...groups.values()];
+};
+
+const themeName = (theme: string) => THEME_LABELS[theme] ?? theme;
+
+export const conditionName = (label: string) => {
+ const [column] = conditionColumns([label]);
+ return `${themeName(column.theme)} ${column.width} ${stateLabel(column.state, column.variant)}`;
+};
+
+export const describeConditions = (labels: string[]) => {
+ const columns = conditionColumns(labels);
+ return [...new Set(columns.map((column) => column.theme))].map((theme) => {
+ const own = columns.filter((column) => column.theme === theme);
+ const byStates = new Map<string, number[]>();
+ for (const width of new Set(own.map((column) => column.width))) {
+ const states = own
+ .filter((column) => column.width === width)
+ .map((column) => stateLabel(column.state, column.variant))
+ .join('、');
+ byStates.set(states, [...(byStates.get(states) ?? []), width]);
+ }
+ const parts = [...byStates].map(([states, widths]) => `${widths.join('、')}(${states})`);
+ return `${themeName(theme)} · ${parts.join(';')}`;
+ });
+};
+
+interface DifferenceView {
+ category: string;
+ comboDifferences: ComboDifference[];
+ combos: Array<{ index: number; label: string }>;
+ differingConditions: string[];
+ summary: string[];
+}
+
+export const hasRenderedDifference = (item: DifferenceView) =>
+ item.category === 'difference' ||
+ item.differingConditions.length > 0 ||
+ item.comboDifferences.length > 0;
+
+const MAX_NOTE_GROUPS = 3;
+
+export const defaultReworkNote = (item: DifferenceView) => {
+ if (!hasRenderedDifference(item)) return '';
+ const labels = new Map(item.combos.map((combo) => [combo.index, combo.label]));
+ const named = item.combos.length > 1;
+ const groups = groupDifferences(
+ item.comboDifferences.map((entry) => ({ ...entry, label: labels.get(entry.combo) ?? '默认' })),
+ );
+ if (!groups.length) return item.summary.length ? `不一样:${item.summary.join(';')}` : '';
+ const parts = groups.slice(0, MAX_NOTE_GROUPS).map((group) => {
+ const where =
+ group.entries.length === 1
+ ? conditionName(group.entries[0].condition)
+ : `${group.entries.length} 个条件`;
+ return `${named ? `${group.label} · ` : ''}${group.summary.join(';')}(${where})`;
+ });
+ const rest = groups.length - parts.length;
+ return `不一样:${parts.join(';')}${rest > 0 ? `;另有 ${rest} 种差异` : ''}`;
+};
diff --git a/packages/style-equivalence/src/report/route.test.ts b/packages/style-equivalence/src/report/route.test.ts
new file mode 100644
index 00000000000..b710d42ae9d
--- /dev/null
+++ b/packages/style-equivalence/src/report/route.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { hrefOf, parseRoute } from './route';
+
+describe('route', () => {
+ it('keeps the anchor of a method page link', () => {
+ expect(parseRoute('#/method#CROSS_COMPONENT')).toEqual({
+ anchor: 'CROSS_COMPONENT',
+ kind: 'method',
+ });
+ expect(parseRoute('#/method')).toEqual({ kind: 'method' });
+ expect(hrefOf({ anchor: 'border', kind: 'method' })).toBe('#/method#border');
+ });
+
+ it('opens one review item by its key', () => {
+ const key = 'src/A.tsx|A#0';
+ expect(hrefOf({ key, kind: 'review' })).toBe(`#/review/${encodeURIComponent(key)}`);
+ expect(parseRoute(hrefOf({ key, kind: 'review' }))).toEqual({ key, kind: 'review' });
+ expect(parseRoute('#/review')).toEqual({ kind: 'review' });
+ });
+});
diff --git a/packages/style-equivalence/src/report/route.ts b/packages/style-equivalence/src/report/route.ts
new file mode 100644
index 00000000000..9d5733354a2
--- /dev/null
+++ b/packages/style-equivalence/src/report/route.ts
@@ -0,0 +1,36 @@
+import { useSyncExternalStore } from 'react';
+
+export type Route =
+ | { kind: 'case'; key: string }
+ | { kind: 'file'; file: string }
+ | { anchor?: string; kind: 'method' }
+ | { kind: 'overview' }
+ | { key?: string; kind: 'review' };
+
+export const parseRoute = (hash: string): Route => {
+ const [path, anchor] = hash.replace(/^#/, '').split('#');
+ const [, kind, ...rest] = path.split('/');
+ const value = decodeURIComponent(rest.join('/'));
+ if (kind === 'file' && value) return { file: value, kind: 'file' };
+ if (kind === 'case' && value) return { key: value, kind: 'case' };
+ if (kind === 'method') return anchor ? { anchor, kind: 'method' } : { kind: 'method' };
+ if (kind === 'review' && value) return { key: value, kind: 'review' };
+ if (kind === 'review' || kind === 'signoff') return { kind: 'review' };
+ return { kind: 'overview' };
+};
+
+export const hrefOf = (route: Route) => {
+ if (route.kind === 'file') return `#/file/${encodeURIComponent(route.file)}`;
+ if (route.kind === 'case') return `#/case/${encodeURIComponent(route.key)}`;
+ if (route.kind === 'review' && route.key) return `#/review/${encodeURIComponent(route.key)}`;
+ if (route.kind === 'overview') return '#/';
+ if (route.kind === 'method' && route.anchor) return `#/method#${route.anchor}`;
+ return `#/${route.kind}`;
+};
+
+const subscribe = (listener: () => void) => {
+ window.addEventListener('hashchange', listener);
+ return () => window.removeEventListener('hashchange', listener);
+};
+
+export const useRoute = () => parseRoute(useSyncExternalStore(subscribe, () => location.hash));
diff --git a/packages/style-equivalence/src/report/ui/App.tsx b/packages/style-equivalence/src/report/ui/App.tsx
new file mode 100644
index 00000000000..ecc63806ef9
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/App.tsx
@@ -0,0 +1,127 @@
+import { Flexbox, ScrollArea, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useCallback, useEffect, useState } from 'react';
+
+import { fetchRun, type RunPayload } from '../api';
+import { useRoute } from '../route';
+import { CaseView } from './CaseView';
+import { FileTree } from './FileTree';
+import { FileView } from './FileView';
+import { MethodPage } from './MethodPage';
+import { OverviewMatrix } from './OverviewMatrix';
+import { PageState } from './PageState';
+import { ReviewPage } from './ReviewPage';
+import { useFollowRun } from './RunBadge';
+import { TopBar, VerdictStrip } from './TopBar';
+
+const styles = stylex.create({
+ app: {
+ backgroundColor: cssVar.colorBgLayout,
+ color: cssVar.colorText,
+ display: 'flex',
+ flexDirection: 'column',
+ fontVariantNumeric: 'tabular-nums',
+ height: '100vh',
+ },
+ layout: { display: 'grid', flex: '1', gridTemplateColumns: '288px minmax(0, 1fr)', minHeight: 0 },
+ main: { minWidth: 0, overflowY: 'auto', paddingBlock: 24, paddingInline: 32 },
+ side: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ borderInlineEndStyle: 'solid',
+ borderInlineEndWidth: 1,
+ height: '100%',
+ minHeight: 0,
+ },
+ title: { fontSize: cssVar.fontSizeLG, fontWeight: 600, marginBlock: 0 },
+});
+
+export const App = () => {
+ const route = useRoute();
+ if (route.kind === 'review') return <ReviewPage initialKey={route.key} />;
+ return <ReportApp route={route} />;
+};
+
+const ReportApp = ({
+ route,
+}: {
+ route: Exclude<ReturnType<typeof useRoute>, { kind: 'review' }>;
+}) => {
+ const [payload, setPayload] = useState<RunPayload>();
+ const [error, setError] = useState<string>();
+ const load = useCallback(() => {
+ fetchRun()
+ .then(setPayload)
+ .catch((reason: unknown) => setError(String(reason)));
+ }, []);
+ useEffect(load, [load]);
+ useFollowRun(payload?.follow, load);
+ if (!payload)
+ return (
+ <PageState
+ error={error}
+ loading="正在读取运行结果…"
+ title="读取运行结果失败"
+ onRetry={() => {
+ setError(undefined);
+ load();
+ }}
+ />
+ );
+ const conditions = payload.run.conditions ?? [];
+ const unpaired = payload.verdict.items.filter((item) => item.category === 'unpaired');
+ return (
+ <div {...stylex.props(styles.app)}>
+ <TopBar
+ base={payload.run.base}
+ follow={payload.follow}
+ head={payload.run.head}
+ section={route.kind === 'method' ? 'method' : 'overview'}
+ />
+ <VerdictStrip payload={payload} />
+ <div key={payload.run.runId} {...stylex.props(styles.layout)}>
+ <aside aria-label="文件" {...stylex.props(styles.side)}>
+ <ScrollArea disableContentFit style={{ height: '100%' }}>
+ <FileTree
+ atOverview={route.kind === 'overview'}
+ cases={payload.cases}
+ unpaired={unpaired}
+ selected={
+ route.kind === 'file'
+ ? route.file
+ : route.kind === 'case'
+ ? route.key.slice(0, route.key.indexOf('|'))
+ : undefined
+ }
+ />
+ </ScrollArea>
+ </aside>
+ <main {...stylex.props(styles.main)}>
+ {route.kind === 'method' ? (
+ <MethodPage anchor={route.anchor} payload={payload} />
+ ) : route.kind === 'case' ? (
+ <CaseView caseKey={route.key} payload={payload} />
+ ) : route.kind === 'file' ? (
+ <FileView
+ cases={payload.cases}
+ conditions={conditions}
+ file={route.file}
+ items={payload.verdict.items}
+ />
+ ) : (
+ <Flexbox gap={16}>
+ <Flexbox gap={4}>
+ <h1 {...stylex.props(styles.title)}>全部文件</h1>
+ <Text type="secondary">
+ 每格是一个文件在这个条件下的结果,数字是有差异的用例数。点文件名进入文件视图。
+ </Text>
+ </Flexbox>
+ <OverviewMatrix cases={payload.cases} conditions={conditions} />
+ </Flexbox>
+ )}
+ </main>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/CaseDebug.tsx b/packages/style-equivalence/src/report/ui/CaseDebug.tsx
new file mode 100644
index 00000000000..fd6a13c2195
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/CaseDebug.tsx
@@ -0,0 +1,78 @@
+import { Accordion, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { useEffect, useState } from 'react';
+
+import { type CaseDetail, fetchCase, type RunPayload } from '../api';
+import { conditionColumns } from '../data';
+import { declaredProperties } from '../declared';
+import { flagLabel } from '../labels';
+import { EvidenceChain } from './EvidenceChain';
+import { LiveCompare } from './LiveCompare';
+import { InlineState } from './PageState';
+
+const styles = stylex.create({
+ body: {
+ columnGap: 24,
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)',
+ paddingBlockStart: 8,
+ },
+});
+
+const DebugBody = ({ caseKey, payload }: { caseKey: string; payload: RunPayload }) => {
+ const [loaded, setLoaded] = useState<{ detail?: CaseDetail; error?: string; key: string }>();
+ useEffect(() => {
+ let current = true;
+ fetchCase(caseKey)
+ .then((detail) => current && setLoaded({ detail, key: caseKey }))
+ .catch((reason: unknown) => current && setLoaded({ error: String(reason), key: caseKey }));
+ return () => {
+ current = false;
+ };
+ }, [caseKey]);
+ const detail = loaded?.key === caseKey ? loaded.detail : undefined;
+ const error = loaded?.key === caseKey ? loaded.error : undefined;
+ if (!detail)
+ return <InlineState error={error && `读取用例失败:${error}`} loading="正在读取用例…" />;
+ const columns = conditionColumns(payload.run.conditions ?? []);
+ const record = detail.case;
+ const category = record?.category ?? detail.item?.category ?? 'unpaired';
+ const declared = declaredProperties([
+ ...Object.values(detail.evidence?.declarations.base ?? {}),
+ ...Object.values(detail.evidence?.declarations.head ?? {}),
+ ]);
+ return (
+ <div {...stylex.props(styles.body)}>
+ <EvidenceChain columns={columns} detail={detail} />
+ {record ? (
+ <LiveCompare
+ base={payload.run.base}
+ caseKey={caseKey}
+ columns={columns}
+ combos={record.plan.combos.length}
+ declared={declared}
+ head={payload.run.head}
+ />
+ ) : (
+ <Text type="secondary">
+ {category === 'unpaired'
+ ? '这个元素两侧配不上,没有可以对照的渲染。'
+ : `这个文件有合成环境比较不了的样式用法:${(detail.item?.flags ?? []).map(flagLabel).join('、')}。`}
+ </Text>
+ )}
+ </div>
+ );
+};
+
+export const CaseDebug = ({ caseKey, payload }: { caseKey: string; payload: RunPayload }) => (
+ <Accordion
+ variant="outlined"
+ items={[
+ {
+ children: <DebugBody caseKey={caseKey} payload={payload} />,
+ key: 'debug',
+ title: '调试信息',
+ },
+ ]}
+ />
+);
diff --git a/packages/style-equivalence/src/report/ui/CaseView.tsx b/packages/style-equivalence/src/report/ui/CaseView.tsx
new file mode 100644
index 00000000000..9d156b42acf
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/CaseView.tsx
@@ -0,0 +1,83 @@
+import { Button, Flexbox } from '@lobehub/ui';
+import { ArrowLeft, ArrowRight } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import { type CaseReview, fetchCaseReview, type ReviewState, type RunPayload } from '../api';
+import { hrefOf } from '../route';
+import { CaseDebug } from './CaseDebug';
+import { Chip, type ChipTone } from './Chip';
+import { InlineState } from './PageState';
+import { ReviewEvidence } from './ReviewEvidence';
+import { ItemHeader, ReworkNote } from './ReviewItemView';
+
+const STATES: Record<ReviewState, { label: string; tone: ChipTone }> = {
+ 'changed': { label: '改过了,待重看', tone: 'warn' },
+ 'passed': { label: '已通过', tone: 'ok' },
+ 'reworked': { label: '已打回', tone: 'bad' },
+ 'todo': { label: '待看', tone: 'warn' },
+ 'waiting-agent': { label: '等 agent', tone: 'plain' },
+};
+
+const stateChip = ({ item, queued }: CaseReview) =>
+ queued ? STATES[item.state] : { label: '工具已证明,不用人工看', tone: 'ok' as const };
+
+const useCaseReview = (caseKey: string) => {
+ const [loaded, setLoaded] = useState<{ error?: string; key: string; review?: CaseReview }>();
+ useEffect(() => {
+ let current = true;
+ fetchCaseReview(caseKey)
+ .then((review) => current && setLoaded({ key: caseKey, review }))
+ .catch((reason: unknown) => current && setLoaded({ error: String(reason), key: caseKey }));
+ return () => {
+ current = false;
+ };
+ }, [caseKey]);
+ return loaded?.key === caseKey ? loaded : undefined;
+};
+
+export const CaseView = ({ caseKey, payload }: { caseKey: string; payload: RunPayload }) => {
+ const loaded = useCaseReview(caseKey);
+ const review = loaded?.review;
+ const file = review?.item.file ?? caseKey.slice(0, caseKey.indexOf('|'));
+ const state = review && stateChip(review);
+ return (
+ <Flexbox gap={24} style={{ maxWidth: 1440 }}>
+ <Flexbox gap={12}>
+ <Flexbox horizontal>
+ <Button href={hrefOf({ file, kind: 'file' })} icon={ArrowLeft} size="small" type="text">
+ {file}
+ </Button>
+ </Flexbox>
+ {!review && (
+ <InlineState
+ error={loaded?.error && `读取用例失败:${loaded.error}`}
+ loading="正在读取用例…"
+ />
+ )}
+ {review && state && (
+ <ItemHeader
+ extra={<Chip tone={state.tone}>{state.label}</Chip>}
+ item={review.item}
+ action={
+ review.queued && (
+ <Button
+ href={hrefOf({ key: caseKey, kind: 'review' })}
+ icon={ArrowRight}
+ iconPosition="end"
+ size="small"
+ >
+ 在复查里打开
+ </Button>
+ )
+ }
+ />
+ )}
+ {review?.item.rework && <ReworkNote note={review.item.rework.note} />}
+ </Flexbox>
+ {review && (
+ <ReviewEvidence conditions={review.conditions} item={review.item} notes="written" />
+ )}
+ <CaseDebug caseKey={caseKey} payload={payload} />
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/Chip.tsx b/packages/style-equivalence/src/report/ui/Chip.tsx
new file mode 100644
index 00000000000..f4c1dd1a58c
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/Chip.tsx
@@ -0,0 +1,34 @@
+import { Tag } from '@lobehub/ui';
+import type { ReactNode } from 'react';
+
+const TONE_COLORS = {
+ bad: 'error',
+ info: 'info',
+ ok: 'success',
+ plain: undefined,
+ warn: 'warning',
+} as const;
+
+export type ChipTone = keyof typeof TONE_COLORS;
+
+export const Chip = ({
+ children,
+ title,
+ tone,
+}: {
+ children: ReactNode;
+ title?: string;
+ tone: ChipTone;
+}) => (
+ <Tag color={TONE_COLORS[tone]} size="small" title={title}>
+ {children}
+ </Tag>
+);
+
+export const CATEGORY_TONES: Record<string, ChipTone> = {
+ 'blocking': 'plain',
+ 'difference': 'bad',
+ 'equal': 'ok',
+ 'needs-signoff': 'warn',
+ 'unpaired': 'warn',
+};
diff --git a/packages/style-equivalence/src/report/ui/EvidenceChain.tsx b/packages/style-equivalence/src/report/ui/EvidenceChain.tsx
new file mode 100644
index 00000000000..2a03637e093
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/EvidenceChain.tsx
@@ -0,0 +1,218 @@
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import type { ReactNode } from 'react';
+
+import type { CaseDetail } from '../api';
+import { type ConditionColumn } from '../data';
+import { shorthandsIn } from '../declared';
+import { flagLabel } from '../labels';
+import { hrefOf } from '../route';
+import { MatrixStrip } from './MatrixStrip';
+
+const styles = stylex.create({
+ code: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ color: cssVar.colorText,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ lineHeight: 1.6,
+ marginBlock: 0,
+ overflowX: 'auto',
+ paddingBlock: 8,
+ paddingInline: 12,
+ whiteSpace: 'pre',
+ },
+ heading: { fontSize: cssVar.fontSize, fontWeight: 600, marginBlockEnd: 8, marginBlockStart: 0 },
+ label: { color: cssVar.colorTextTertiary, fontSize: cssVar.fontSizeSM, marginBlockEnd: 4 },
+ list: {
+ display: 'flex',
+ flexDirection: 'column',
+ marginBlock: 0,
+ paddingInlineStart: 18,
+ rowGap: 4,
+ },
+ note: { color: cssVar.colorTextSecondary, fontSize: cssVar.fontSizeSM, lineHeight: 1.7 },
+ number: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorFillSecondary,
+ borderRadius: '50%',
+ color: cssVar.colorText,
+ display: 'flex',
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 600,
+ height: 20,
+ justifyContent: 'center',
+ width: 20,
+ },
+ step: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ columnGap: 12,
+ display: 'grid',
+ gridTemplateColumns: '20px minmax(0, 1fr)',
+ paddingBlock: 16,
+ },
+ strip: { overflowX: 'auto', paddingBlockEnd: 4 },
+ two: { columnGap: 12, display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))' },
+});
+
+const CORPUS_FOR: Record<string, string> = { background: 'background-reset', border: 'border' };
+
+const Step = ({
+ children,
+ index,
+ title,
+}: {
+ children: ReactNode;
+ index: number;
+ title: string;
+}) => (
+ <div {...stylex.props(styles.step)}>
+ <div {...stylex.props(styles.number)}>{index}</div>
+ <div>
+ <h3 {...stylex.props(styles.heading)}>{title}</h3>
+ {children}
+ </div>
+ </div>
+);
+
+const Declarations = ({ texts }: { texts?: Record<string, string> }) =>
+ texts && Object.keys(texts).length ? (
+ <pre {...stylex.props(styles.code)}>{Object.values(texts).join('\n\n')}</pre>
+ ) : (
+ <div {...stylex.props(styles.note)}>这一侧没有这个元素。</div>
+ );
+
+const chainText = (elements?: Array<{ tag: string }>) =>
+ elements?.map((element) => `<${element.tag}>`).join(' › ') ?? '--';
+
+export const EvidenceChain = ({
+ columns,
+ detail,
+}: {
+ columns: ConditionColumn[];
+ detail: CaseDetail;
+}) => {
+ const record = detail.case;
+ const evidence = detail.evidence;
+ const flags = [...(record?.plan.flags ?? []), ...(record?.result.gaps ?? [])];
+ const slots = new Set([
+ ...(evidence?.elements.base ?? []).flatMap((element) => element.slots),
+ ...(evidence?.elements.head ?? []).flatMap((element) => element.slots),
+ ]);
+ const rules = (['base', 'head'] as const).flatMap((side) =>
+ (detail.extraction?.[side]?.rules ?? [])
+ .filter((rule) => rule.slot && slots.has(rule.slot))
+ .map((rule) => ({ ...rule, side })),
+ );
+ const baseText = Object.values(evidence?.declarations.base ?? {}).join('\n');
+ const headText = Object.values(evidence?.declarations.head ?? {}).join('\n');
+ const shorthands = shorthandsIn(baseText).filter(
+ (name) => !shorthandsIn(headText).includes(name),
+ );
+ const total = columns.length * Math.max(record?.plan.combos.length ?? 1, 1);
+ return (
+ <div>
+ <Step index={1} title="源码里声明了什么">
+ <div {...stylex.props(styles.two)}>
+ <div>
+ <div {...stylex.props(styles.label)}>base</div>
+ <Declarations texts={evidence?.declarations.base} />
+ </div>
+ <div>
+ <div {...stylex.props(styles.label)}>head</div>
+ <Declarations texts={evidence?.declarations.head} />
+ </div>
+ </div>
+ </Step>
+ <Step index={2} title="真正生效的规则">
+ <div {...stylex.props(styles.note)}>
+ {shorthands.length === 0 &&
+ rules.length === 0 &&
+ '两侧都只有元素自身的声明,没有嵌套选择器。'}
+ {shorthands.map((name) => (
+ <p key={name}>
+ base 用了 shorthand <code>{name}</code>,它会把没写到的子属性重置为初始值;head 拆成了
+ longhand。 只要这些子属性在这个元素上本来就是初始值,就不会产生差异
+ {CORPUS_FOR[name] && (
+ <>
+ ,别的规则设置了它们时的情况由边界语料{' '}
+ <a href={hrefOf({ anchor: CORPUS_FOR[name], kind: 'method' })}>
+ {CORPUS_FOR[name]}
+ </a>{' '}
+ 覆盖
+ </>
+ )}
+ 。
+ </p>
+ ))}
+ {rules.length > 0 && (
+ <ul {...stylex.props(styles.list)}>
+ {rules.map((rule) => (
+ <li key={`${rule.side}${rule.selector}${rule.conditions.join()}`}>
+ {rule.side}:<code>{rule.selector}</code>
+ {rule.conditions.length ? ` · ${rule.conditions.join(' · ')}` : ''}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </Step>
+ <Step index={3} title="在什么 DOM 上比较">
+ <div {...stylex.props(styles.note)}>
+ base:<code>{chainText(evidence?.elements.base)}</code>;head:
+ <code>{chainText(evidence?.elements.head)}</code>。
+ {record?.plan.variables.length
+ ? ` 条件变量 ${record.plan.variables.map((variable) => variable.name).join('、')},共 ${record.plan.combos.length} 种组合。`
+ : ' 没有条件变量。'}
+ {flags.length > 0 && (
+ <ul {...stylex.props(styles.list)}>
+ {flags.map((flag) => (
+ <li key={flag}>
+ <a href={hrefOf({ anchor: flag, kind: 'method' })}>{flagLabel(flag)}</a>({flag}
+ ):这一点合成环境证明不了,需要人工确认。
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </Step>
+ <Step index={4} title="在哪些条件下比较">
+ {record && (
+ <div {...stylex.props(styles.strip)}>
+ <MatrixStrip large columns={columns} entry={record} />
+ </div>
+ )}
+ <div {...stylex.props(styles.note)}>
+ 每行一个主题,每列一个宽度和状态的组合。base 加载两次自比(A/A):
+ {record?.result.unstableConditions.length
+ ? `${record.result.unstableConditions.length} 个条件不稳定,这个用例阻塞。`
+ : `${columns.length} / ${columns.length} 稳定。`}
+ </div>
+ </Step>
+ <Step index={5} title="比较的结果">
+ <div {...stylex.props(styles.note)}>
+ {total} 个条件 × 组合里,{record?.result.differingConditions.length ?? 0} 个条件出现差异。
+ {record?.result.rootCauses.length ? (
+ <ul {...stylex.props(styles.list)}>
+ {record.result.rootCauses.map((cause) => (
+ <li key={`${cause.key}${cause.property}${cause.before}`}>
+ <code>{cause.key}</code> {cause.property}:{cause.before ?? '∅'} →{' '}
+ {cause.after ?? '∅'}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ ' 所有计算属性和盒子尺寸逐项一致。'
+ )}
+ 右侧可以按条件逐项对照。
+ </div>
+ </Step>
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/FileTree.tsx b/packages/style-equivalence/src/report/ui/FileTree.tsx
new file mode 100644
index 00000000000..e46abae7613
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/FileTree.tsx
@@ -0,0 +1,108 @@
+import { Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import { buildTree, type FileStatus, type ReportCase, type UnpairedEntry } from '../data';
+import { CATEGORY_LABELS } from '../labels';
+import { hrefOf } from '../route';
+
+const styles = stylex.create({
+ directory: {
+ color: cssVar.colorTextTertiary,
+ fontSize: cssVar.fontSizeSM,
+ paddingBlockEnd: 4,
+ paddingBlockStart: 12,
+ paddingInline: 12,
+ wordBreak: 'break-all',
+ },
+ dot: { borderRadius: '50%', flex: 'none', height: 8, width: 8 },
+ file: {
+ alignItems: 'center',
+ backgroundColor: { ':hover': cssVar.colorFillTertiary, 'default': 'transparent' },
+ borderRadius: cssVar.borderRadius,
+ color: cssVar.colorTextSecondary,
+ columnGap: 8,
+ display: 'grid',
+ fontSize: cssVar.fontSize,
+ gridTemplateColumns: '8px minmax(0, 1fr) auto',
+ paddingBlock: 6,
+ paddingInline: 12,
+ textDecorationLine: 'none',
+ },
+ name: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+ root: {
+ backgroundColor: { ':hover': cssVar.colorFillTertiary, 'default': 'transparent' },
+ borderRadius: cssVar.borderRadius,
+ color: cssVar.colorText,
+ display: 'block',
+ fontSize: cssVar.fontSize,
+ fontWeight: 500,
+ paddingBlock: 6,
+ paddingInline: 12,
+ textDecorationLine: 'none',
+ },
+ selected: {
+ backgroundColor: { ':hover': cssVar.colorFillSecondary, 'default': cssVar.colorFillSecondary },
+ color: cssVar.colorText,
+ fontWeight: 500,
+ },
+ tree: { padding: 8 },
+});
+
+const dots = stylex.create({
+ 'blocking': { backgroundColor: cssVar.colorTextQuaternary },
+ 'difference': { backgroundColor: cssVar.colorError },
+ 'equal': { backgroundColor: cssVar.colorSuccess },
+ 'needs-signoff': { backgroundColor: cssVar.colorWarning },
+});
+
+export const StatusDot = ({ status }: { status: FileStatus }) => (
+ <span
+ aria-label={CATEGORY_LABELS[status]}
+ role="img"
+ {...stylex.props(styles.dot, dots[status])}
+ />
+);
+
+export const FileTree = ({
+ atOverview,
+ cases,
+ selected,
+ unpaired,
+}: {
+ atOverview: boolean;
+ cases: ReportCase[];
+ selected: string | undefined;
+ unpaired: UnpairedEntry[];
+}) => (
+ <nav {...stylex.props(styles.tree)}>
+ <a
+ aria-current={atOverview ? 'page' : undefined}
+ href={hrefOf({ kind: 'overview' })}
+ {...stylex.props(styles.root, atOverview && styles.selected)}
+ >
+ 全部文件
+ </a>
+ {buildTree(cases, unpaired).map(({ directory, files }) => (
+ <div key={directory}>
+ <div {...stylex.props(styles.directory)}>{directory || '.'}</div>
+ {files.map((file) => (
+ <a
+ aria-current={selected === file.file ? 'page' : undefined}
+ data-status={file.status}
+ href={hrefOf({ file: file.file, kind: 'file' })}
+ key={file.file}
+ title={file.file}
+ {...stylex.props(styles.file, selected === file.file && styles.selected)}
+ >
+ <StatusDot status={file.status} />
+ <span {...stylex.props(styles.name)}>{file.name}</span>
+ <Text fontSize={12} type="secondary">
+ {file.open ? `${file.open} / ${file.total}` : file.total}
+ </Text>
+ </a>
+ ))}
+ </div>
+ ))}
+ </nav>
+);
diff --git a/packages/style-equivalence/src/report/ui/FileView.tsx b/packages/style-equivalence/src/report/ui/FileView.tsx
new file mode 100644
index 00000000000..b0f184d6cae
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/FileView.tsx
@@ -0,0 +1,120 @@
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import type { VerdictEntry } from '../api';
+import { conditionColumns, type ReportCase } from '../data';
+import { CATEGORY_LABELS, flagLabel, shortKey } from '../labels';
+import { hrefOf } from '../route';
+import { CATEGORY_TONES, Chip } from './Chip';
+import { MatrixStrip } from './MatrixStrip';
+
+const styles = stylex.create({
+ cause: {
+ color: cssVar.colorTextSecondary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ chips: { columnGap: 4, display: 'flex', flexWrap: 'wrap', rowGap: 4 },
+ heading: {
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ marginBlock: 0,
+ wordBreak: 'break-all',
+ },
+ key: { color: cssVar.colorText, fontFamily: cssVar.fontFamilyCode, fontSize: cssVar.fontSizeSM },
+ row: {
+ alignItems: 'center',
+ backgroundColor: { ':hover': cssVar.colorFillQuaternary, 'default': 'transparent' },
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: { ':first-child': 'none', 'default': 'solid' },
+ borderBlockStartWidth: 1,
+ color: 'inherit',
+ columnGap: 12,
+ display: 'grid',
+ gridTemplateColumns: '180px auto minmax(0, 1fr) minmax(0, 1.2fr)',
+ paddingBlock: 12,
+ paddingInline: 16,
+ textDecorationLine: 'none',
+ },
+});
+
+const SIGNOFF_LABELS: Record<string, string> = { stale: '签收已失效', valid: '已签收' };
+
+export const FileView = ({
+ cases,
+ conditions,
+ file,
+ items,
+}: {
+ cases: ReportCase[];
+ conditions: string[];
+ file: string;
+ items: VerdictEntry[];
+}) => {
+ const columns = conditionColumns(conditions);
+ const list = cases.filter((entry) => entry.plan.file === file);
+ const unpaired = items.filter((item) => item.file === file && item.category === 'unpaired');
+ const signoffOf = (key: string) => items.find((item) => item.key === key)?.signoff;
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={4}>
+ <h1 {...stylex.props(styles.heading)}>{file}</h1>
+ <Text type="secondary">
+ {list.length} 个用例
+ {unpaired.length ? `,${unpaired.length} 个元素两侧配不上` : ''}
+ 。小格子是这个用例在各条件下的结果,点一行看截图。
+ </Text>
+ </Flexbox>
+ <Block style={{ overflow: 'hidden' }} variant="outlined">
+ {list.map((entry) => {
+ const [cause] = entry.result.rootCauses;
+ const signoff = signoffOf(entry.key);
+ return (
+ <a
+ href={hrefOf({ key: entry.key, kind: 'case' })}
+ key={entry.key}
+ {...stylex.props(styles.row)}
+ >
+ <span {...stylex.props(styles.key)}>{shortKey(entry.key)}</span>
+ <MatrixStrip columns={columns} entry={entry} />
+ <span {...stylex.props(styles.chips)}>
+ <Chip tone={CATEGORY_TONES[entry.category]}>{CATEGORY_LABELS[entry.category]}</Chip>
+ {signoff && SIGNOFF_LABELS[signoff] && (
+ <Chip tone={signoff === 'valid' ? 'ok' : 'bad'}>{SIGNOFF_LABELS[signoff]}</Chip>
+ )}
+ {[...entry.plan.flags, ...entry.result.gaps].map((flag) => (
+ <Chip key={flag} title={flag} tone="plain">
+ {flagLabel(flag)}
+ </Chip>
+ ))}
+ </span>
+ <span {...stylex.props(styles.cause)}>
+ {cause ? `${cause.property}: ${cause.before ?? '∅'} → ${cause.after ?? '∅'}` : ''}
+ </span>
+ </a>
+ );
+ })}
+ {unpaired.map((item) => (
+ <a
+ href={hrefOf({ key: item.key, kind: 'review' })}
+ key={item.key}
+ {...stylex.props(styles.row)}
+ >
+ <span {...stylex.props(styles.key)}>{shortKey(item.key)}</span>
+ <span />
+ <span {...stylex.props(styles.chips)}>
+ <Chip tone="warn">{CATEGORY_LABELS.unpaired}</Chip>
+ {item.signoff === 'valid' && <Chip tone="ok">已签收</Chip>}
+ </span>
+ <span />
+ </a>
+ ))}
+ </Block>
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/LiveCompare.tsx b/packages/style-equivalence/src/report/ui/LiveCompare.tsx
new file mode 100644
index 00000000000..36ae4abd921
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/LiveCompare.tsx
@@ -0,0 +1,258 @@
+import { Segmented, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useEffect, useState } from 'react';
+
+import { type CaseSnapshot, fetchSnapshot, shotUrl } from '../api';
+import type { ConditionColumn } from '../data';
+import { stateLabel, THEME_LABELS } from '../labels';
+import { type PropertyMode, propertyRows } from '../properties';
+
+const styles = stylex.create({
+ controls: { columnGap: 8, display: 'flex', flexWrap: 'wrap', rowGap: 8 },
+ frame: (width: number) => ({ borderStyle: 'none', display: 'block', height: 240, width }),
+ heading: { fontSize: cssVar.fontSize, fontWeight: 600, marginBlock: 0 },
+ missing: { padding: 12 },
+ pane: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ paneTitle: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ color: cssVar.colorTextSecondary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ paddingBlock: 6,
+ paddingInline: 12,
+ },
+ panes: { columnGap: 12, display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))' },
+ root: { display: 'flex', flexDirection: 'column', rowGap: 12 },
+ row: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ columnGap: 8,
+ display: 'grid',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 20px',
+ paddingBlock: 6,
+ paddingInline: 12,
+ },
+ rowBad: { backgroundColor: cssVar.colorErrorBg },
+ rowHead: { color: cssVar.colorTextTertiary, fontFamily: cssVar.fontFamily },
+ shot: { display: 'block', maxWidth: '100%' },
+ table: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ value: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+ viewport: { overflow: 'hidden', width: 376 },
+});
+
+const MODES: Array<[PropertyMode, string]> = [
+ ['declared', '声明过的属性'],
+ ['diff', '只看不同'],
+ ['all', '全部'],
+];
+
+const MARKS = { different: '✗', ignored: '≈', same: '✓' } as const;
+
+const Segment = <T extends string | number>({
+ onChange,
+ options,
+ value,
+}: {
+ onChange: (value: T) => void;
+ options: Array<[T, string]>;
+ value: T;
+}) => (
+ <Segmented
+ options={options.map(([option, label]) => ({ label, value: String(option) }))}
+ size="small"
+ value={String(value)}
+ onChange={(next) => {
+ const match = options.find(([option]) => String(option) === next);
+ if (match) onChange(match[0]);
+ }}
+ />
+);
+
+const Pane = ({
+ caseKey,
+ column,
+ combo,
+ revision,
+ side,
+}: {
+ caseKey: string;
+ column: ConditionColumn;
+ combo: number;
+ revision: string;
+ side: 'base' | 'head';
+}) => {
+ const live = column.state === 'default' && !column.variant;
+ const query = `case=${encodeURIComponent(caseKey)}&combo=${combo}&theme=${encodeURIComponent(column.theme)}`;
+ return (
+ <div {...stylex.props(styles.pane)}>
+ <div {...stylex.props(styles.paneTitle)}>
+ {side} {revision.slice(0, 7)} · {live ? '实时' : '截图'}
+ </div>
+ {live ? (
+ <div {...stylex.props(styles.viewport)}>
+ <iframe
+ src={`/${side}/?${query}`}
+ title={`${side} ${column.label}`}
+ {...stylex.props(styles.frame(column.width))}
+ />
+ </div>
+ ) : (
+ <img
+ alt={`${side} ${column.label}`}
+ src={shotUrl(caseKey, side, column.label, combo)}
+ {...stylex.props(styles.shot)}
+ />
+ )}
+ </div>
+ );
+};
+
+export const LiveCompare = ({
+ base,
+ caseKey,
+ columns,
+ combos,
+ declared,
+ head,
+}: {
+ base: string;
+ caseKey: string;
+ columns: ConditionColumn[];
+ combos: number;
+ declared: string[];
+ head: string;
+}) => {
+ const [label, setLabel] = useState(columns[0]?.label ?? '');
+ const [combo, setCombo] = useState(0);
+ const [mode, setMode] = useState<PropertyMode>('declared');
+ const [loaded, setLoaded] = useState<{
+ error?: string;
+ request: string;
+ snapshot?: CaseSnapshot;
+ }>();
+ const column = columns.find((item) => item.label === label) ?? columns[0];
+ const request = `${caseKey}\n${column?.label}\n${combo}`;
+ useEffect(() => {
+ if (!column) return;
+ let current = true;
+ fetchSnapshot(caseKey, column.label, combo)
+ .then((snapshot) => current && setLoaded({ request, snapshot }))
+ .catch((reason: unknown) => current && setLoaded({ error: String(reason), request }));
+ return () => {
+ current = false;
+ };
+ }, [caseKey, column, combo, request]);
+ const snapshot = loaded?.request === request ? loaded.snapshot : undefined;
+ const error = loaded?.request === request ? loaded.error : undefined;
+ if (!column) return null;
+ const pick = (change: Partial<ConditionColumn>) => {
+ const wanted = { ...column, ...change };
+ const match =
+ columns.find(
+ (item) =>
+ item.theme === wanted.theme &&
+ item.width === wanted.width &&
+ item.state === wanted.state &&
+ item.variant === wanted.variant,
+ ) ??
+ columns.find((item) => item.theme === wanted.theme && item.width === wanted.width) ??
+ columns.find((item) => item.theme === wanted.theme);
+ if (match) setLabel(match.label);
+ };
+ const themes = [...new Set(columns.map((item) => item.theme))];
+ const widths = [
+ ...new Set(columns.filter((item) => item.theme === column.theme).map((item) => item.width)),
+ ];
+ const states = columns.filter(
+ (item) => item.theme === column.theme && item.width === column.width,
+ );
+ const rows = snapshot ? propertyRows(snapshot, declared, mode) : [];
+ return (
+ <div {...stylex.props(styles.root)}>
+ <h3 {...stylex.props(styles.heading)}>实时对照</h3>
+ <div {...stylex.props(styles.controls)}>
+ <Segment
+ options={themes.map((theme) => [theme, THEME_LABELS[theme] ?? theme])}
+ value={column.theme}
+ onChange={(theme) => pick({ theme })}
+ />
+ <Segment
+ options={widths.map((width) => [width, String(width)])}
+ value={column.width}
+ onChange={(width) => pick({ width })}
+ />
+ <Segment
+ options={states.map((item) => [item.label, stateLabel(item.state, item.variant)])}
+ value={column.label}
+ onChange={(value) => setLabel(value)}
+ />
+ {combos > 1 && (
+ <Segment
+ options={Array.from({ length: combos }, (_, index) => [index, `组合 ${index + 1}`])}
+ value={combo}
+ onChange={setCombo}
+ />
+ )}
+ </div>
+ <div {...stylex.props(styles.panes)}>
+ <Pane caseKey={caseKey} column={column} combo={combo} revision={base} side="base" />
+ <Pane caseKey={caseKey} column={column} combo={combo} revision={head} side="head" />
+ </div>
+ <Segment options={MODES} value={mode} onChange={setMode} />
+ <div {...stylex.props(styles.table)}>
+ <div {...stylex.props(styles.row, styles.rowHead)}>
+ <span>属性({snapshot?.base.targetKey ?? '目标元素'})</span>
+ <span>base</span>
+ <span>head</span>
+ <span />
+ </div>
+ {!snapshot && (
+ <Text type={error ? 'danger' : 'secondary'} {...stylex.props(styles.missing)}>
+ {error ? `读取失败:${error}` : '正在这个条件下重新采样…'}
+ </Text>
+ )}
+ {snapshot && rows.length === 0 && (
+ <Text type="secondary" {...stylex.props(styles.missing)}>
+ {mode === 'diff' ? '这个条件下目标元素没有不同的属性。' : '没有可对照的属性。'}
+ </Text>
+ )}
+ {rows.map((row) => (
+ <div
+ key={row.name}
+ title={row.reason ? `不影响渲染:${row.reason}` : undefined}
+ {...stylex.props(styles.row, row.mark === 'different' && styles.rowBad)}
+ >
+ <span {...stylex.props(styles.value)}>{row.name}</span>
+ <span title={row.base} {...stylex.props(styles.value)}>
+ {row.base ?? '--'}
+ </span>
+ <span title={row.head} {...stylex.props(styles.value)}>
+ {row.head ?? '--'}
+ </span>
+ <span>{MARKS[row.mark]}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/MatrixStrip.tsx b/packages/style-equivalence/src/report/ui/MatrixStrip.tsx
new file mode 100644
index 00000000000..a43257fb502
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/MatrixStrip.tsx
@@ -0,0 +1,51 @@
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import { caseStrip, type ConditionColumn, type ReportCase } from '../data';
+
+const styles = stylex.create({
+ cell: { borderRadius: 2, height: 8, width: 8 },
+ large: { borderRadius: 3, height: 18, width: 18 },
+ largeStrip: { columnGap: 3, rowGap: 3 },
+ strip: (rows: number, size: number) => ({
+ columnGap: 2,
+ display: 'inline-grid',
+ gridAutoFlow: 'column',
+ gridTemplateRows: `repeat(${rows}, ${size}px)`,
+ rowGap: 2,
+ }),
+});
+
+const tones = stylex.create({
+ 'difference': { backgroundColor: cssVar.colorError },
+ 'equal': { backgroundColor: cssVar.colorSuccess, opacity: 0.85 },
+ 'flagged-difference': { backgroundColor: cssVar.colorWarning },
+ 'unknown': { backgroundColor: cssVar.colorFillSecondary },
+});
+
+export const MatrixStrip = ({
+ columns,
+ entry,
+ large,
+}: {
+ columns: ConditionColumn[];
+ entry: ReportCase;
+ large?: boolean;
+}) => {
+ const rows = new Set(columns.map((column) => column.theme)).size || 1;
+ return (
+ <span
+ aria-label="条件矩阵"
+ {...stylex.props(styles.strip(rows, large ? 18 : 8), large && styles.largeStrip)}
+ >
+ {caseStrip(entry, columns).map((cell) => (
+ <i
+ data-status={cell.status}
+ key={cell.label}
+ title={cell.label}
+ {...stylex.props(styles.cell, large && styles.large, tones[cell.status])}
+ />
+ ))}
+ </span>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/MethodPage.tsx b/packages/style-equivalence/src/report/ui/MethodPage.tsx
new file mode 100644
index 00000000000..b98c4a961f7
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/MethodPage.tsx
@@ -0,0 +1,221 @@
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { type ReactNode, useEffect, useState } from 'react';
+
+import { type CorpusEntry, fetchMethod, type RunPayload, type SelfTestPayload } from '../api';
+import { UNMODELED_SHAPES } from '../knownGaps';
+import { FLAG_EXPLANATIONS, flagLabel, shortKey } from '../labels';
+import { aaSummary, conditionScope } from '../method';
+import { hrefOf } from '../route';
+
+const styles = stylex.create({
+ code: { fontFamily: cssVar.fontFamilyCode, fontSize: cssVar.fontSizeSM },
+ corpus: { columnGap: 16, display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))' },
+ heading: { fontSize: cssVar.fontSizeLG, fontWeight: 600, marginBlock: 0 },
+ muted: { color: cssVar.colorTextTertiary },
+ row: {
+ alignItems: 'baseline',
+ borderRadius: cssVar.borderRadiusSM,
+ columnGap: 8,
+ display: 'flex',
+ fontSize: cssVar.fontSizeSM,
+ minWidth: 0,
+ paddingBlock: 4,
+ paddingInline: 4,
+ },
+ rowBad: { color: cssVar.colorError },
+ spread: { justifyContent: 'space-between' },
+ subheading: {
+ color: cssVar.colorTextSecondary,
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 600,
+ marginBlockEnd: 8,
+ marginBlockStart: 16,
+ },
+ target: { backgroundColor: cssVar.colorWarningBg },
+ title: { fontSize: cssVar.fontSizeHeading4, fontWeight: 600, marginBlock: 0 },
+});
+
+const Card = ({
+ children,
+ count,
+ lead,
+ title,
+}: {
+ children: ReactNode;
+ count?: ReactNode;
+ lead: string;
+ title: string;
+}) => (
+ <Block as="section" gap={12} padding={20} variant="outlined">
+ <Flexbox gap={4}>
+ <Flexbox horizontal align="baseline" gap={8}>
+ <h2 {...stylex.props(styles.heading)}>{title}</h2>
+ {count !== undefined && (
+ <Text fontSize={12} type="secondary">
+ {count}
+ </Text>
+ )}
+ </Flexbox>
+ <Text fontSize={12} type="secondary">
+ {lead}
+ </Text>
+ </Flexbox>
+ <div>{children}</div>
+ </Block>
+);
+
+const passedOf = (entries: CorpusEntry[]) =>
+ `${entries.filter((entry) => entry.passed).length} / ${entries.length} 通过`;
+
+const CorpusList = ({ anchor, entries }: { anchor?: string; entries: CorpusEntry[] }) => (
+ <div {...stylex.props(styles.corpus)}>
+ {entries.map((entry) => (
+ <div
+ id={entry.id}
+ key={entry.id}
+ title={entry.passed ? undefined : `期望 ${entry.expected},实际 ${entry.actual}`}
+ {...stylex.props(
+ styles.row,
+ !entry.passed && styles.rowBad,
+ anchor === entry.id && styles.target,
+ )}
+ >
+ <span>{entry.passed ? '✓' : '✗'}</span>
+ <code {...stylex.props(styles.code)}>{entry.id}</code>
+ <span {...stylex.props(styles.muted)}>{entry.feature}</span>
+ </div>
+ ))}
+ </div>
+);
+
+const SelfTest = ({
+ anchor,
+ selfTest,
+}: {
+ anchor?: string;
+ selfTest: SelfTestPayload | null | undefined;
+}) => {
+ if (selfTest === undefined) return <Text type="secondary">正在读取自检结果…</Text>;
+ if (!selfTest)
+ return (
+ <Text type="secondary">
+ 还没有自检记录。运行 <code {...stylex.props(styles.code)}>bun run style-eq self-test</code>{' '}
+ 后刷新这一页。
+ </Text>
+ );
+ return (
+ <>
+ <Text fontSize={12} type="secondary">
+ 验证器 {selfTest.verifierVersion} · {new Date(selfTest.ranAt).toLocaleString('zh-CN')}
+ </Text>
+ <h4 {...stylex.props(styles.subheading)}>CSS 语料 · {passedOf(selfTest.css)}</h4>
+ <CorpusList anchor={anchor} entries={selfTest.css} />
+ <h4 {...stylex.props(styles.subheading)}>源码语料 · {passedOf(selfTest.source)}</h4>
+ <CorpusList anchor={anchor} entries={selfTest.source} />
+ </>
+ );
+};
+
+export const MethodPage = ({ anchor, payload }: { anchor?: string; payload: RunPayload }) => {
+ const [selfTest, setSelfTest] = useState<SelfTestPayload | null>();
+ const [error, setError] = useState<string>();
+ useEffect(() => {
+ fetchMethod()
+ .then((value) => setSelfTest(value.selfTest))
+ .catch((reason: unknown) => setError(String(reason)));
+ }, []);
+ useEffect(() => {
+ if (anchor && selfTest !== undefined)
+ document.getElementById(anchor)?.scrollIntoView({ block: 'center' });
+ }, [anchor, selfTest]);
+ const conditions = payload.run.conditions ?? [];
+ const aa = aaSummary(payload.cases, conditions.length);
+ const { mutation } = payload;
+ return (
+ <Flexbox gap={16} style={{ maxWidth: 1200 }}>
+ <Flexbox gap={4}>
+ <h1 {...stylex.props(styles.title)}>方法依据</h1>
+ <Text type="secondary">
+ 「相等」的意思是:<b>在列出的条件下,两侧每个元素的全部计算属性和盒模型逐项一致</b>
+ 。下面几项说明为什么这个比较可信,以及它看不到什么。
+ </Text>
+ </Flexbox>
+ <Card
+ lead="每一类 CSS 差异都构造一对已知结果的样式,确认比较器该报的报出来、不该报的不报。"
+ title="边界语料"
+ >
+ {error ? (
+ <Text type="danger">读取自检结果失败:{error}</Text>
+ ) : (
+ <SelfTest anchor={anchor} selfTest={selfTest} />
+ )}
+ </Card>
+ <Card
+ count={`${mutation.caught} / ${mutation.evaluated} 抓到`}
+ lead="往 head 里注入已知的改动,确认每个都在预期的条件下被报出来。"
+ title="本次运行的变异测试"
+ >
+ {mutation.mutants.map((mutant) => (
+ <div
+ key={`${mutant.caseKey}${mutant.description}`}
+ {...stylex.props(
+ styles.row,
+ styles.spread,
+ mutant.outcome === 'missed' && styles.rowBad,
+ )}
+ >
+ <span>
+ {mutant.outcome === 'caught' ? '✓' : mutant.outcome === 'equivalent' ? '≈' : '✗'}{' '}
+ <code {...stylex.props(styles.code)}>{mutant.description}</code>{' '}
+ <a
+ href={hrefOf({ key: mutant.caseKey, kind: 'case' })}
+ {...stylex.props(styles.muted)}
+ >
+ {shortKey(mutant.caseKey)}
+ </a>
+ </span>
+ <span {...stylex.props(styles.muted)}>
+ {mutant.gaps?.length
+ ? mutant.gaps.map(flagLabel).join('、')
+ : conditionScope(mutant.expected, conditions.length)}
+ </span>
+ </div>
+ ))}
+ </Card>
+ <Card
+ count={aa.unstable.length ? `${aa.unstable.length} 个用例不稳定` : '全部稳定'}
+ lead="base 自己和自己比两次。自比都不一致的用例,任何结论都不算数,标为阻塞。"
+ title="A/A 稳定性"
+ >
+ <div {...stylex.props(styles.row)}>
+ {aa.checks} 次自比({payload.cases.length} 个用例 × {conditions.length} 个条件)
+ </div>
+ {aa.unstable.map((entry) => (
+ <div key={entry.key} {...stylex.props(styles.row, styles.rowBad)}>
+ <a href={hrefOf({ key: entry.key, kind: 'case' })}>{shortKey(entry.key)}</a>
+ <span>{entry.conditions.join('、')}</span>
+ </div>
+ ))}
+ </Card>
+ <Card lead="遇到下面的情况,用例进入签收清单,而不是标成相等。" title="已知盲区">
+ {Object.entries(FLAG_EXPLANATIONS).map(([flag, text]) => (
+ <div id={flag} key={flag} {...stylex.props(styles.row, anchor === flag && styles.target)}>
+ <b>{flagLabel(flag)}</b>
+ <code {...stylex.props(styles.code, styles.muted)}>{flag}</code>
+ <span>{text}</span>
+ </div>
+ ))}
+ </Card>
+ <Card lead="下面这些写法工具还没有建模,结果里可能出现不是真差异的差异。" title="尚未建模">
+ {UNMODELED_SHAPES.map((entry) => (
+ <div key={entry.title} {...stylex.props(styles.row)}>
+ <b>{entry.title}</b>
+ <span>{entry.text}</span>
+ </div>
+ ))}
+ </Card>
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/OverviewMatrix.tsx b/packages/style-equivalence/src/report/ui/OverviewMatrix.tsx
new file mode 100644
index 00000000000..9b96603b3f2
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/OverviewMatrix.tsx
@@ -0,0 +1,148 @@
+import { Block, Button } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useState } from 'react';
+
+import { type CellStatus, conditionColumns, overviewRows, type ReportCase } from '../data';
+import { stateLabel, THEME_LABELS } from '../labels';
+import { hrefOf } from '../route';
+
+const styles = stylex.create({
+ cell: {
+ borderRadius: cssVar.borderRadiusXS,
+ fontSize: cssVar.fontSizeSM,
+ height: 24,
+ minWidth: 40,
+ textAlign: 'center',
+ },
+ head: {
+ color: cssVar.colorTextTertiary,
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 400,
+ lineHeight: 1.4,
+ textAlign: 'center',
+ },
+ name: {
+ color: cssVar.colorText,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ paddingInlineEnd: 12,
+ textDecorationLine: { ':hover': 'underline', 'default': 'none' },
+ whiteSpace: 'nowrap',
+ },
+ rowHead: {
+ backgroundColor: cssVar.colorBgContainer,
+ fontWeight: 400,
+ insetInlineStart: 0,
+ position: 'sticky',
+ textAlign: 'start',
+ zIndex: 1,
+ },
+ scroll: { overflowX: 'auto', padding: 16 },
+ table: { borderCollapse: 'separate', borderSpacing: 4 },
+ themeHead: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ color: cssVar.colorTextSecondary,
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 500,
+ paddingBlockEnd: 4,
+ textAlign: 'start',
+ },
+});
+
+const cells = stylex.create({
+ 'difference': { backgroundColor: cssVar.colorError, color: cssVar.colorTextLightSolid },
+ 'equal': { backgroundColor: cssVar.colorSuccessBg, color: cssVar.colorSuccess },
+ 'flagged-difference': { backgroundColor: cssVar.colorErrorBg, color: cssVar.colorError },
+ 'unknown': { backgroundColor: cssVar.colorFillQuaternary, color: cssVar.colorTextQuaternary },
+});
+
+const cellText = (status: CellStatus, count: number) =>
+ status === 'equal' ? '✓' : status === 'unknown' ? '—' : String(count);
+
+export const OverviewMatrix = ({
+ cases,
+ conditions,
+}: {
+ cases: ReportCase[];
+ conditions: string[];
+}) => {
+ const [showEqual, setShowEqual] = useState(false);
+ const columns = conditionColumns(conditions);
+ const themes = [...new Set(columns.map((column) => column.theme))];
+ const { equal, open } = overviewRows(cases, columns);
+ const rows = showEqual ? [...open, ...equal] : open;
+ return (
+ <Block variant="outlined">
+ <div {...stylex.props(styles.scroll)}>
+ <table {...stylex.props(styles.table)}>
+ <thead>
+ <tr>
+ <th {...stylex.props(styles.rowHead)} />
+ {themes.map((theme) => (
+ <th
+ colSpan={columns.filter((column) => column.theme === theme).length}
+ key={theme}
+ {...stylex.props(styles.themeHead)}
+ >
+ {THEME_LABELS[theme] ?? theme}
+ </th>
+ ))}
+ </tr>
+ <tr>
+ <th {...stylex.props(styles.rowHead)} />
+ {columns.map((column) => (
+ <th key={column.label} title={column.label} {...stylex.props(styles.head)}>
+ {column.width}
+ <br />
+ {stateLabel(column.state, column.variant)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => (
+ <tr aria-label={row.file} key={row.file}>
+ <th scope="row" {...stylex.props(styles.rowHead)}>
+ <a href={hrefOf({ file: row.file, kind: 'file' })} {...stylex.props(styles.name)}>
+ {row.file}
+ </a>
+ </th>
+ {row.matrix.map((cell) => (
+ <td
+ data-status={cell.status}
+ key={cell.label}
+ title={cell.label}
+ {...stylex.props(styles.cell, cells[cell.status])}
+ >
+ {cellText(cell.status, cell.count)}
+ </td>
+ ))}
+ </tr>
+ ))}
+ {!showEqual && equal.length > 0 && (
+ <tr aria-label={`另外 ${equal.length} 个文件全部相等`}>
+ <th scope="row" {...stylex.props(styles.rowHead)}>
+ <Button size="small" type="text" onClick={() => setShowEqual(true)}>
+ 另外 {equal.length} 个文件全部相等,展开
+ </Button>
+ </th>
+ {columns.map((column) => (
+ <td
+ data-status="equal"
+ key={column.label}
+ {...stylex.props(styles.cell, cells.equal)}
+ >
+ ✓
+ </td>
+ ))}
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </Block>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/PageState.tsx b/packages/style-equivalence/src/report/ui/PageState.tsx
new file mode 100644
index 00000000000..5d755859711
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/PageState.tsx
@@ -0,0 +1,34 @@
+import { Button, Center, Empty, Spin, Text } from '@lobehub/ui';
+import { CircleAlert } from 'lucide-react';
+
+export const PageState = ({
+ error,
+ loading,
+ onRetry,
+ title,
+}: {
+ error?: string;
+ loading: string;
+ onRetry?: () => void;
+ title: string;
+}) => (
+ <Center gap={12} height="100vh" width="100%">
+ {error ? (
+ <Empty
+ action={onRetry && <Button onClick={onRetry}>重试</Button>}
+ description={error}
+ icon={CircleAlert}
+ title={title}
+ />
+ ) : (
+ <>
+ <Spin />
+ <Text type="secondary">{loading}</Text>
+ </>
+ )}
+ </Center>
+);
+
+export const InlineState = ({ error, loading }: { error?: string; loading: string }) => (
+ <Text type={error ? 'danger' : 'secondary'}>{error ?? loading}</Text>
+);
diff --git a/packages/style-equivalence/src/report/ui/RestDifferences.tsx b/packages/style-equivalence/src/report/ui/RestDifferences.tsx
new file mode 100644
index 00000000000..27b47d1bd63
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/RestDifferences.tsx
@@ -0,0 +1,106 @@
+import { Block, Button, Flexbox, Tag, Text } from '@lobehub/ui';
+import { useState } from 'react';
+
+import type { ReviewView } from '../api';
+import { conditionName, describeConditions, groupDifferences, type reviewGrid } from '../review';
+import { Pair } from './ShotGrid';
+
+type RestDifference = ReturnType<typeof reviewGrid>['restDifferences'][number];
+type Group = ReturnType<typeof groupDifferences<RestDifference>>[number];
+
+const VISIBLE_GROUPS = 3;
+const VISIBLE_CONDITIONS = 10;
+
+const DifferenceGroup = ({
+ group,
+ item,
+ showCombo,
+}: {
+ group: Group;
+ item: ReviewView;
+ showCombo: boolean;
+}) => {
+ const [picked, setPicked] = useState(group.entries[0]);
+ const [allConditions, setAllConditions] = useState(false);
+ const shown = allConditions ? group.entries : group.entries.slice(0, VISIBLE_CONDITIONS);
+ const hidden = group.entries.length - shown.length;
+ return (
+ <Block gap={12} padding={16} variant="outlined">
+ <Flexbox gap={4}>
+ <Text strong type="danger">
+ 不一样:{group.summary.join(';')}
+ </Text>
+ <Text fontSize={12} type="secondary">
+ {showCombo ? `${group.label} · ` : ''}
+ {group.entries.length} 个条件:
+ {describeConditions(group.entries.map((entry) => entry.condition)).join(';')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={6} wrap="wrap">
+ {shown.map((entry) => (
+ <Tag
+ aria-pressed={entry === picked}
+ color={entry === picked ? 'processing' : undefined}
+ key={entry.condition}
+ role="button"
+ size="small"
+ style={{ cursor: 'pointer' }}
+ tabIndex={0}
+ onClick={() => setPicked(entry)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setPicked(entry);
+ }
+ }}
+ >
+ {conditionName(entry.condition)}
+ </Tag>
+ ))}
+ {hidden > 0 && (
+ <Button size="small" type="text" onClick={() => setAllConditions(true)}>
+ 还有 {hidden} 个
+ </Button>
+ )}
+ </Flexbox>
+ <Pair combo={picked.combo} condition={picked.condition} item={item} />
+ </Block>
+ );
+};
+
+export const RestDifferences = ({
+ count,
+ differences,
+ item,
+}: {
+ count: number;
+ differences: RestDifference[];
+ item: ReviewView;
+}) => {
+ const [allGroups, setAllGroups] = useState(false);
+ if (!differences.length)
+ return (
+ <Text fontSize={12} type="secondary">
+ 还有 {count} 个宽度和交互状态,全部一致。
+ </Text>
+ );
+ const groups = groupDifferences(differences);
+ const shown = allGroups ? groups : groups.slice(0, VISIBLE_GROUPS);
+ const showCombo = item.combos.length > 1;
+ return (
+ <Flexbox gap={12}>
+ <Text type="secondary">
+ 其余 {count} 个宽度和交互状态里,{differences.length} 个不一样,归成 {groups.length}{' '}
+ 种差异。点条件切换截图。
+ </Text>
+ {shown.map((group) => (
+ <DifferenceGroup group={group} item={item} key={group.key} showCombo={showCombo} />
+ ))}
+ {groups.length > shown.length && (
+ <Button block onClick={() => setAllGroups(true)}>
+ 再显示 {groups.length - shown.length} 种差异
+ </Button>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ReviewBar.tsx b/packages/style-equivalence/src/report/ui/ReviewBar.tsx
new file mode 100644
index 00000000000..f3359f6efbb
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewBar.tsx
@@ -0,0 +1,164 @@
+import { Button, Flexbox, Hotkey, Text, TextArea, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Check, Undo2 } from 'lucide-react';
+import type { ReactNode, RefObject } from 'react';
+
+import type { ReviewView } from '../api';
+import { defaultReworkNote, hasRenderedDifference } from '../review';
+
+const styles = stylex.create({
+ bar: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ flex: 'none',
+ paddingBlock: 12,
+ paddingInline: 32,
+ },
+ trigger: { display: 'inline-flex' },
+});
+
+const ActionTooltip = ({
+ blocked,
+ children,
+ hotkey,
+ title,
+}: {
+ blocked: boolean;
+ children: ReactNode;
+ hotkey: string;
+ title: string;
+}) => (
+ <Tooltip hotkey={hotkey} title={title}>
+ <span
+ aria-label={blocked ? title : undefined}
+ tabIndex={blocked ? 0 : undefined}
+ {...stylex.props(styles.trigger)}
+ >
+ {children}
+ </span>
+ </Tooltip>
+);
+
+const passBlocker = (item: ReviewView, note: string) => {
+ if (!item.canPass)
+ return item.state === 'waiting-agent' ? '等 agent 读完代码才能操作' : '这一项只能打回';
+ if (item.category === 'difference' && !note.trim())
+ return '通过要先写一句为什么不一样也没问题,打回不用写';
+};
+
+const placeholderOf = (differs: boolean, passNeedsNote: boolean) => {
+ if (!differs) return '打回原因(打回时必填),比如「在线时多了一圈灰边」';
+ return passNeedsNote
+ ? '原因可不填:打回时默认记下这处差异;通过时要写一句为什么不一样也没问题'
+ : '原因可不填:打回时默认记下这处差异,也可以写你自己的原因';
+};
+
+const reworkTitleOf = (item: ReviewView, differs: boolean, note: string) => {
+ if (item.state === 'waiting-agent') return '等 agent 读完代码才能操作';
+ if (!differs) return '打回,原因必填';
+ return note.trim() ? '打回,记下你写的原因' : `打回,默认记下:${defaultReworkNote(item)}`;
+};
+
+export const ReviewBar = ({
+ busy,
+ error,
+ inputRef,
+ item,
+ note,
+ onNote,
+ onPass,
+ onRework,
+ position,
+}: {
+ busy?: 'pass' | 'rework';
+ error?: string;
+ inputRef: RefObject<HTMLTextAreaElement | null>;
+ item: ReviewView;
+ note: string;
+ onNote: (value: string) => void;
+ onPass: () => void;
+ onRework: () => void;
+ position: string;
+}) => {
+ const passNeedsNote = item.canPass && item.category === 'difference';
+ const waiting = item.state === 'waiting-agent';
+ const blocker = passBlocker(item, note);
+ const differs = hasRenderedDifference(item);
+ const hints = [
+ blocker,
+ !differs && !waiting && !note.trim() ? '打回要先写原因' : undefined,
+ ].filter(Boolean);
+ return (
+ <Flexbox gap={8} {...stylex.props(styles.bar)}>
+ <Flexbox horizontal align="flex-end" gap={8}>
+ <TextArea
+ aria-label="打回原因"
+ autoSize={{ maxRows: 4, minRows: 1 }}
+ disabled={Boolean(busy)}
+ placeholder={placeholderOf(differs, passNeedsNote)}
+ ref={inputRef}
+ style={{ flex: 1 }}
+ value={note}
+ onChange={(event) => onNote(event.target.value)}
+ />
+ <ActionTooltip blocked={waiting} hotkey="n" title={reworkTitleOf(item, differs, note)}>
+ <Button
+ danger
+ disabled={Boolean(busy) || waiting}
+ icon={Undo2}
+ loading={busy === 'rework'}
+ onClick={onRework}
+ >
+ 打回
+ </Button>
+ </ActionTooltip>
+ <ActionTooltip blocked={Boolean(blocker)} hotkey="y" title={blocker ?? '通过这一项'}>
+ <Button
+ disabled={Boolean(busy || blocker)}
+ icon={Check}
+ loading={busy === 'pass'}
+ type="primary"
+ onClick={onPass}
+ >
+ 通过
+ </Button>
+ </ActionTooltip>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={12}>
+ {error ? (
+ <Text fontSize={12} type="danger">
+ 操作没有保存:{error}
+ </Text>
+ ) : (
+ <Text fontSize={12} type="secondary">
+ {position}
+ {hints.map((hint) => ` · ${hint}`).join('')}
+ </Text>
+ )}
+ <Flexbox flex={1} />
+ <Flexbox horizontal align="center" gap={4}>
+ <Hotkey compact keys="j" />
+ <Hotkey compact keys="k" />
+ <Text fontSize={12} type="secondary">
+ 上下条
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={4}>
+ <Hotkey compact keys="y" />
+ <Text fontSize={12} type="secondary">
+ 通过
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={4}>
+ <Hotkey compact keys="n" />
+ <Text fontSize={12} type="secondary">
+ 打回
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx b/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx
new file mode 100644
index 00000000000..dec681cbaeb
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx
@@ -0,0 +1,73 @@
+import { Alert, Flexbox } from '@lobehub/ui';
+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 { RestDifferences } from './RestDifferences';
+import { Legend, ShotGrid } from './ShotGrid';
+import { StyleDetails } from './StyleDetails';
+
+const styles = stylex.create({
+ heading: { fontSize: cssVar.fontSizeLG, fontWeight: 600, marginBlock: 0 },
+});
+
+const AgentNote = ({ item }: { item: ReviewView }) =>
+ item.note ? (
+ <Alert
+ description={item.note.finding}
+ title={item.note.suggestion === 'pass' ? 'agent 建议通过' : 'agent 建议打回'}
+ type={item.note.suggestion === 'pass' ? 'success' : 'error'}
+ variant="soft"
+ />
+ ) : (
+ <Alert
+ description="截图之外还要读代码确认。agent 读完会在这里写一句结论,之后才能操作。"
+ title="等 agent 读代码"
+ type="info"
+ variant="soft"
+ />
+ );
+
+export const ReviewEvidence = ({
+ conditions,
+ item,
+ notes = 'needed',
+}: {
+ conditions: string[];
+ item: ReviewView;
+ notes?: 'needed' | 'written';
+}) => {
+ const grid = reviewGrid(item.combos, conditions, item.comboDifferences);
+ const visual = hasScreenshots(item);
+ const note = notes === 'needed' ? item.needsAgent : Boolean(item.note);
+ return (
+ <Flexbox gap={24}>
+ {item.category === 'blocking' && (
+ <Alert
+ description={item.errors[0] ?? '渲染失败'}
+ title="没能渲染"
+ type="error"
+ variant="soft"
+ />
+ )}
+ {note && <AgentNote item={item} />}
+ {visual && (
+ <Flexbox gap={16}>
+ <Legend />
+ <ShotGrid columns={grid.columns} item={item} rows={grid.rows} />
+ </Flexbox>
+ )}
+ {visual && grid.states.columns.length > 0 && (
+ <Flexbox gap={12}>
+ <h2 {...stylex.props(styles.heading)}>交互状态</h2>
+ <ShotGrid columns={grid.states.columns} item={item} rows={grid.states.rows} />
+ </Flexbox>
+ )}
+ {visual && (
+ <RestDifferences count={grid.restCount} differences={grid.restDifferences} item={item} />
+ )}
+ <StyleDetails item={item} />
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ReviewItemView.tsx b/packages/style-equivalence/src/report/ui/ReviewItemView.tsx
new file mode 100644
index 00000000000..c995cdb6f4e
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewItemView.tsx
@@ -0,0 +1,80 @@
+import { Alert, Button, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ExternalLink } from 'lucide-react';
+import type { ReactNode } from 'react';
+
+import type { ReviewView } from '../api';
+import { CATEGORY_LABELS } from '../labels';
+import { hrefOf } from '../route';
+import { CATEGORY_TONES, Chip } from './Chip';
+import { ReviewEvidence } from './ReviewEvidence';
+
+const styles = stylex.create({
+ title: {
+ fontSize: cssVar.fontSizeHeading4,
+ fontWeight: 600,
+ lineHeight: cssVar.lineHeightHeading4,
+ marginBlock: 0,
+ overflowWrap: 'anywhere',
+ },
+});
+
+export const ItemHeader = ({
+ action,
+ extra,
+ item,
+}: {
+ action?: ReactNode;
+ extra?: ReactNode;
+ item: ReviewView;
+}) => (
+ <Flexbox gap={8}>
+ <Flexbox horizontal align="center" gap={8} wrap="wrap">
+ <h1 {...stylex.props(styles.title)}>{item.title}</h1>
+ <Chip tone={CATEGORY_TONES[item.category] ?? 'plain'}>
+ {CATEGORY_LABELS[item.category] ?? item.category}
+ </Chip>
+ {item.component && <Chip tone="info">{item.component}</Chip>}
+ {extra}
+ <Flexbox flex={1} />
+ {action}
+ </Flexbox>
+ <Text code fontSize={12} type="secondary">
+ {item.file}
+ </Text>
+ </Flexbox>
+);
+
+export const ReworkNote = ({ note }: { note: string }) => (
+ <Alert description={note} title="你上次打回的原因" type="warning" variant="soft" />
+);
+
+export const ReviewItemView = ({
+ conditions,
+ item,
+}: {
+ conditions: string[];
+ item: ReviewView;
+}) => (
+ <Flexbox gap={24}>
+ <Flexbox gap={12}>
+ <ItemHeader
+ item={item}
+ action={
+ <Button
+ href={hrefOf({ key: item.key, kind: 'case' })}
+ icon={ExternalLink}
+ size="small"
+ type="text"
+ >
+ 用例详情
+ </Button>
+ }
+ />
+ <Text fontSize={14}>{item.ask}</Text>
+ {item.rework && <ReworkNote note={item.rework.note} />}
+ </Flexbox>
+ <ReviewEvidence conditions={conditions} item={item} />
+ </Flexbox>
+);
diff --git a/packages/style-equivalence/src/report/ui/ReviewPage.tsx b/packages/style-equivalence/src/report/ui/ReviewPage.tsx
new file mode 100644
index 00000000000..58f188d7ce2
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewPage.tsx
@@ -0,0 +1,190 @@
+import { Button, Empty, ScrollArea, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckCheck } from 'lucide-react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { fetchReview, postReview, type ReviewPayload } from '../api';
+import { completionText, hasRenderedDifference, keyAction, nextSelection } from '../review';
+import { PageState } from './PageState';
+import { ReviewBar } from './ReviewBar';
+import { ReviewItemView } from './ReviewItemView';
+import { ReviewProgress } from './ReviewProgress';
+import { ReviewQueue } from './ReviewQueue';
+import { ReworkPanel } from './ReworkPanel';
+import { useFollowRun } from './RunBadge';
+import { TopBar } from './TopBar';
+
+const styles = stylex.create({
+ content: { maxWidth: 1440, paddingBlock: 24, paddingInline: 32 },
+ layout: { display: 'grid', flex: '1', gridTemplateColumns: '288px minmax(0, 1fr)', minHeight: 0 },
+ main: { display: 'flex', flexDirection: 'column', minHeight: 0, minWidth: 0 },
+ page: {
+ backgroundColor: cssVar.colorBgLayout,
+ color: cssVar.colorText,
+ display: 'flex',
+ flexDirection: 'column',
+ fontVariantNumeric: 'tabular-nums',
+ height: '100vh',
+ },
+ queue: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ borderInlineEndStyle: 'solid',
+ borderInlineEndWidth: 1,
+ height: '100%',
+ minHeight: 0,
+ },
+ scroll: { flex: '1', minHeight: 0, overflowY: 'auto' },
+});
+
+const isTyping = (target: EventTarget | null) =>
+ target instanceof HTMLElement && ['INPUT', 'TEXTAREA'].includes(target.tagName);
+
+const inDialog = (target: EventTarget | null) =>
+ target instanceof Element && Boolean(target.closest('[role="dialog"]'));
+
+export const ReviewPage = ({ initialKey }: { initialKey?: string }) => {
+ const [payload, setPayload] = useState<ReviewPayload>();
+ const [current, setCurrent] = useState<string | undefined>(initialKey);
+ const [note, setNote] = useState('');
+ const [busy, setBusy] = useState<'pass' | 'rework'>();
+ const [error, setError] = useState<string>();
+ const [panel, setPanel] = useState(false);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ const load = useCallback(() => {
+ fetchReview()
+ .then((next) => {
+ setPayload(next);
+ setCurrent((selected) =>
+ selected && next.items.some((entry) => entry.key === selected)
+ ? selected
+ : nextSelection(next.items, undefined),
+ );
+ })
+ .catch((reason: unknown) => setError(String(reason)));
+ }, []);
+ useEffect(load, [load]);
+ useFollowRun(payload?.follow, load);
+
+ const item = payload?.items.find((entry) => entry.key === current);
+
+ const select = useCallback((key: string | undefined) => {
+ setCurrent(key);
+ setNote('');
+ setError(undefined);
+ scrollRef.current?.scrollTo({ top: 0 });
+ }, []);
+
+ const act = useCallback(
+ async (action: 'pass' | 'rework') => {
+ if (!item || busy) return;
+ const needsNote =
+ action === 'rework' ? !hasRenderedDifference(item) : item.category === 'difference';
+ if (needsNote && !note.trim()) return void inputRef.current?.focus();
+ setBusy(action);
+ try {
+ const next = await postReview({ action, key: item.key, note });
+ setPayload(next);
+ select(nextSelection(next.items, item.key));
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : String(reason));
+ } finally {
+ setBusy(undefined);
+ }
+ },
+ [busy, item, note, select],
+ );
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (!payload || event.metaKey || event.ctrlKey || event.altKey) return;
+ const action = keyAction(event.key, isTyping(event.target), panel || inDialog(event.target));
+ if (!action) return;
+ event.preventDefault();
+ const index = payload.items.findIndex((entry) => entry.key === current);
+ if (action === 'next')
+ select(payload.items[Math.min(index + 1, payload.items.length - 1)]?.key);
+ if (action === 'previous') select(payload.items[Math.max(index - 1, 0)]?.key);
+ if (action === 'pass' && item?.canPass) void act('pass');
+ if (action === 'rework') void act('rework');
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [act, current, item, panel, payload, select]);
+
+ if (!payload)
+ return (
+ <PageState
+ error={error}
+ loading="正在读取复查队列…"
+ title="读取复查队列失败"
+ onRetry={() => {
+ setError(undefined);
+ load();
+ }}
+ />
+ );
+ const index = payload.items.findIndex((entry) => entry.key === current);
+ return (
+ <div {...stylex.props(styles.page)}>
+ <TopBar
+ base={payload.run.base}
+ follow={payload.follow}
+ head={payload.run.head}
+ section="review"
+ />
+ <ReviewProgress payload={payload} onOpenReworked={() => setPanel(true)} />
+ <div {...stylex.props(styles.layout)}>
+ <aside aria-label="复查队列" {...stylex.props(styles.queue)}>
+ <ScrollArea disableContentFit style={{ height: '100%' }}>
+ <ReviewQueue current={current} payload={payload} onSelect={select} />
+ </ScrollArea>
+ </aside>
+ <main key={payload.run.runId} {...stylex.props(styles.main)}>
+ <div ref={scrollRef} {...stylex.props(styles.scroll)}>
+ <div {...stylex.props(styles.content)}>
+ {item ? (
+ <ReviewItemView conditions={payload.conditions} item={item} />
+ ) : (
+ <Empty
+ icon={CheckCheck}
+ title={completionText(payload.counts, payload.verdict)[0]}
+ type="page"
+ action={
+ payload.counts.reworked > 0 && (
+ <Button onClick={() => setPanel(true)}>查看打回的项</Button>
+ )
+ }
+ description={completionText(payload.counts, payload.verdict)
+ .slice(1)
+ .map((line) => (
+ <Text as="p" key={line} type="secondary">
+ {line}
+ </Text>
+ ))}
+ />
+ )}
+ </div>
+ </div>
+ {item && (
+ <ReviewBar
+ busy={busy}
+ error={error}
+ inputRef={inputRef}
+ item={item}
+ note={note}
+ position={`第 ${index + 1} / ${payload.items.length} 条`}
+ onNote={setNote}
+ onPass={() => void act('pass')}
+ onRework={() => void act('rework')}
+ />
+ )}
+ </main>
+ </div>
+ <ReworkPanel open={panel} payload={payload} onClose={() => setPanel(false)} />
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ReviewProgress.tsx b/packages/style-equivalence/src/report/ui/ReviewProgress.tsx
new file mode 100644
index 00000000000..693ba26260c
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewProgress.tsx
@@ -0,0 +1,71 @@
+import { Button, Flexbox, Progress, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import type { ReviewPayload } from '../api';
+import { Chip } from './Chip';
+
+const styles = stylex.create({
+ bar: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorBgContainer,
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ columnGap: 16,
+ display: 'flex',
+ flex: 'none',
+ flexWrap: 'wrap',
+ paddingBlock: 10,
+ paddingInline: 20,
+ rowGap: 8,
+ },
+ progress: { width: 160 },
+});
+
+export const ReviewProgress = ({
+ onOpenReworked,
+ payload,
+}: {
+ onOpenReworked: () => void;
+ payload: ReviewPayload;
+}) => {
+ const { counts } = payload;
+ const open = counts.todo + counts.changed;
+ const total = payload.items.length;
+ const decided = counts.passed + counts.reworked;
+ return (
+ <div {...stylex.props(styles.bar)}>
+ <Text ellipsis strong>
+ {payload.pr
+ ? `#${payload.pr.number} ${payload.pr.title}`
+ : `${payload.run.base.slice(0, 7)}..${payload.run.head.slice(0, 7)}`}
+ </Text>
+ <Text type="secondary">
+ 工具已自动证明 {counts.proven} 条,剩 {total} 条要你看
+ </Text>
+ <Flexbox flex={1} />
+ <Flexbox horizontal align="center" gap={8}>
+ <Progress
+ aria-label="复查进度"
+ percent={total ? Math.round((decided / total) * 100) : 100}
+ showInfo={false}
+ size="small"
+ {...stylex.props(styles.progress)}
+ />
+ <Text fontSize={12} type="secondary">
+ {decided} / {total}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={6}>
+ <Chip tone="ok">已通过 {counts.passed}</Chip>
+ <Chip tone="bad">已打回 {counts.reworked}</Chip>
+ <Chip tone="plain">待看 {open}</Chip>
+ {counts['waiting-agent'] > 0 && <Chip tone="warn">等 agent {counts['waiting-agent']}</Chip>}
+ </Flexbox>
+ <Button size="small" onClick={onOpenReworked}>
+ 查看打回({counts.reworked})
+ </Button>
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ReviewQueue.tsx b/packages/style-equivalence/src/report/ui/ReviewQueue.tsx
new file mode 100644
index 00000000000..2b1b9ec9cf4
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReviewQueue.tsx
@@ -0,0 +1,128 @@
+import { Empty, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckCheck } from 'lucide-react';
+
+import type { ReviewPayload, ReviewState, ReviewView } from '../api';
+
+const styles = stylex.create({
+ current: {
+ backgroundColor: { ':hover': cssVar.colorFillSecondary, 'default': cssVar.colorFillSecondary },
+ color: cssVar.colorText,
+ fontWeight: 500,
+ },
+ file: {
+ paddingBlockEnd: 4,
+ paddingBlockStart: 12,
+ paddingInline: 8,
+ },
+ item: {
+ alignItems: 'start',
+ backgroundColor: { ':hover': cssVar.colorFillTertiary, 'default': 'transparent' },
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'none',
+ color: cssVar.colorTextSecondary,
+ columnGap: 8,
+ cursor: 'pointer',
+ display: 'grid',
+ font: 'inherit',
+ gridTemplateColumns: '8px minmax(0, 1fr) auto',
+ paddingBlock: 6,
+ paddingInline: 8,
+ textAlign: 'start',
+ width: '100%',
+ },
+ mark: { borderRadius: '50%', height: 8, marginBlockStart: 7, width: 8 },
+ root: { padding: 8 },
+ title: { overflowWrap: 'anywhere' },
+});
+
+const marks = stylex.create({
+ 'changed': { backgroundColor: cssVar.colorInfo },
+ 'passed': { backgroundColor: cssVar.colorSuccess },
+ 'reworked': { backgroundColor: cssVar.colorError },
+ 'todo': { backgroundColor: cssVar.colorTextQuaternary },
+ 'waiting-agent': { backgroundColor: cssVar.colorWarning },
+});
+
+const STATE_LABELS: Record<ReviewState, string> = {
+ 'changed': '已修改',
+ 'passed': '已通过',
+ 'reworked': '已打回',
+ 'todo': '待看',
+ 'waiting-agent': '等 agent',
+};
+
+const HINTS: Partial<Record<ReviewState, string>> = {
+ 'changed': '已修改',
+ 'waiting-agent': '等 agent',
+};
+
+const byFile = (items: ReviewView[]) => {
+ const groups = new Map<string, ReviewView[]>();
+ for (const item of items) groups.set(item.file, [...(groups.get(item.file) ?? []), item]);
+ return [...groups];
+};
+
+const shortFile = (file: string) => file.split('/').slice(-3).join('/');
+
+const scrollIntoView = (element: HTMLButtonElement | null) => {
+ element?.scrollIntoView({ block: 'nearest' });
+};
+
+export const ReviewQueue = ({
+ current,
+ onSelect,
+ payload,
+}: {
+ current?: string;
+ onSelect: (key: string) => void;
+ payload: ReviewPayload;
+}) => (
+ <nav aria-label="复查队列" {...stylex.props(styles.root)}>
+ {!payload.items.length && (
+ <Empty description="工具已证明的项不用人工看。" icon={CheckCheck} title="没有要你看的项" />
+ )}
+ {byFile(payload.items).map(([file, items]) => (
+ <div key={file}>
+ <Text ellipsis fontSize={12} title={file} type="secondary" {...stylex.props(styles.file)}>
+ {shortFile(file)}
+ </Text>
+ {items.map((item) => (
+ <button
+ aria-current={item.key === current ? 'true' : undefined}
+ key={item.key}
+ ref={item.key === current ? scrollIntoView : undefined}
+ type="button"
+ onClick={() => onSelect(item.key)}
+ {...stylex.props(styles.item, item.key === current && styles.current)}
+ >
+ <span
+ aria-label={STATE_LABELS[item.state]}
+ role="img"
+ {...stylex.props(styles.mark, marks[item.state])}
+ />
+ <span {...stylex.props(styles.title)}>{item.title}</span>
+ {HINTS[item.state] && (
+ <Text fontSize={12} type="secondary">
+ {HINTS[item.state]}
+ </Text>
+ )}
+ </button>
+ ))}
+ </div>
+ ))}
+ {payload.resolved.length > 0 && (
+ <div>
+ <Text fontSize={12} type="secondary" {...stylex.props(styles.file)}>
+ 已解决
+ </Text>
+ {payload.resolved.map((entry) => (
+ <Text fontSize={12} key={entry.key} type="secondary" {...stylex.props(styles.file)}>
+ {entry.key.slice(entry.key.indexOf('|') + 1)}:{entry.note}
+ </Text>
+ ))}
+ </div>
+ )}
+ </nav>
+);
diff --git a/packages/style-equivalence/src/report/ui/ReworkPanel.tsx b/packages/style-equivalence/src/report/ui/ReworkPanel.tsx
new file mode 100644
index 00000000000..d401e29d3b3
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ReworkPanel.tsx
@@ -0,0 +1,80 @@
+import { Alert, Block, Drawer, Empty, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Inbox } from 'lucide-react';
+
+import type { ReviewPayload } from '../api';
+
+const styles = stylex.create({
+ reason: {
+ borderInlineStartColor: cssVar.colorError,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartWidth: 3,
+ paddingInlineStart: 10,
+ },
+});
+
+const timeOf = (iso: string) =>
+ new Date(iso).toLocaleString('zh-CN', {
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ month: 'numeric',
+ });
+
+export const ReworkPanel = ({
+ onClose,
+ open,
+ payload,
+}: {
+ onClose: () => void;
+ open: boolean;
+ payload: ReviewPayload;
+}) => {
+ const reworked = payload.items.filter((item) => item.state === 'reworked' && item.rework);
+ return (
+ <Drawer
+ open={open}
+ placement="right"
+ title={`已打回 ${reworked.length} 项`}
+ width={480}
+ footer={
+ reworked.length > 0 && (
+ <Alert
+ description="在终端对 agent 说「处理打回」。改完重跑后,这些项会标成「已修改」回到左侧队列,请你再看一眼。"
+ title="下一步"
+ type="info"
+ variant="soft"
+ />
+ )
+ }
+ onClose={onClose}
+ >
+ {reworked.length === 0 ? (
+ <Empty
+ description="打回的项会列在这里,附上你写的原因。"
+ icon={Inbox}
+ title="现在没有打回的项"
+ />
+ ) : (
+ <Flexbox gap={8}>
+ {reworked.map((item) => (
+ <Block gap={8} key={item.key} padding={12} variant="outlined">
+ <Flexbox horizontal align="baseline" gap={8}>
+ <Text strong>{item.title}</Text>
+ <Text fontSize={12} type="secondary">
+ {item.file.split('/').pop()}
+ </Text>
+ <Flexbox flex={1} />
+ <Text fontSize={12} type="secondary">
+ {timeOf(item.rework!.at)}
+ </Text>
+ </Flexbox>
+ <Text {...stylex.props(styles.reason)}>{item.rework!.note}</Text>
+ </Block>
+ ))}
+ </Flexbox>
+ )}
+ </Drawer>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/RunBadge.tsx b/packages/style-equivalence/src/report/ui/RunBadge.tsx
new file mode 100644
index 00000000000..05f96e08156
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/RunBadge.tsx
@@ -0,0 +1,43 @@
+import { Flexbox, Text } from '@lobehub/ui';
+import { useEffect } from 'react';
+
+import { fetchCurrent, type FollowInfo } from '../api';
+import { Chip } from './Chip';
+
+const POLL_MS = 5000;
+
+const timeOf = (startedAt: string | undefined) =>
+ startedAt ? new Date(startedAt).toLocaleString('zh-CN', { hour12: false }) : undefined;
+
+export const useFollowRun = (follow: FollowInfo | undefined, reload: () => void) => {
+ const runId = follow?.runId;
+ const pinned = follow?.pinned ?? true;
+ useEffect(() => {
+ if (!runId || pinned) return;
+ const timer = window.setInterval(() => {
+ fetchCurrent()
+ .then((next) => next.runId !== runId && reload())
+ .catch(() => undefined);
+ }, POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [pinned, reload, runId]);
+};
+
+export const RunBadge = ({ follow }: { follow?: FollowInfo }) => {
+ if (!follow) return null;
+ const time = timeOf(follow.startedAt);
+ return (
+ <Flexbox horizontal align="center" gap={8} title={follow.runId}>
+ <Text fontSize={12} type="secondary">
+ 运行于 {time ?? follow.runId}
+ </Text>
+ {follow.pinned ? (
+ <Chip tone="plain">已固定这次运行</Chip>
+ ) : follow.runId === follow.requested ? null : (
+ <Chip title={`启动时打开的是 ${follow.requested}`} tone="info">
+ 已自动切到最新一次运行
+ </Chip>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/ShotGrid.tsx b/packages/style-equivalence/src/report/ui/ShotGrid.tsx
new file mode 100644
index 00000000000..a30c19506ef
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ShotGrid.tsx
@@ -0,0 +1,196 @@
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { TriangleAlert } from 'lucide-react';
+
+import { REVEAL_COLORS } from '../../server/reveal';
+import { cropShotUrl, type ReviewView } from '../api';
+import type { reviewGrid } from '../review';
+import { cellVerdict, shotNotes } from '../review';
+
+const styles = stylex.create({
+ cell: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ padding: 12,
+ rowGap: 8,
+ },
+ checker: (dark: string, light: string) => ({
+ backgroundImage: `repeating-conic-gradient(${dark} 0 25%, ${light} 0 50%)`,
+ backgroundSize: '6px 6px',
+ borderRadius: 2,
+ height: 12,
+ width: 12,
+ }),
+ colHead: { paddingInlineStart: 4 },
+ dash: (color: string) => ({
+ borderColor: color,
+ borderStyle: 'dashed',
+ borderWidth: 1,
+ height: 10,
+ width: 14,
+ }),
+ diff: {
+ borderColor: cssVar.colorError,
+ boxShadow: `0 0 0 3px ${cssVar.colorErrorBg}`,
+ },
+ grid: { alignItems: 'stretch', columnGap: 16, display: 'grid', rowGap: 12 },
+ gridColumns: (count: number) => ({
+ gridTemplateColumns: `96px repeat(${count}, minmax(0, 1fr))`,
+ }),
+ pair: { columnGap: 8, display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))' },
+ rowHead: { alignSelf: 'center', overflowWrap: 'anywhere' },
+ shot: {
+ backgroundColor: cssVar.colorBgLayout,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ boxSizing: 'border-box',
+ display: 'block',
+ height: 128,
+ imageRendering: 'pixelated',
+ objectFit: 'contain',
+ width: '100%',
+ },
+ side: { minWidth: 0 },
+ standIn: {
+ backgroundColor: cssVar.colorWarningBg,
+ borderColor: cssVar.colorWarningBorder,
+ borderRadius: cssVar.borderRadiusSM,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ fontWeight: 500,
+ paddingBlock: 2,
+ paddingInline: 6,
+ },
+ warnIcon: { marginInlineEnd: 4, verticalAlign: '-2px' },
+});
+
+type Grid = ReturnType<typeof reviewGrid>;
+
+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);
+};
+
+export const Pair = ({
+ combo,
+ condition,
+ item,
+}: {
+ combo: number;
+ condition: string;
+ item: ReviewView;
+}) => (
+ <div {...stylex.props(styles.pair)}>
+ {sidesOf(item).map((side) => {
+ const notes = shotNotes(item, side);
+ return (
+ <Flexbox gap={4} key={side} {...stylex.props(styles.side)}>
+ <Text fontSize={12} type="secondary">
+ {SIDE_LABELS[side]}
+ </Text>
+ {notes.map((note) => (
+ <Text fontSize={12} key={note} type="warning" {...stylex.props(styles.standIn)}>
+ <TriangleAlert size={12} {...stylex.props(styles.warnIcon)} />
+ {note}
+ </Text>
+ ))}
+ <img
+ alt={`${SIDE_LABELS[side]} ${item.title}`}
+ loading="lazy"
+ src={cropShotUrl(item.key, side, condition, combo)}
+ {...stylex.props(styles.shot)}
+ />
+ </Flexbox>
+ );
+ })}
+ </div>
+);
+
+export const CellVerdict = ({
+ cell,
+ itemKey,
+}: {
+ cell: { differs: boolean; summary: string[] };
+ itemKey: string;
+}) => {
+ const verdict = cellVerdict(itemKey, cell);
+ const type =
+ verdict.tone === 'ok' ? 'success' : verdict.tone === 'error' ? 'danger' : 'secondary';
+ return (
+ <Text fontSize={12} type={type}>
+ {verdict.text}
+ </Text>
+ );
+};
+
+export const ShotGrid = ({
+ columns,
+ item,
+ rows,
+}: {
+ columns: Grid['columns'];
+ item: ReviewView;
+ rows: Grid['rows'];
+}) => (
+ <div {...stylex.props(styles.grid, styles.gridColumns(columns.length))}>
+ <div />
+ {columns.map((column) => (
+ <Text fontSize={12} key={column.label} type="secondary" {...stylex.props(styles.colHead)}>
+ {column.title}
+ </Text>
+ ))}
+ {rows.map((row) => [
+ <Text
+ fontSize={12}
+ key={`${row.index}-head`}
+ type="secondary"
+ {...stylex.props(styles.rowHead)}
+ >
+ {row.label}
+ </Text>,
+ ...row.cells.map((cell) => (
+ <div
+ data-differs={cell.differs || undefined}
+ key={`${row.index}-${cell.condition}`}
+ {...stylex.props(styles.cell, cell.differs && styles.diff)}
+ >
+ <Pair combo={cell.combo} condition={cell.condition} item={item} />
+ <CellVerdict cell={cell} itemKey={item.key} />
+ </div>
+ )),
+ ])}
+ </div>
+);
+
+export const Legend = () => (
+ <Flexbox horizontal align="center" gap={16} wrap="wrap">
+ <Flexbox horizontal align="center" gap={6}>
+ <span {...stylex.props(styles.checker(...REVEAL_COLORS.checker))} />
+ <Text fontSize={12} type="secondary">
+ 棋盘格:透明,没有背景
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={6}>
+ <span {...stylex.props(styles.dash(REVEAL_COLORS.element))} />
+ <Text fontSize={12} type="secondary">
+ 粉色虚线:这个元素的边界
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={6}>
+ <span {...stylex.props(styles.dash(REVEAL_COLORS.pseudo))} />
+ <Text fontSize={12} type="secondary">
+ 蓝色虚线:::before / ::after
+ </Text>
+ </Flexbox>
+ </Flexbox>
+);
diff --git a/packages/style-equivalence/src/report/ui/StyleDetails.tsx b/packages/style-equivalence/src/report/ui/StyleDetails.tsx
new file mode 100644
index 00000000000..418562e4c37
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/StyleDetails.tsx
@@ -0,0 +1,237 @@
+import { Accordion, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import type { ReviewView } from '../api';
+
+const styles = stylex.create({
+ block: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ cell: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ paddingBlock: 8,
+ paddingInline: 12,
+ verticalAlign: 'top',
+ },
+ code: {
+ color: cssVar.colorText,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ lineHeight: 1.7,
+ margin: 0,
+ overflowX: 'auto',
+ padding: 12,
+ whiteSpace: 'pre',
+ },
+ differs: { backgroundColor: cssVar.colorErrorBg },
+ group: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ color: cssVar.colorTextSecondary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 600,
+ paddingBlock: 8,
+ paddingInline: 12,
+ },
+ head: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ color: cssVar.colorTextTertiary,
+ fontSize: cssVar.fontSizeSM,
+ fontWeight: 500,
+ paddingBlock: 8,
+ paddingInline: 12,
+ textAlign: 'start',
+ },
+ line: { display: 'block' },
+ mono: { color: cssVar.colorText, fontFamily: cssVar.fontFamilyCode, fontSize: cssVar.fontSizeSM },
+ pane: { minWidth: 0 },
+ paneHead: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ color: cssVar.colorTextTertiary,
+ fontSize: cssVar.fontSizeSM,
+ paddingBlock: 8,
+ paddingInline: 12,
+ },
+ panes: { display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))' },
+ paneSplit: {
+ borderInlineStartColor: cssVar.colorBorderSecondary,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartWidth: 1,
+ },
+ standIn: { fontFamily: cssVar.fontFamily, fontWeight: 400, marginInlineStart: 12 },
+ swatch: (color: string) => ({
+ backgroundColor: color,
+ borderColor: cssVar.colorBorder,
+ borderRadius: 3,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ display: 'inline-block',
+ height: 10,
+ marginInlineEnd: 6,
+ verticalAlign: '-1px',
+ width: 10,
+ }),
+ table: { borderCollapse: 'collapse', fontSize: cssVar.fontSizeSM, width: '100%' },
+});
+
+const COLOR_TOKEN = /:\s*(color[A-Z]\w*)$/;
+
+const tokenVar = (name: string) =>
+ `var(--lobe-${name.replaceAll(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)})`;
+
+const Lines = ({ label, lines }: { label: string; lines: string[] }) =>
+ lines.length ? (
+ <>
+ {lines.map((line) => {
+ const color = COLOR_TOKEN.exec(line)?.[1];
+ return (
+ <span key={line} {...stylex.props(styles.line)}>
+ {color && <i {...stylex.props(styles.swatch(tokenVar(color)))} />}
+ {line.startsWith(`${label.split(' ').pop()}: `)
+ ? line.slice(line.indexOf(': ') + 2)
+ : line}
+ </span>
+ );
+ })}
+ </>
+ ) : (
+ <Text fontSize={12} type="secondary">
+ 没有写
+ </Text>
+ );
+
+const RESULT = {
+ differs: { text: '不一样', type: 'danger' },
+ oneSided: { text: '只写在一边,渲染一致', type: 'warning' },
+ same: { text: '一致', type: 'success' },
+} as const;
+
+const DeclarationTable = ({ blocks }: { blocks: ReviewView['styles']['blocks'] }) => (
+ <div {...stylex.props(styles.block)}>
+ <table {...stylex.props(styles.table)}>
+ <thead>
+ <tr>
+ <th {...stylex.props(styles.head)}>属性</th>
+ <th {...stylex.props(styles.head)}>改之前</th>
+ <th {...stylex.props(styles.head)}>改之后</th>
+ <th {...stylex.props(styles.head)}>渲染结果</th>
+ </tr>
+ </thead>
+ {blocks.map((block) => (
+ <tbody key={block.slot}>
+ <tr>
+ <td colSpan={4} {...stylex.props(styles.group)}>
+ {block.slot}
+ {block.standIn && (
+ <Text as="span" fontSize={12} type="warning" {...stylex.props(styles.standIn)}>
+ 按替身渲染:没有加载 {block.standIn}{' '}
+ 自带的样式,这一块的「一致」只说明我们写的样式没变
+ </Text>
+ )}
+ </td>
+ </tr>
+ {block.rows.map((row) => {
+ const result = RESULT[row.differs ? 'differs' : row.oneSided ? 'oneSided' : 'same'];
+ return (
+ <tr key={row.label} {...stylex.props(row.differs && styles.differs)}>
+ <td {...stylex.props(styles.cell, styles.mono)}>{row.label}</td>
+ <td {...stylex.props(styles.cell, styles.mono)}>
+ <Lines label={row.label} lines={row.before} />
+ </td>
+ <td {...stylex.props(styles.cell, styles.mono)}>
+ <Lines label={row.label} lines={row.after} />
+ </td>
+ <td {...stylex.props(styles.cell)}>
+ <Text fontSize={12} type={result.type}>
+ {result.text}
+ </Text>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ ))}
+ </table>
+ </div>
+);
+
+const SourcePane = ({
+ children,
+ label,
+ split,
+}: {
+ children: string;
+ label: string;
+ split?: boolean;
+}) => (
+ <div {...stylex.props(styles.pane, split && styles.paneSplit)}>
+ <div {...stylex.props(styles.paneHead)}>{label}</div>
+ <pre {...stylex.props(styles.code)}>{children}</pre>
+ </div>
+);
+
+const SourceCompare = ({ styles: data }: { styles: ReviewView['styles'] }) => {
+ const slots = [
+ ...new Set([...Object.keys(data.source.base ?? {}), ...Object.keys(data.source.head ?? {})]),
+ ].sort();
+ const usage = (side: 'base' | 'head') =>
+ (data.usage[side] ?? ['(这一侧没有这个元素)']).join('\n');
+ 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="改之后">
+ {usage('head')}
+ </SourcePane>
+ </div>
+ </div>
+ {slots.map((slot) => (
+ <div key={slot} {...stylex.props(styles.block)}>
+ <div {...stylex.props(styles.group)}>{slot}</div>
+ <div {...stylex.props(styles.panes)}>
+ <SourcePane label="改之前">{data.source.base?.[slot] ?? '(没有)'}</SourcePane>
+ <SourcePane split label="改之后">
+ {data.source.head?.[slot] ?? '(没有)'}
+ </SourcePane>
+ </div>
+ </div>
+ ))}
+ </Flexbox>
+ );
+};
+
+export const StyleDetails = ({ item }: { item: ReviewView }) => {
+ const items = [
+ item.styles.blocks.length > 0 && {
+ children: (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type="secondary">
+ 两边都换成 CSS 属性名,按样式块对齐。渲染结果来自截图比对,不是看代码猜的。
+ </Text>
+ <DeclarationTable blocks={item.styles.blocks} />
+ </Flexbox>
+ ),
+ key: 'declarations',
+ title: '样式对照',
+ },
+ Object.keys(item.styles.usage).length > 0 && {
+ children: <SourceCompare styles={item.styles} />,
+ key: 'source',
+ title: '源码对照(原文不截断,调试用)',
+ },
+ ].filter((entry) => entry !== false);
+ if (!items.length) return null;
+ return <Accordion defaultValue={['declarations']} gap={8} items={items} variant="borderless" />;
+};
diff --git a/packages/style-equivalence/src/report/ui/ThemeToggle.tsx b/packages/style-equivalence/src/report/ui/ThemeToggle.tsx
new file mode 100644
index 00000000000..67ea7785e94
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/ThemeToggle.tsx
@@ -0,0 +1,42 @@
+import { ActionIcon, setLobeTheme } from '@lobehub/ui';
+import { Moon, Sun } from 'lucide-react';
+import { useEffect, useState, useSyncExternalStore } from 'react';
+
+type Appearance = 'dark' | 'light';
+
+const STORAGE_KEY = 'style-eq:appearance';
+const DARK_QUERY = '(prefers-color-scheme: dark)';
+
+const stored = (): Appearance | undefined => {
+ const value = localStorage.getItem(STORAGE_KEY);
+ return value === 'dark' || value === 'light' ? value : undefined;
+};
+
+const systemAppearance = (): Appearance => (matchMedia(DARK_QUERY).matches ? 'dark' : 'light');
+
+export const initialAppearance = () => stored() ?? systemAppearance();
+
+const subscribeSystem = (listener: () => void) => {
+ const media = matchMedia(DARK_QUERY);
+ media.addEventListener('change', listener);
+ return () => media.removeEventListener('change', listener);
+};
+
+export const ThemeToggle = () => {
+ const system = useSyncExternalStore(subscribeSystem, systemAppearance);
+ const [chosen, setChosen] = useState(stored);
+ const appearance = chosen ?? system;
+ useEffect(() => setLobeTheme({ appearance }), [appearance]);
+ const next = appearance === 'dark' ? 'light' : 'dark';
+ return (
+ <ActionIcon
+ icon={appearance === 'dark' ? Moon : Sun}
+ size="small"
+ title={next === 'dark' ? '切换到暗色' : '切换到亮色'}
+ onClick={() => {
+ localStorage.setItem(STORAGE_KEY, next);
+ setChosen(next);
+ }}
+ />
+ );
+};
diff --git a/packages/style-equivalence/src/report/ui/TopBar.tsx b/packages/style-equivalence/src/report/ui/TopBar.tsx
new file mode 100644
index 00000000000..654856bb991
--- /dev/null
+++ b/packages/style-equivalence/src/report/ui/TopBar.tsx
@@ -0,0 +1,129 @@
+import { Flexbox, Segmented, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowRight } from 'lucide-react';
+
+import type { FollowInfo, RunPayload } from '../api';
+import { CATEGORY_LABELS } from '../labels';
+import { hrefOf } from '../route';
+import { RunBadge } from './RunBadge';
+import { ThemeToggle } from './ThemeToggle';
+
+const styles = stylex.create({
+ bar: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorBgContainer,
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ columnGap: 16,
+ display: 'flex',
+ flex: 'none',
+ height: 52,
+ paddingInline: 20,
+ },
+ brand: {
+ color: cssVar.colorText,
+ fontSize: cssVar.fontSize,
+ fontWeight: 600,
+ textDecorationLine: 'none',
+ },
+ nav: { alignSelf: 'center' },
+ spacer: { flex: '1' },
+ strip: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorBgContainer,
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ columnGap: 16,
+ display: 'flex',
+ flex: 'none',
+ flexWrap: 'wrap',
+ minHeight: 40,
+ paddingBlock: 8,
+ paddingInline: 20,
+ rowGap: 4,
+ },
+});
+
+export type Section = 'method' | 'overview' | 'review';
+
+const SECTIONS: Array<{ label: string; value: Section }> = [
+ { label: '总览', value: 'overview' },
+ { label: '复查', value: 'review' },
+ { label: '方法依据', value: 'method' },
+];
+
+const SECTION_HREFS: Record<Section, string> = {
+ method: hrefOf({ kind: 'method' }),
+ overview: hrefOf({ kind: 'overview' }),
+ review: hrefOf({ kind: 'review' }),
+};
+
+export const TopBar = ({
+ base,
+ follow,
+ head,
+ section,
+}: {
+ base: string;
+ follow?: FollowInfo;
+ head: string;
+ section: Section;
+}) => (
+ <header {...stylex.props(styles.bar)}>
+ <a href={hrefOf({ kind: 'overview' })} {...stylex.props(styles.brand)}>
+ style-equivalence
+ </a>
+ <Flexbox horizontal align="center" gap={6}>
+ <Text code fontSize={12}>
+ {base.slice(0, 7)}
+ </Text>
+ <ArrowRight aria-label="到" size={12} />
+ <Text code fontSize={12}>
+ {head.slice(0, 7)}
+ </Text>
+ </Flexbox>
+ <RunBadge follow={follow} />
+ <div {...stylex.props(styles.spacer)} />
+ <Segmented
+ className={stylex.props(styles.nav).className}
+ options={SECTIONS}
+ size="small"
+ value={section}
+ onChange={(value) => {
+ location.hash = SECTION_HREFS[value];
+ }}
+ />
+ <ThemeToggle />
+ </header>
+);
+
+export const VerdictStrip = ({ payload }: { payload: RunPayload }) => {
+ const { cases, mutation, verdict } = payload;
+ const count = (category: string) => cases.filter((entry) => entry.category === category).length;
+ const unpaired = verdict.items.filter((item) => item.category === 'unpaired').length;
+ const files = new Set(cases.map((entry) => entry.plan.file)).size;
+ const parts = [
+ `${CATEGORY_LABELS.difference} ${count('difference')}`,
+ `${CATEGORY_LABELS['needs-signoff']} ${count('needs-signoff') + unpaired}`,
+ `${CATEGORY_LABELS.blocking} ${count('blocking')}`,
+ `${CATEGORY_LABELS.equal} ${count('equal')}`,
+ `共 ${cases.length} 个用例、${files} 个文件`,
+ mutation.requested ? `变异 ${mutation.caught}/${mutation.evaluated}` : '变异未运行',
+ ];
+ return (
+ <div {...stylex.props(styles.strip)}>
+ <Text strong type={verdict.mergeable ? 'success' : 'danger'}>
+ {verdict.mergeable ? '可以合并' : '还不能合并'}
+ </Text>
+ <Text type="secondary">{parts.join(' · ')}</Text>
+ {!verdict.mergeable && (
+ <Text fontSize={12} type="secondary">
+ 原因:{verdict.reasons.join(';')}
+ </Text>
+ )}
+ </div>
+ );
+};
diff --git a/packages/style-equivalence/src/review/declarations.test.ts b/packages/style-equivalence/src/review/declarations.test.ts
new file mode 100644
index 00000000000..1e32d05d4db
--- /dev/null
+++ b/packages/style-equivalence/src/review/declarations.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+
+import { declarationBlocks, parseDeclarations } from './declarations';
+
+const emotion = `chip: css\`
+ overflow: hidden;
+ padding-block: 2px;
+ padding-inline: 8px;
+ color: \${cssVar.colorTextSecondary};
+ background: \${cssVar.colorFillTertiary};
+
+ &:not(:last-child) {
+ border-block-end: 1px solid \${cssVar.colorBorderSecondary};
+ }
+ \``;
+
+const stylex = `chip: {
+ overflow: 'hidden',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ borderBlockEndWidth: { 'default': null, ':not(:last-child)': '1px' },
+ borderBlockEndStyle: { 'default': null, ':not(:last-child)': 'solid' },
+ borderBlockEndColor: { 'default': null, ':not(:last-child)': cssVar.colorBorderSecondary },
+ fontSize: 12,
+ }`;
+
+describe('parseDeclarations', () => {
+ it('reads an emotion block with tokens and nested selectors', () => {
+ expect(parseDeclarations(emotion)).toEqual([
+ { property: 'overflow', selector: '', value: 'hidden' },
+ { property: 'padding-block', selector: '', value: '2px' },
+ { property: 'padding-inline', selector: '', value: '8px' },
+ { property: 'color', selector: '', value: 'colorTextSecondary' },
+ { property: 'background', selector: '', value: 'colorFillTertiary' },
+ {
+ property: 'border-block-end',
+ selector: ':not(:last-child)',
+ value: '1px solid colorBorderSecondary',
+ },
+ ]);
+ });
+
+ it('reads a stylex object with conditional values', () => {
+ const rows = parseDeclarations(stylex);
+ expect(rows).toContainEqual({ property: 'background-image', selector: '', value: 'none' });
+ expect(rows).toContainEqual({ property: 'font-size', selector: '', value: '12' });
+ expect(rows).toContainEqual({
+ property: 'border-block-end-color',
+ selector: ':not(:last-child)',
+ value: 'colorBorderSecondary',
+ });
+ expect(
+ rows.some((row) => row.property === 'border-block-end-width' && row.selector === ''),
+ ).toBe(false);
+ });
+
+ it('keeps a composed style that stands alone on a line', () => {
+ const text =
+ 'root: css`\n /* note */\n ${groupStyles.shiny}\n\n overflow: hidden;\n `';
+ expect(parseDeclarations(text)).toEqual([
+ { property: 'composes', selector: '', value: 'groupStyles.shiny' },
+ { property: 'overflow', selector: '', value: 'hidden' },
+ ]);
+ });
+
+ it('returns nothing instead of throwing on broken css', () => {
+ expect(parseDeclarations('root: css`\n color: red;;; {{\n `')).toEqual([]);
+ });
+
+ it('reads a stylex pseudo-element block as a selector, not a property', () => {
+ const rows = parseDeclarations(
+ "header: {\n 'height': '44px',\n '::before': {\n content: '\"\"',\n zIndex: -1,\n height: 'var(--bar)',\n },\n}",
+ );
+ expect(rows).toEqual([
+ { property: 'height', selector: '', value: '44px' },
+ { property: 'content', selector: '::before', value: '""' },
+ { property: 'z-index', selector: '::before', value: '-1' },
+ { property: 'height', selector: '::before', value: 'var(--bar)' },
+ ]);
+ });
+
+ it('keeps non-token interpolations readable on both sides', () => {
+ expect(parseDeclarations('a: css`\n height: ${HEADER_HEIGHT}px;\n `')).toEqual([
+ { property: 'height', selector: '', value: '${HEADER_HEIGHT}px' },
+ ]);
+ expect(parseDeclarations('a: { height: `${HEADER_HEIGHT}px` }')).toEqual([
+ { property: 'height', selector: '', value: '${HEADER_HEIGHT}px' },
+ ]);
+ });
+
+ it('returns nothing for text it cannot read', () => {
+ expect(parseDeclarations('chip: someHelper()')).toEqual([]);
+ });
+});
+
+describe('declarationBlocks', () => {
+ it('marks a family written on only one side', () => {
+ const [block] = declarationBlocks(
+ {
+ 'styles.h': 'h: css`\n color: red;\n > * {\n pointer-events: auto;\n }\n `',
+ },
+ { 'styles.h': "h: { color: 'red' }" },
+ );
+ expect(block.rows.find((row) => row.label === '> * pointer-events')).toMatchObject({
+ oneSided: true,
+ });
+ expect(block.rows.find((row) => row.label === 'color')).toMatchObject({ oneSided: false });
+ });
+
+ it('aligns both sides by property family per style block and marks differing families', () => {
+ const [block] = declarationBlocks({ 'styles.chip': emotion }, { 'styles.chip': stylex }, [
+ 'border-block-end-color',
+ ]);
+ expect(block.slot).toBe('chip');
+ const background = block.rows.find((row) => row.label === 'background');
+ expect(background).toMatchObject({
+ after: ['background-color: colorFillTertiary', 'background-image: none'],
+ before: ['background: colorFillTertiary'],
+ differs: false,
+ });
+ const border = block.rows.find((row) => row.label === ':not(:last-child) border');
+ expect(border?.differs).toBe(true);
+ expect(block.rows.find((row) => row.label === 'font-size')).toMatchObject({
+ after: ['font-size: 12'],
+ before: [],
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/review/declarations.ts b/packages/style-equivalence/src/review/declarations.ts
new file mode 100644
index 00000000000..0433f9a8bb5
--- /dev/null
+++ b/packages/style-equivalence/src/review/declarations.ts
@@ -0,0 +1,209 @@
+import postcss, { type ChildNode } from 'postcss';
+import ts from 'typescript';
+
+export interface Declaration {
+ property: string;
+ selector: string;
+ value: string;
+}
+
+export interface DeclarationRow {
+ after: string[];
+ before: string[];
+ differs: boolean;
+ label: string;
+ oneSided: boolean;
+}
+
+export interface DeclarationBlock {
+ key: string;
+ rows: DeclarationRow[];
+ slot: string;
+}
+
+const kebab = (name: string) => name.replaceAll(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
+
+const token = (text: string) => {
+ const trimmed = text.trim();
+ return trimmed.startsWith('cssVar.') ? trimmed.slice('cssVar.'.length) : `\${${trimmed}}`;
+};
+
+const PLACEHOLDER = /__I(\d+)__/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) => {
+ for (const node of nodes) {
+ if (node.type === 'decl')
+ rows.push({ property: node.prop, selector: scope, value: restore(node.value.trim()) });
+ else if (node.type === 'rule')
+ walk(node.nodes, `${scope}${node.selector.replace(/^&/, '').trim()}`.trim());
+ else if (node.type === 'atrule')
+ walk(node.nodes ?? [], `${scope} @${node.name} ${node.params}`.trim());
+ }
+ };
+ walk(postcss.parse(css).nodes, selector);
+ return rows;
+};
+
+const fromEmotion = (template: string) => {
+ const composed = template.replaceAll(
+ /^(\s*)\$\{([^{}]*)\}\s*;?\s*$/gm,
+ (_match, indent: string, inner: string) => `${indent}composes: ${inner.trim()};`,
+ );
+ const interpolations: string[] = [];
+ const masked = composed.replaceAll(/\$\{([^{}]*)\}/g, (_match, inner: string) => {
+ const text = token(inner);
+ if (!text.startsWith('${')) return text;
+ interpolations.push(text);
+ return `__I${interpolations.length - 1}__`;
+ });
+ try {
+ return fromCss(masked, '', (value) =>
+ value.replaceAll(PLACEHOLDER, (_match, index: string) => interpolations[Number(index)]),
+ );
+ } catch {
+ return [];
+ }
+};
+
+const fromCssModule = (text: string) => {
+ const rows: Declaration[] = [];
+ postcss.parse(text).walkRules((rule) => {
+ if (rule.parent?.type === 'rule') return;
+ const scope = rule.selector.replace(/^\.[\w-]+/, '').trim();
+ rows.push(...fromCss(rule.nodes.map(String).join(';'), scope));
+ });
+ return rows;
+};
+
+const expressionText = (node: ts.Expression, source: ts.SourceFile): string | undefined => {
+ if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) return node.text;
+ if (ts.isPrefixUnaryExpression(node)) return node.getText(source);
+ if (ts.isPropertyAccessExpression(node)) return node.getText(source).replace(/^cssVar\./, '');
+ if (ts.isTemplateExpression(node))
+ return [
+ node.head.text,
+ ...node.templateSpans.map(
+ (span) => `${token(span.expression.getText(source))}${span.literal.text}`,
+ ),
+ ].join('');
+ return node.kind === ts.SyntaxKind.NullKeyword ? undefined : node.getText(source);
+};
+
+const keyText = (name: ts.PropertyName) =>
+ ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)
+ ? name.text
+ : undefined;
+
+const fromObject = (
+ object: ts.ObjectLiteralExpression,
+ source: ts.SourceFile,
+ property?: string,
+ selector = '',
+) => {
+ const rows: Declaration[] = [];
+ for (const member of object.properties) {
+ if (!ts.isPropertyAssignment(member)) continue;
+ const key = keyText(member.name);
+ if (key === undefined) continue;
+ if (property === undefined) {
+ if (/^[:@]/.test(key) && ts.isObjectLiteralExpression(member.initializer))
+ rows.push(...fromObject(member.initializer, source, undefined, scopeOf(selector, key)));
+ else if (ts.isObjectLiteralExpression(member.initializer))
+ rows.push(...fromObject(member.initializer, source, kebab(key), selector));
+ else {
+ const value = expressionText(member.initializer, source);
+ if (value !== undefined) rows.push({ property: kebab(key), selector, value });
+ }
+ continue;
+ }
+ const scope = key === 'default' ? selector : scopeOf(selector, key);
+ if (ts.isObjectLiteralExpression(member.initializer))
+ rows.push(...fromObject(member.initializer, source, property, scope));
+ else {
+ const value = expressionText(member.initializer, source);
+ if (value !== undefined) rows.push({ property, selector: scope, value });
+ }
+ }
+ return rows;
+};
+
+export const parseDeclarations = (text: string): Declaration[] => {
+ const emotion = /^[\w$]+\s*:\s*css`([\s\S]*)`\s*$/.exec(text.trim());
+ if (emotion) return fromEmotion(emotion[1]);
+ if (/^[.#@]/.test(text.trim())) {
+ try {
+ return fromCssModule(text);
+ } catch {
+ return [];
+ }
+ }
+ const source = ts.createSourceFile('slot.ts', `({${text}})`, ts.ScriptTarget.Latest, true);
+ const [statement] = source.statements;
+ if (!statement || !ts.isExpressionStatement(statement)) return [];
+ const outer = ts.isParenthesizedExpression(statement.expression)
+ ? statement.expression.expression
+ : undefined;
+ if (!outer || !ts.isObjectLiteralExpression(outer)) return [];
+ const [member] = outer.properties;
+ if (
+ !member ||
+ !ts.isPropertyAssignment(member) ||
+ !ts.isObjectLiteralExpression(member.initializer)
+ )
+ return [];
+ return fromObject(member.initializer, source);
+};
+
+const family = (property: string) => {
+ if (property.startsWith('background')) return 'background';
+ if (/^border(-.+)?-radius$/.test(property)) return 'border-radius';
+ if (property.startsWith('border')) return 'border';
+ if (property.startsWith('padding')) return 'padding';
+ if (property.startsWith('margin')) return 'margin';
+ if (property.startsWith('inset') || ['top', 'right', 'bottom', 'left'].includes(property))
+ return 'inset';
+ if (property === 'flex' || /^flex-(grow|shrink|basis)$/.test(property)) return 'flex';
+ return property;
+};
+
+export const slotName = (key: string) => key.slice(key.lastIndexOf('.') + 1);
+
+export const declarationBlocks = (
+ before: Record<string, string> = {},
+ after: Record<string, string> = {},
+ differing: string[] = [],
+): DeclarationBlock[] => {
+ const changed = new Set(differing.map(family));
+ const slots = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort();
+ return slots.map((slot) => {
+ const rows = new Map<string, DeclarationRow>();
+ const add = (side: 'after' | 'before', text?: string) => {
+ for (const { property, selector, value } of text ? parseDeclarations(text) : []) {
+ const name = family(property);
+ const label = selector ? `${selector} ${name}` : name;
+ const row = rows.get(label) ?? {
+ after: [],
+ before: [],
+ differs: changed.has(name),
+ label,
+ oneSided: false,
+ };
+ row[side].push(`${property}: ${value}`);
+ rows.set(label, row);
+ }
+ };
+ add('before', before[slot]);
+ add('after', after[slot]);
+ for (const row of rows.values()) row.oneSided = !row.before.length || !row.after.length;
+ return {
+ key: slot,
+ rows: [...rows.values()].sort((a, b) => Number(b.differs) - Number(a.differs)),
+ slot: slotName(slot),
+ };
+ });
+};
diff --git a/packages/style-equivalence/src/review/state.test.ts b/packages/style-equivalence/src/review/state.test.ts
new file mode 100644
index 00000000000..b2776d26680
--- /dev/null
+++ b/packages/style-equivalence/src/review/state.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from 'vitest';
+
+import { decideVerdict, type VerdictItem } from '../verdict';
+import { passRecord, resolvedReworks, reviewItems, reworkRecord } from './state';
+import type { Reviews, ReworkRecord } from './store';
+
+const item = (overrides: Partial<VerdictItem> = {}): VerdictItem => ({
+ category: 'needs-signoff',
+ file: 'src/A.tsx',
+ flags: ['VARIABLE_UNMODELED'],
+ hash: 'h1',
+ key: 'src/A.tsx|A#0',
+ ...overrides,
+});
+
+const empty = (): Reviews => ({ notes: new Map(), passes: new Map(), reworks: new Map() });
+
+const verdictOf = (items: VerdictItem[], reviews: Reviews) =>
+ decideVerdict({
+ calibration: [],
+ items,
+ mutation: { passed: true },
+ reworks: reviews.reworks,
+ signoffs: reviews.passes,
+ });
+
+const context = (combos = 2, signature = 'span|styles.dot') => ({
+ combos: new Map([['src/A.tsx|A#0', combos]]),
+ signatures: new Map([['src/A.tsx|A#0', signature]]),
+});
+
+const rework = (hash = 'h1', signature = 'span|styles.dot'): ReworkRecord => ({
+ at: 'now',
+ base: 'b',
+ elementSignature: signature,
+ file: 'src/A.tsx',
+ hash,
+ head: 'h',
+ key: 'src/A.tsx|A#0',
+ note: '在线时多了灰边',
+ reviewer: 'innei',
+ runId: 'r1',
+});
+
+const stateOf = (items: VerdictItem[], reviews: Reviews, ctx = context()) =>
+ reviewItems(verdictOf(items, reviews).items, reviews, ctx)[0]?.state;
+
+describe('review state', () => {
+ it('moves from todo to reworked, to changed when the source changes, to passed', () => {
+ const reviews = empty();
+ expect(stateOf([item()], reviews)).toBe('todo');
+ reviews.reworks.set('src/A.tsx|A#0', rework());
+ expect(stateOf([item()], reviews)).toBe('reworked');
+ expect(stateOf([item({ hash: 'h2' })], reviews)).toBe('changed');
+ const [changed] = reviewItems(
+ verdictOf([item({ hash: 'h2' })], reviews).items,
+ reviews,
+ context(),
+ );
+ reviews.passes.set(changed.key, passRecord(changed, '', 'innei', 'now'));
+ expect(stateOf([item({ hash: 'h2' })], reviews)).toBe('passed');
+ });
+
+ it('shows a send-back made after a pass as reworked', () => {
+ const reviews = empty();
+ const [entry] = reviewItems(verdictOf([item()], reviews).items, reviews, context());
+ reviews.passes.set(entry.key, passRecord(entry, '', 'innei', '2026-11-05T01:00:00Z'));
+ reviews.reworks.set(entry.key, { ...rework(), at: '2026-11-05T02:00:00Z' });
+ expect(stateOf([item()], reviews)).toBe('reworked');
+ });
+
+ it('keeps a file-level send-back as reworked when neither side has an element signature', () => {
+ const reviews = empty();
+ const fileItem = item({ flags: ['STYLE_OUTSIDE_JSX'], key: 'src/A.tsx|file' });
+ reviews.reworks.set(fileItem.key, { ...rework(), elementSignature: '', key: fileItem.key });
+ const ctx = { combos: new Map<string, number>(), signatures: new Map<string, string>() };
+ expect(reviewItems(verdictOf([fileItem], reviews).items, reviews, ctx)[0].state).toBe(
+ 'reworked',
+ );
+ });
+
+ it('marks a rework changed when the element at that key is a different element', () => {
+ const reviews = empty();
+ reviews.reworks.set('src/A.tsx|A#0', rework('h1', 'div|styles.card'));
+ expect(stateOf([item()], reviews)).toBe('changed');
+ });
+
+ it('one pass covers every flag of the item', () => {
+ const reviews = empty();
+ const [entry] = reviewItems(
+ verdictOf([item({ flags: ['VARIABLE_UNMODELED', 'CROSS_COMPONENT'] })], reviews).items,
+ reviews,
+ context(),
+ );
+ const record = passRecord(entry, '', 'innei', 'now');
+ expect(record.reasons).toEqual(['CROSS_COMPONENT', 'VARIABLE_UNMODELED']);
+ expect(record.note).toBe('复查通过');
+ reviews.passes.set(record.key, record);
+ expect(
+ verdictOf([item({ flags: ['VARIABLE_UNMODELED', 'CROSS_COMPONENT'] })], reviews).mergeable,
+ ).toBe(true);
+ });
+
+ it('never lets a difference without flags pass', () => {
+ const reviews = empty();
+ const [entry] = reviewItems(
+ verdictOf([item({ category: 'difference', flags: [] })], reviews).items,
+ reviews,
+ context(),
+ );
+ expect(entry.canPass).toBe(false);
+ expect(() => passRecord(entry, '看过了', 'innei', 'now')).toThrow('CANNOT_PASS');
+ });
+
+ it('requires a note to pass a flagged difference', () => {
+ const reviews = empty();
+ const [entry] = reviewItems(
+ verdictOf([item({ category: 'difference', flags: ['CROSS_COMPONENT'] })], reviews).items,
+ reviews,
+ context(),
+ );
+ expect(() => passRecord(entry, ' ', 'innei', 'now')).toThrow('NOTE_REQUIRED');
+ expect(passRecord(entry, '工具误报', 'innei', 'now').reasons).toEqual(['TOOL_FALSE_POSITIVE']);
+ });
+
+ it('blocks the merge while a rework is open', () => {
+ const reviews = empty();
+ const [entry] = reviewItems(verdictOf([item()], reviews).items, reviews, context());
+ reviews.passes.set(entry.key, passRecord(entry, '', 'innei', 'now'));
+ reviews.reworks.set(entry.key, rework());
+ expect(verdictOf([item()], reviews).reasons).toContain('rework open 1');
+ });
+
+ it('requires a note for a rework', () => {
+ const [entry] = reviewItems(verdictOf([item()], empty()).items, empty(), context());
+ const meta = { base: 'b', head: 'h', reviewer: 'innei', runId: 'r1', signature: 's' };
+ expect(() => reworkRecord(entry, { ...meta, note: '' }, 'now')).toThrow('NOTE_REQUIRED');
+ expect(reworkRecord(entry, { ...meta, note: '灰边' }, 'now').elementSignature).toBe('s');
+ });
+
+ it('waits for the agent on items with nothing to observe until a current note exists', () => {
+ const reviews = empty();
+ const placement = item({ flags: ['PLACEMENT_SUBSTITUTED'] });
+ expect(stateOf([placement], reviews)).toBe('waiting-agent');
+ expect(stateOf([item()], reviews, context(1))).toBe('waiting-agent');
+ reviews.notes.set(placement.key, {
+ at: 'now',
+ finding: 'f',
+ hash: 'old',
+ key: placement.key,
+ suggestion: 'pass',
+ });
+ expect(stateOf([placement], reviews)).toBe('waiting-agent');
+ reviews.notes.set(placement.key, {
+ at: 'now',
+ finding: 'f',
+ hash: 'h1',
+ key: placement.key,
+ suggestion: 'pass',
+ });
+ expect(stateOf([placement], reviews)).toBe('todo');
+ });
+
+ it('lists blocking items with only the rework action', () => {
+ const [entry] = reviewItems(
+ verdictOf([item({ category: 'blocking', flags: [] })], empty()).items,
+ empty(),
+ context(),
+ );
+ expect(entry).toMatchObject({ canPass: false, state: 'todo' });
+ });
+
+ it('resolves a rework whose item no longer needs a person', () => {
+ const reviews = empty();
+ reviews.reworks.set('src/A.tsx|A#0', rework());
+ const resolved = resolvedReworks(
+ verdictOf([item({ category: 'equal', flags: [] })], reviews).items,
+ reviews,
+ 'now',
+ );
+ expect(resolved).toMatchObject([{ key: 'src/A.tsx|A#0', resolvedAt: 'now' }]);
+ });
+});
diff --git a/packages/style-equivalence/src/review/state.ts b/packages/style-equivalence/src/review/state.ts
new file mode 100644
index 00000000000..06d7cbd0522
--- /dev/null
+++ b/packages/style-equivalence/src/review/state.ts
@@ -0,0 +1,153 @@
+import type { StyleElement } from '../extract';
+import type { SignoffRecord } from '../signoff/store';
+import { allowedReasons, type Verdict } from '../verdict';
+import type { AgentNote, Reviews, ReworkRecord } from './store';
+
+export type ReviewState = 'changed' | 'passed' | 'reworked' | 'todo' | 'waiting-agent';
+
+export const REVIEW_PASS = 'REVIEW_PASS';
+
+const AGENT_FLAGS = new Set([
+ 'CONTAINER_UNMODELED',
+ 'GLOBAL_RULES_CHANGED',
+ 'MEDIA_UNMODELED',
+ 'PLACEMENT_NEUTRAL_PROP',
+ 'PLACEMENT_SUBSTITUTED',
+ 'PSEUDO_UNMODELED',
+ 'STATE_UNMODELED',
+ 'STYLESHEET_UNPARSEABLE',
+ 'STYLESHEET_UNREADABLE',
+ 'STYLE_OUTSIDE_JSX',
+]);
+
+type VerdictEntry = Verdict['items'][number];
+
+export interface ReviewItem extends VerdictEntry {
+ canPass: boolean;
+ needsAgent: boolean;
+ note?: AgentNote;
+ rework?: ReworkRecord;
+ state: ReviewState;
+}
+
+export interface ReviewContext {
+ combos: Map<string, number>;
+ signatures: Map<string, string>;
+}
+
+export const elementSignature = (element: Pick<StyleElement, 'slots' | 'tag'>) =>
+ `${element.tag}|${[...element.slots].sort().join(',')}`;
+
+const needsPerson = (item: VerdictEntry) =>
+ item.category === 'blocking' || item.signoff !== 'not-needed';
+
+const needsAgent = (item: VerdictEntry, combos: number | undefined) =>
+ item.category === 'needs-signoff' &&
+ (item.flags.some((flag) => AGENT_FLAGS.has(flag.split(':')[0])) ||
+ (item.flags.includes('VARIABLE_UNMODELED') && (combos ?? 1) <= 1));
+
+const canPassItem = (item: VerdictEntry) =>
+ item.category !== 'blocking' && !(item.category === 'difference' && !item.flags.length);
+
+const stateOf = (
+ item: VerdictEntry,
+ agent: boolean,
+ rework: ReworkRecord | undefined,
+ note: AgentNote | undefined,
+ signature: string | undefined,
+ pass: SignoffRecord | undefined,
+): ReviewState => {
+ const passed = item.signoff === 'valid';
+ if (rework && (!passed || !pass || rework.at > pass.signedAt))
+ return rework.hash === item.hash && (rework.elementSignature || '') === (signature || '')
+ ? 'reworked'
+ : 'changed';
+ if (passed) return 'passed';
+ if (agent && note?.hash !== item.hash) return 'waiting-agent';
+ return 'todo';
+};
+
+export const reviewItems = (
+ items: VerdictEntry[],
+ reviews: Reviews,
+ context: ReviewContext,
+): ReviewItem[] =>
+ items.filter(needsPerson).map((item) => {
+ const agent = needsAgent(item, context.combos.get(item.key));
+ const rework = reviews.reworks.get(item.key);
+ const openRework = rework && !rework.resolvedAt ? rework : undefined;
+ const note = reviews.notes.get(item.key);
+ const state = stateOf(
+ item,
+ agent,
+ openRework,
+ note,
+ context.signatures.get(item.key),
+ reviews.passes.get(item.key),
+ );
+ return {
+ ...item,
+ canPass: canPassItem(item) && state !== 'waiting-agent',
+ needsAgent: agent,
+ ...(note?.hash === item.hash ? { note } : {}),
+ ...(openRework ? { rework: openRework } : {}),
+ state,
+ };
+ });
+
+export const passRecord = (
+ item: ReviewItem,
+ note: string,
+ reviewer: string,
+ now: string,
+): SignoffRecord => {
+ if (!item.canPass) throw new Error(`CANNOT_PASS:${item.key}`);
+ if (item.category === 'difference' && !note.trim()) throw new Error('NOTE_REQUIRED');
+ return {
+ hash: item.hash,
+ key: item.key,
+ note: note.trim() || '复查通过',
+ reason: REVIEW_PASS,
+ reasons: allowedReasons(item).sort(),
+ signedAt: now,
+ signer: reviewer,
+ };
+};
+
+export interface ReworkMeta {
+ base: string;
+ head: string;
+ note: string;
+ pr?: number;
+ reviewer: string;
+ runId: string;
+ signature: string;
+}
+
+export const reworkRecord = (item: ReviewItem, meta: ReworkMeta, now: string): ReworkRecord => {
+ if (!meta.note.trim()) throw new Error('NOTE_REQUIRED');
+ return {
+ at: now,
+ base: meta.base,
+ elementSignature: meta.signature,
+ file: item.file,
+ hash: item.hash,
+ head: meta.head,
+ key: item.key,
+ note: meta.note.trim(),
+ ...(meta.pr ? { pr: meta.pr } : {}),
+ reviewer: meta.reviewer,
+ runId: meta.runId,
+ };
+};
+
+export const resolvedReworks = (items: VerdictEntry[], reviews: Reviews, now: string) => {
+ const byKey = new Map(items.map((item) => [item.key, item]));
+ return [...reviews.reworks.values()]
+ .filter((rework) => !rework.resolvedAt)
+ .filter((rework) => {
+ const item = byKey.get(rework.key);
+ return !item || !needsPerson(item);
+ })
+ .map((rework) => ({ ...rework, resolvedAt: now }));
+};
diff --git a/packages/style-equivalence/src/review/store.test.ts b/packages/style-equivalence/src/review/store.test.ts
new file mode 100644
index 00000000000..a96b1ad8a23
--- /dev/null
+++ b/packages/style-equivalence/src/review/store.test.ts
@@ -0,0 +1,107 @@
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { readReviews, reviewPath, writeReviews } from './store';
+
+let records: string;
+
+beforeEach(async () => {
+ records = await mkdtemp(path.join(tmpdir(), 'se-reviews-'));
+});
+
+afterEach(async () => {
+ await rm(records, { force: true, recursive: true });
+});
+
+const pass = (key: string, hash = 'h1') => ({
+ hash,
+ key,
+ note: '复查通过',
+ reason: 'REVIEW_PASS',
+ reasons: ['PLACEMENT_SUBSTITUTED'],
+ signedAt: '2026-11-05T00:00:00Z',
+ signer: 'innei',
+});
+
+const rework = (key: string) => ({
+ at: '2026-11-05T00:00:00Z',
+ base: 'aaa',
+ elementSignature: 'span|styles.dot',
+ file: 'src/A.tsx',
+ hash: 'h1',
+ head: 'bbb',
+ key,
+ note: '在线时多了灰边',
+ reviewer: 'innei',
+ runId: 'run-1',
+});
+
+const note = (key: string) => ({
+ at: '2026-11-05T00:00:00Z',
+ finding: 'className 落在根 svg 上',
+ hash: 'h1',
+ key,
+ suggestion: 'pass' as const,
+});
+
+describe('review store', () => {
+ it('stores passes, reworks and agent notes under the records directory', async () => {
+ await writeReviews(records, 'src/A.tsx', {
+ notes: [note('src/A.tsx|A#1')],
+ passes: [pass('src/A.tsx|A#0')],
+ reworks: [rework('src/A.tsx|A#2')],
+ });
+ const stored = JSON.parse(await readFile(reviewPath(records, 'src/A.tsx'), 'utf8'));
+ expect(reviewPath(records, 'src/A.tsx')).toBe(path.join(records, 'reviews', 'src/A.tsx.json'));
+ expect(stored.passes).toHaveLength(1);
+ const reviews = await readReviews(records, ['src/A.tsx', 'src/A.tsx']);
+ expect(reviews.passes.get('src/A.tsx|A#0')?.note).toBe('复查通过');
+ expect(reviews.reworks.get('src/A.tsx|A#2')?.note).toBe('在线时多了灰边');
+ expect(reviews.notes.get('src/A.tsx|A#1')?.suggestion).toBe('pass');
+ });
+
+ it('merges later writes by key instead of overwriting the file', async () => {
+ await writeReviews(records, 'src/A.tsx', { passes: [pass('src/A.tsx|A#0')] });
+ await writeReviews(records, 'src/A.tsx', { reworks: [rework('src/A.tsx|A#2')] });
+ await writeReviews(records, 'src/A.tsx', { passes: [pass('src/A.tsx|A#0', 'h2')] });
+ const reviews = await readReviews(records, ['src/A.tsx']);
+ expect(reviews.passes.get('src/A.tsx|A#0')?.hash).toBe('h2');
+ expect(reviews.reworks.size).toBe(1);
+ });
+
+ it('keeps every record when writes to one file run concurrently', async () => {
+ await Promise.all(
+ ['A#0', 'A#1', 'A#2', 'A#3'].map((id) =>
+ writeReviews(records, 'src/A.tsx', { passes: [pass(`src/A.tsx|${id}`)] }),
+ ),
+ );
+ expect((await readReviews(records, ['src/A.tsx'])).passes.size).toBe(4);
+ });
+
+ it('keeps passes for different hashes and picks the one matching the current hash', async () => {
+ await writeReviews(records, 'src/A.tsx', { passes: [pass('src/A.tsx|A#0', 'h1')] });
+ await writeReviews(records, 'src/A.tsx', { passes: [pass('src/A.tsx|A#0', 'h2')] });
+ const scoped = await readReviews(records, ['src/A.tsx'], {
+ hashes: new Map([['src/A.tsx|A#0', 'h1']]),
+ });
+ expect(scoped.passes.get('src/A.tsx|A#0')?.hash).toBe('h1');
+ });
+
+ it('only reads reworks of the requested PR', async () => {
+ await writeReviews(records, 'src/A.tsx', { reworks: [{ ...rework('src/A.tsx|A#2'), pr: 1 }] });
+ await writeReviews(records, 'src/A.tsx', {
+ reworks: [{ ...rework('src/A.tsx|A#2'), note: 'PR 2 的原因', pr: 2 }],
+ });
+ const scoped = await readReviews(records, ['src/A.tsx'], { pr: 1 });
+ expect(scoped.reworks.get('src/A.tsx|A#2')?.pr).toBe(1);
+ expect((await readReviews(records, ['src/A.tsx'], { pr: 3 })).reworks.size).toBe(0);
+ });
+
+ it('reads an unknown file as empty', async () => {
+ const reviews = await readReviews(records, ['src/missing.tsx']);
+ expect(reviews.passes.size + reviews.reworks.size + reviews.notes.size).toBe(0);
+ });
+});
diff --git a/packages/style-equivalence/src/review/store.ts b/packages/style-equivalence/src/review/store.ts
new file mode 100644
index 00000000000..75d5dce81f8
--- /dev/null
+++ b/packages/style-equivalence/src/review/store.ts
@@ -0,0 +1,125 @@
+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { SignoffRecord } from '../signoff/store';
+
+export const REVIEWS_DIR = 'reviews';
+
+export interface ReworkRecord {
+ at: string;
+ base: string;
+ elementSignature: string;
+ file: string;
+ hash: string;
+ head: string;
+ key: string;
+ note: string;
+ pr?: number;
+ resolvedAt?: string;
+ reviewer: string;
+ runId: string;
+}
+
+export interface AgentNote {
+ at: string;
+ finding: string;
+ hash: string;
+ key: string;
+ suggestion: 'pass' | 'rework';
+}
+
+export interface ReviewFile {
+ notes: AgentNote[];
+ passes: SignoffRecord[];
+ reworks: ReworkRecord[];
+}
+
+export interface Reviews {
+ notes: Map<string, AgentNote>;
+ passes: Map<string, SignoffRecord>;
+ reworks: Map<string, ReworkRecord>;
+}
+
+export const reviewPath = (recordsDir: string, file: string) =>
+ path.join(recordsDir, REVIEWS_DIR, `${file}.json`);
+
+const readReviewFile = async (recordsDir: string, file: string): Promise<ReviewFile> => {
+ try {
+ const parsed = JSON.parse(await readFile(reviewPath(recordsDir, file), 'utf8'));
+ return {
+ notes: parsed.notes ?? [],
+ passes: parsed.passes ?? [],
+ reworks: parsed.reworks ?? [],
+ };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return { notes: [], passes: [], reworks: [] };
+ throw error;
+ }
+};
+
+export interface ReviewScope {
+ hashes?: Map<string, string>;
+ pr?: number;
+}
+
+export const reviewScope = (items: Array<{ hash: string; key: string }>, pr?: number) => ({
+ hashes: new Map(items.map((item) => [item.key, item.hash])),
+ pr,
+});
+
+const matchesHash = (scope: ReviewScope | undefined, record: { hash: string; key: string }) => {
+ const expected = scope?.hashes?.get(record.key);
+ return expected === undefined || expected === record.hash;
+};
+
+export const readReviews = async (
+ recordsDir: string,
+ files: string[],
+ scope?: ReviewScope,
+): Promise<Reviews> => {
+ const reviews: Reviews = { notes: new Map(), passes: new Map(), reworks: new Map() };
+ for (const file of new Set(files)) {
+ const stored = await readReviewFile(recordsDir, file);
+ for (const record of stored.passes)
+ if (matchesHash(scope, record)) reviews.passes.set(record.key, record);
+ for (const record of stored.notes)
+ if (matchesHash(scope, record)) reviews.notes.set(record.key, record);
+ for (const record of stored.reworks)
+ if (!scope || record.pr === scope.pr) reviews.reworks.set(record.key, record);
+ }
+ return reviews;
+};
+
+const hashId = (record: { hash: string; key: string }) => `${record.key}@${record.hash}`;
+const reworkId = (record: ReworkRecord) => `${record.key}@${record.pr ?? record.runId}`;
+
+const mergeById = <T>(current: T[], next: T[] = [], id: (record: T) => string) => {
+ const merged = new Map(current.map((record) => [id(record), record]));
+ for (const record of next) merged.set(id(record), record);
+ return [...merged].sort(([a], [b]) => a.localeCompare(b)).map(([, record]) => record);
+};
+
+const queues = new Map<string, Promise<unknown>>();
+
+const writeNow = async (recordsDir: string, file: string, patch: Partial<ReviewFile>) => {
+ const current = await readReviewFile(recordsDir, file);
+ const next: ReviewFile = {
+ notes: mergeById(current.notes, patch.notes, hashId),
+ passes: mergeById(current.passes, patch.passes, hashId),
+ reworks: mergeById(current.reworks, patch.reworks, reworkId),
+ };
+ const target = reviewPath(recordsDir, file);
+ await mkdir(path.dirname(target), { recursive: true });
+ const temporary = `${target}.${process.pid}.tmp`;
+ await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`);
+ await rename(temporary, target);
+};
+
+export const writeReviews = (recordsDir: string, file: string, patch: Partial<ReviewFile>) => {
+ const target = reviewPath(recordsDir, file);
+ const previous = queues.get(target) ?? Promise.resolve();
+ const next = previous.catch(() => undefined).then(() => writeNow(recordsDir, file, patch));
+ queues.set(target, next);
+ return next;
+};
diff --git a/packages/style-equivalence/src/run.test.ts b/packages/style-equivalence/src/run.test.ts
new file mode 100644
index 00000000000..ee47975c1c2
--- /dev/null
+++ b/packages/style-equivalence/src/run.test.ts
@@ -0,0 +1,94 @@
+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();
+
+beforeAll(async () => {
+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-e2e-'));
+ records = await mkdtemp(path.join(tmpdir(), 'style-eq-records-'));
+ await cp(path.join(fixtures, 'mini-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');
+ await writeFile(
+ path.join(repo, 'src/Card.module.css'),
+ '.card { padding: 10px; }\n.active { color: rgb(0, 0, 255); border-color: var(--ink-alias); }\n.title { font-weight: 600; color: var(--ink); }\n',
+ );
+ git('commit', '-qam', 'head');
+}, 30_000);
+
+afterAll(async () => {
+ await rm(repo, { force: true, recursive: true });
+ await rm(records, { force: true, recursive: true });
+});
+
+describe('runComparison', () => {
+ it('reports the padding change on the card and stores the evidence', async () => {
+ const result = await runComparison({
+ base: 'HEAD~1',
+ configFile: path.join(fixtures, 'mini-project/style-equivalence.config.ts'),
+ head: 'HEAD',
+ recordsDir: records,
+ repo,
+ });
+ expect(result.files).toEqual(['src/Card.tsx']);
+ const statuses = Object.fromEntries(
+ result.cases.map((entry) => [entry.key, entry.result.status]),
+ );
+ expect(statuses).toEqual({
+ 'src/Card.tsx|Card#0': 'difference',
+ 'src/Card.tsx|Card#1': 'equal',
+ });
+ const card = result.cases.find((entry) => entry.key === 'src/Card.tsx|Card#0')!;
+ expect(card.plan.combos).toEqual([{ active: false }, { active: true }]);
+ expect(
+ card.result.rootCauses.map((cause) => [cause.property, cause.before, cause.after]),
+ ).toEqual(expect.arrayContaining([['padding-block-start', '8px', '10px']]));
+ const stored = JSON.parse(await readFile(path.join(result.runDir, 'results.json'), 'utf8'));
+ expect(stored.cases).toHaveLength(2);
+ expect(git('worktree', 'list').split('\n')).toHaveLength(1);
+ expect(result.mutation).toMatchObject({ caught: 1, evaluated: 1, passed: true });
+ expect(result.verdict).toMatchObject({ mergeable: false, reasons: ['difference 1'] });
+ const [mutant] = result.mutation.mutants;
+ expect(mutant).toMatchObject({
+ caseKey: 'src/Card.tsx|Card#1',
+ operator: 'numeric',
+ outcome: 'caught',
+ });
+ expect(mutant.expected).toHaveLength(32);
+ expect(mutant.detected).toEqual(mutant.expected);
+ }, 180_000);
+
+ it('drops a token swap that resolves to the same value as an equivalent mutant', async () => {
+ const result = await runComparison({
+ base: 'HEAD~1',
+ configFile: path.join(fixtures, 'mini-project/style-equivalence.config.ts'),
+ head: 'HEAD',
+ mutationOperators: ['swap-token'],
+ recordsDir: records,
+ repo,
+ });
+ expect(result.mutation).toMatchObject({ equivalent: 1, evaluated: 0, passed: true });
+ expect(result.mutation.mutants[0]).toMatchObject({
+ expected: [],
+ operator: 'swap-token',
+ outcome: 'equivalent',
+ });
+ }, 180_000);
+});
diff --git a/packages/style-equivalence/src/run.ts b/packages/style-equivalence/src/run.ts
new file mode 100644
index 00000000000..163e975ad92
--- /dev/null
+++ b/packages/style-equivalence/src/run.ts
@@ -0,0 +1,289 @@
+import { execFile } from 'node:child_process';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { promisify } from 'node:util';
+
+import type { Browser } from '@playwright/test';
+
+import { type CaseResult, confirmDifferences, createRunAnalyzer, mergeRetry } from './analyze/diff';
+import { buildWithStubs } from './build/stubs';
+import { calibrate, type CalibrationResult } from './calibration';
+import { launchBrowser } from './capture/browser';
+import { captureRun, conditionFromLabel } from './capture/runner';
+import { serveDirectories } from './capture/staticServer';
+import type { ProjectConfig } from './config';
+import { createRunDir, writeEvidence } from './evidence/store';
+import type { MutationOperator } from './mutation/operators';
+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 { 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';
+
+const run = promisify(execFile);
+
+export const VERIFIER_VERSION = '2.14.0';
+export const DEFAULT_MUTATIONS = 10;
+
+export interface RunOptions {
+ base: string;
+ browser?: Browser;
+ calibrate?: boolean;
+ configFile: string;
+ head: string;
+ keepWorktrees?: boolean;
+ mutationOperators?: MutationOperator[];
+ mutations?: number;
+ pr?: PullRequestInfo;
+ recordsDir: string;
+ repo: string;
+ restrictTo?: string[];
+}
+
+export interface PullRequestInfo {
+ branch: string;
+ number: number;
+ title: string;
+}
+
+export interface CaseRecord {
+ category: CaseCategory;
+ key: string;
+ plan: PlanCase;
+ result: CaseResult;
+}
+
+export interface RunResult {
+ base: string;
+ calibration: CalibrationResult[];
+ cases: CaseRecord[];
+ comparisons: number;
+ durationMs: number;
+ files: string[];
+ head: string;
+ mutation: MutationReport;
+ plans: FilePlan[];
+ runDir: string;
+ runId: string;
+ unpaired: number;
+ verdict: Verdict;
+}
+
+const resolveSha = async (repo: string, revision: string) =>
+ (await run('git', ['-C', repo, 'rev-parse', '--verify', `${revision}^{commit}`])).stdout.trim();
+
+export const loadConfig = async (configFile: string) =>
+ (await import(pathToFileURL(configFile).href)).default as ProjectConfig;
+
+export const runComparison = async (options: RunOptions): Promise<RunResult> => {
+ const started = performance.now();
+ const config = await loadConfig(options.configFile);
+ const base = await resolveSha(options.repo, options.base);
+ const head = await resolveSha(options.repo, options.head);
+ const { runDir, runId } = await createRunDir(options.recordsDir, base, head);
+ const revisions = await prepareRevisions({ base, head, repo: options.repo, runDir });
+ const roots = { base: revisions.base.root, head: revisions.head.root };
+ let browser = options.browser;
+ const ownsBrowser = !browser;
+ try {
+ const { files: scope } = await resolveScope({
+ aliases: config.aliases,
+ base,
+ head,
+ repo: options.repo,
+ restrictTo: options.restrictTo,
+ });
+ const synthesis = await synthesize(scope, roots, config);
+ const configDir = path.dirname(options.configFile);
+ const hosts = {
+ base: await writeHost('base', roots.base, synthesis, scope, config, configDir),
+ head: await writeHost('head', roots.head, synthesis, scope, config, configDir),
+ };
+ const dists = { base: path.join(runDir, 'dist-base'), head: path.join(runDir, 'dist-head') };
+ await Promise.all(
+ (['base', 'head'] as const).map((side) =>
+ buildWithStubs(
+ {
+ configFile: options.configFile,
+ hostDir: hosts[side].host,
+ logFile: path.join(runDir, `build-${side}.log`),
+ outDir: dists[side],
+ root: roots[side],
+ },
+ hosts[side].written,
+ ),
+ ),
+ );
+ const server = await serveDirectories(runDir);
+ browser ??= await launchBrowser();
+ let capture;
+ let comparisons = 0;
+ let cases: CaseRecord[];
+ let mutation: MutationReport;
+ try {
+ const analyzer = createRunAnalyzer();
+ capture = await captureRun({
+ browser,
+ conditions: config.conditions,
+ onCondition: (condition) => {
+ comparisons += Object.keys(condition.head).length + (condition.identical?.length ?? 0);
+ analyzer.add(condition);
+ },
+ urls: { base: `${server.url}/dist-base/`, head: `${server.url}/dist-head/` },
+ });
+ const session = browser;
+ const retry = async (
+ results: CaseResult[],
+ conditionsOf: (result: CaseResult) => string[],
+ merge: (original: CaseResult, retry: CaseResult, conditions: string[]) => CaseResult,
+ ): Promise<CaseResult[]> => {
+ const targets = results.filter((result) => conditionsOf(result).length);
+ if (!targets.length) return results;
+ const keys = encodeURIComponent(JSON.stringify(targets.map((result) => result.key)));
+ const again = createRunAnalyzer();
+ await captureRun({
+ browser: session,
+ conditions: config.conditions,
+ onCondition: again.add,
+ plan: [...new Set(targets.flatMap(conditionsOf))].map(conditionFromLabel),
+ urls: {
+ base: `${server.url}/dist-base/#cases=${keys}`,
+ head: `${server.url}/dist-head/#cases=${keys}`,
+ },
+ });
+ const retried = new Map(again.finish().map((result) => [result.key, result]));
+ return results.map((result) => {
+ const second = retried.get(result.key);
+ const conditions = conditionsOf(result);
+ return conditions.length && second ? merge(result, second, conditions) : result;
+ });
+ };
+ const total = capture.conditions.length;
+ let analyzed = await retry(
+ analyzer.finish(capture.caseGaps),
+ (result) => result.unstableConditions,
+ mergeRetry,
+ );
+ analyzed = await retry(
+ analyzed,
+ (result) => (result.differingConditions.length < total ? result.differingConditions : []),
+ confirmDifferences,
+ );
+ const results = new Map(analyzed.map((result) => [result.key, result]));
+ cases = synthesis.plans.flatMap((plan) =>
+ plan.cases.map((entry) => {
+ const result =
+ results.get(entry.key) ??
+ ({
+ comboDifferences: [],
+ differingConditions: [],
+ errors: ['CASE_NOT_CAPTURED'],
+ gaps: [],
+ key: entry.key,
+ rootCauses: [],
+ status: 'error',
+ unstableConditions: [],
+ } satisfies CaseResult);
+ return { category: categorizeCase(entry, result), key: entry.key, plan: entry, result };
+ }),
+ );
+ const count = options.mutations ?? DEFAULT_MUTATIONS;
+ mutation = await runMutations({
+ browser,
+ candidates: count
+ ? planMutations({
+ aliases: config.aliases,
+ cases,
+ count,
+ extractions: synthesis.extractions,
+ headRoot: roots.head,
+ operators: options.mutationOperators,
+ scope,
+ seed: runId,
+ })
+ : [],
+ config,
+ configDir,
+ configFile: options.configFile,
+ count,
+ extractions: synthesis.extractions,
+ headRoot: roots.head,
+ plans: synthesis.plans,
+ runDir,
+ scope,
+ serverUrl: server.url,
+ states: capture.states ?? [],
+ widths: capture.widths,
+ });
+ } finally {
+ await server.close();
+ }
+ const calibration = await calibrate(
+ { base, cases, head, repo: options.repo, runDir },
+ options.calibrate === false ? undefined : config.calibration,
+ );
+ const { evidence, verdict } = await assembleVerdict({
+ aliases: config.aliases,
+ calibration,
+ cases,
+ extractions: synthesis.extractions,
+ mutation,
+ plans: synthesis.plans,
+ pr: options.pr?.number,
+ recordsDir: options.recordsDir,
+ roots,
+ scope,
+ unparsedSelectors: capture.unparsedSelectors,
+ verifierVersion: VERIFIER_VERSION,
+ });
+ const result: RunResult = {
+ base,
+ calibration,
+ cases,
+ comparisons,
+ durationMs: Math.round(performance.now() - started),
+ files: synthesis.plans.map((plan) => plan.file),
+ head,
+ mutation,
+ plans: synthesis.plans,
+ runDir,
+ runId,
+ unpaired: synthesis.plans.reduce((total, plan) => total + plan.unpaired.length, 0),
+ verdict,
+ };
+ await writeEvidence(runDir, 'run.json', {
+ base,
+ conditionConfig: config.conditions,
+ conditions: capture.conditions.map((condition) => condition.condition),
+ containerRules: capture.containerRules,
+ dependencyMode: revisions.dependencyMode,
+ durationMs: result.durationMs,
+ head,
+ pageErrors: capture.pageErrors,
+ ...(options.pr ? { pr: options.pr } : {}),
+ repo: options.repo,
+ runId,
+ scope,
+ states: capture.states,
+ unparsedMedia: capture.unparsedMedia,
+ unparsedSelectors: capture.unparsedSelectors,
+ verifierVersion: VERIFIER_VERSION,
+ widths: capture.widths,
+ });
+ await writeEvidence(runDir, 'plan.json', synthesis.plans);
+ await writeEvidence(runDir, 'extractions.json', synthesis.extractions);
+ await writeEvidence(runDir, 'mutation.json', mutation);
+ await writeEvidence(runDir, 'calibration.json', calibration);
+ await writeEvidence(runDir, 'verdict.json', verdict);
+ await writeEvidence(runDir, 'evidence.json', evidence);
+ await writeEvidence(runDir, 'results.json', { cases, comparisons, unpaired: result.unpaired });
+ return result;
+ } finally {
+ if (ownsBrowser) await browser?.close();
+ if (!options.keepWorktrees) await revisions.cleanup();
+ }
+};
diff --git a/packages/style-equivalence/src/selftest/cssCorpus.test.ts b/packages/style-equivalence/src/selftest/cssCorpus.test.ts
new file mode 100644
index 00000000000..9125a011a18
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/cssCorpus.test.ts
@@ -0,0 +1,27 @@
+import type { Browser } from '@playwright/test';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { launchBrowser } from '../capture/browser';
+import { runCssCorpus } from './run';
+
+let browser: Browser;
+
+beforeAll(async () => {
+ browser = await launchBrowser();
+}, 60_000);
+
+afterAll(async () => {
+ await browser?.close();
+});
+
+describe('CSS boundary corpus', () => {
+ it('gives every entry its expected outcome', async () => {
+ const results = await runCssCorpus({ browser });
+ expect(results).toHaveLength(33);
+ expect(
+ results
+ .filter((entry) => !entry.passed)
+ .map((entry) => `${entry.id}: expected ${entry.expected}, got ${entry.actual}`),
+ ).toEqual([]);
+ }, 300_000);
+});
diff --git a/packages/style-equivalence/src/selftest/cssCorpus.ts b/packages/style-equivalence/src/selftest/cssCorpus.ts
new file mode 100644
index 00000000000..650d554ea2c
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/cssCorpus.ts
@@ -0,0 +1,286 @@
+export type CorpusExpectation = 'changed' | 'equivalent' | 'flagged';
+
+export interface CssCorpusEntry {
+ after: string;
+ afterMarkup?: string;
+ before: string;
+ expected: CorpusExpectation;
+ feature: string;
+ id: string;
+ markup?: string;
+ setup?: string;
+}
+
+const ITEM = '<div class="item">Deterministic text</div>';
+
+export const cssCorpusPage = (entry: CssCorpusEntry, side: 'after' | 'before') => {
+ const markup = (side === 'after' ? (entry.afterMarkup ?? entry.markup) : entry.markup) ?? ITEM;
+ return `<!doctype html><html><head><meta charset="utf-8"><style>body{margin:0;font:14px Arial} ${entry[side]}</style></head><body><div id="app"><main data-synthetic-cases=""><section data-case="css|${entry.id}|0" style="box-sizing:border-box;padding:8px;position:relative;width:360px"><div data-synthetic-target="">${markup}</div></section></main></div><script>
+const params = new URLSearchParams(location.search);
+if (params.get('theme')) document.documentElement.setAttribute('data-theme', params.get('theme'));
+if (params.get('dir')) document.documentElement.setAttribute('dir', params.get('dir'));
+for (const element of document.querySelectorAll('[data-synthetic-target] *')) element.setAttribute('data-synthetic-element', '');
+${entry.setup ?? ''}
+document.getElementById('app').setAttribute('data-synthetic-ready', 'true');
+</script></body></html>`;
+};
+
+export const CSS_CORPUS: CssCorpusEntry[] = [
+ {
+ after: '.item{color:blue}',
+ before: '.item{color:red}',
+ expected: 'changed',
+ feature: '普通颜色',
+ id: 'color',
+ },
+ {
+ after: '.item{background-image:linear-gradient(red,blue)}.item{background-color:red}',
+ before: '.item{background-image:linear-gradient(red,blue)}.item{background:red}',
+ expected: 'changed',
+ feature: 'shorthand 隐含 reset',
+ id: 'background-reset',
+ },
+ {
+ after: '.item{border:0 solid red}',
+ before: '.item{border:2px solid red}',
+ expected: 'changed',
+ feature: '边框',
+ id: 'border',
+ },
+ {
+ after: '.item{color:blue}',
+ before: '.item{color:blue!important}',
+ expected: 'changed',
+ feature: '!important 与 inline',
+ id: 'important',
+ markup: '<div class="item" style="color:red">Text</div>',
+ },
+ {
+ after: '@layer b,a;@layer a{.item{color:red}}@layer b{.item{color:blue}}',
+ before: '@layer a,b;@layer a{.item{color:red}}@layer b{.item{color:blue}}',
+ expected: 'changed',
+ feature: 'cascade layer 顺序',
+ id: 'layer-order',
+ },
+ {
+ after: '.item{color:var(--missing,blue)}',
+ before: '.item{color:var(--missing,red)}',
+ expected: 'changed',
+ feature: '变量 fallback',
+ id: 'variable-fallback',
+ },
+ {
+ after: '.item::before{content:"label";color:blue}',
+ before: '.item::before{content:"label";color:red}',
+ expected: 'changed',
+ feature: '::before',
+ id: 'before',
+ },
+ {
+ after: '.item::after{color:red}',
+ before: '.item::after{content:"label";color:red}',
+ expected: 'changed',
+ feature: '伪元素消失',
+ id: 'after-content',
+ },
+ {
+ after: 'input::placeholder{color:blue}',
+ before: 'input::placeholder{color:red}',
+ expected: 'changed',
+ feature: '::placeholder',
+ id: 'placeholder',
+ markup: '<input placeholder="Placeholder">',
+ },
+ {
+ after: 'li::marker{color:blue}',
+ before: 'li::marker{color:red}',
+ expected: 'changed',
+ feature: '::marker',
+ id: 'marker',
+ markup: '<ul><li>List item</li></ul>',
+ },
+ {
+ after: '.item{color:black}',
+ before: '.item{color:black}.item:hover{color:red}',
+ expected: 'changed',
+ feature: ':hover',
+ id: 'hover',
+ },
+ {
+ after: '.item{outline:none}',
+ before: '.item{outline:none}.item:focus-visible{outline:2px solid red}',
+ expected: 'changed',
+ feature: ':focus-visible',
+ id: 'focus-visible',
+ markup: '<button class="item">Button</button>',
+ },
+ {
+ after: '.target{opacity:0}',
+ before: '.target{opacity:0}.parent:hover .target{opacity:1}',
+ expected: 'changed',
+ feature: '祖先 hover',
+ id: 'ancestor-hover',
+ markup: '<div class="parent"><span class="target">Action</span></div>',
+ },
+ {
+ after: '.target{color:black}',
+ before: '.target{color:black}.trigger:hover + .target{color:red}',
+ expected: 'changed',
+ feature: '兄弟 hover',
+ id: 'sibling-hover',
+ markup: '<button class="trigger">Trigger</button><span class="target">Target</span>',
+ },
+ {
+ after: '.target{color:black}',
+ before: '.target{color:black}.parent:has(.trigger:hover) .target{color:red}',
+ expected: 'changed',
+ feature: ':has + hover',
+ id: 'has-hover',
+ markup:
+ '<div class="parent"><button class="trigger">Trigger</button><span class="target">Target</span></div>',
+ },
+ {
+ after: '.item{color:black}',
+ before: '.item{color:black;@media(width<600px){color:red}}',
+ expected: 'changed',
+ feature: '原生嵌套 media',
+ id: 'nested-media',
+ },
+ {
+ after: '.item{color:black}',
+ before: '.item{color:black}@media(600px<=width<800px){.item{color:red}}',
+ expected: 'changed',
+ feature: '范围 media',
+ id: 'range-media',
+ },
+ {
+ after: '.host{container-type:inline-size;width:400px}.item{color:black}',
+ before:
+ '.host{container-type:inline-size;width:400px}.item{color:black}@container(width<300px){.item{color:red}}',
+ expected: 'flagged',
+ feature: '尺寸 container',
+ id: 'container',
+ markup: '<div class="host"><div class="item">Text</div></div>',
+ },
+ {
+ after: '.host{container:panel/inline-size;width:400px}.item{color:black}',
+ before:
+ '.host{container:panel/inline-size;width:400px}.item{color:black}@container panel (width<300px){.item{color:red}}',
+ expected: 'flagged',
+ feature: '命名 container',
+ id: 'named-container',
+ markup: '<div class="host"><div class="item">Text</div></div>',
+ },
+ {
+ after: '.host{container-type:inline-size;width:400px}.item{color:black}',
+ before:
+ '.host{container-type:inline-size;width:400px}.item{color:black;@media(width<600px){@container(width<300px){color:red}}}',
+ expected: 'flagged',
+ feature: 'media 与 container 交集',
+ id: 'media-container',
+ markup: '<div class="host"><div class="item">Text</div></div>',
+ },
+ {
+ after: '.item{color:black}',
+ before: '.item{color:black}@media(width<600px){.item:hover{color:red}}',
+ expected: 'changed',
+ feature: 'media 与 hover 交集',
+ id: 'media-hover',
+ },
+ {
+ after: '.row~.row{border-top:1px solid red}',
+ before: '.row+.row{border-top:1px solid red}',
+ expected: 'changed',
+ feature: '相邻兄弟与一般兄弟',
+ id: 'adjacent-sibling',
+ markup: '<div class="row">First</div><div>Separator</div><div class="row">Last</div>',
+ },
+ {
+ after: '.item{padding-left:8px}',
+ before: '.item{padding-inline-start:8px}',
+ expected: 'changed',
+ feature: 'RTL 逻辑属性',
+ id: 'rtl',
+ },
+ {
+ after: '.item{color:black}',
+ before: '.item{color:black}.item:hover:focus-visible{color:red}',
+ expected: 'changed',
+ feature: '伪类组合',
+ id: 'combined-pseudos',
+ markup: '<button class="item">Button</button>',
+ },
+ {
+ after: '.item{animation:fade 2s linear infinite}@keyframes fade{to{opacity:0}}',
+ before: '.item{animation:fade 1s linear infinite}@keyframes fade{to{opacity:0}}',
+ expected: 'changed',
+ feature: '动画 timing',
+ id: 'animation-timing',
+ },
+ {
+ after: '.item{animation:fade 1s linear infinite}@keyframes fade{from{opacity:1}to{opacity:0}}',
+ before:
+ '.item{animation:fade 1s linear infinite}@keyframes fade{from{opacity:1}to{opacity:0}}@media(prefers-reduced-motion:reduce){.item{animation:none}}',
+ expected: 'changed',
+ feature: 'reduced-motion',
+ id: 'reduced-motion',
+ },
+ {
+ after: '.item{transition:color .4s}',
+ before: '.item{transition:color .2s}',
+ expected: 'changed',
+ feature: 'transition 参数',
+ id: 'transition',
+ },
+ {
+ after:
+ '.item{color:blue;--density:normal}@container style(--density:compact){.item{color:red}}',
+ before:
+ '.item{color:blue;--density:normal}@container style(--density:compact){.item{color:green}}',
+ expected: 'flagged',
+ feature: '字面量 style container 查询',
+ id: 'style-container',
+ markup: '<div style="--density:normal"><div class="item">Text</div></div>',
+ },
+ {
+ after: '.item::highlight(experiment){background:blue}',
+ before: '.item::highlight(experiment){background:red}',
+ expected: 'flagged',
+ feature: 'CSS Highlight,需反馈',
+ id: 'highlight',
+ setup:
+ 'const range=new Range();range.selectNodeContents(document.querySelector(".item"));CSS.highlights.set("experiment",new Highlight(range));',
+ },
+ {
+ after: '.item{color:blue}',
+ before: '.item{color:blue}',
+ expected: 'equivalent',
+ feature: '完全相同正对照',
+ id: 'identity',
+ },
+ {
+ after: '.renamed{color:blue;padding:8px}',
+ afterMarkup: '<div class="renamed">Deterministic text</div>',
+ before: '.item{color:blue;padding:8px}',
+ expected: 'equivalent',
+ feature: '类名变化正对照',
+ id: 'class-rename',
+ },
+ {
+ after: '.color{color:blue}.padding{padding:8px}',
+ afterMarkup: '<div class="color padding">Deterministic text</div>',
+ before: '.item{color:blue;padding:8px}',
+ expected: 'equivalent',
+ feature: '原子类拆分正对照',
+ id: 'atomic-split',
+ },
+ {
+ after:
+ '.item{animation:hash123 1s linear infinite}@keyframes hash123{from{opacity:1}to{opacity:0}}',
+ before:
+ '.item{animation:original 1s linear infinite}@keyframes original{from{opacity:1}to{opacity:0}}',
+ expected: 'equivalent',
+ feature: '动画名变化正对照',
+ id: 'keyframe-rename',
+ },
+];
diff --git a/packages/style-equivalence/src/selftest/index.ts b/packages/style-equivalence/src/selftest/index.ts
new file mode 100644
index 00000000000..4709e8008af
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/index.ts
@@ -0,0 +1,18 @@
+import { launchBrowser } from '../capture/browser';
+import { runCssCorpus, type SelfTestReport } from './run';
+import { runSourceCorpus } from './sourceCorpus/run';
+
+export const runSelfTest = async (options: {
+ configFile: string;
+ recordsDir: string;
+ repo: string;
+}): Promise<SelfTestReport> => {
+ const browser = await launchBrowser();
+ try {
+ const css = await runCssCorpus({ browser });
+ const source = await runSourceCorpus({ ...options, browser });
+ return { css, passed: [...css, ...source].every((entry) => entry.passed), source };
+ } finally {
+ await browser.close();
+ }
+};
diff --git a/packages/style-equivalence/src/selftest/run.ts b/packages/style-equivalence/src/selftest/run.ts
new file mode 100644
index 00000000000..6c2385adad7
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/run.ts
@@ -0,0 +1,97 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { Browser } from '@playwright/test';
+
+import { analyzeRun, type CaseResult } from '../analyze/diff';
+import { captureRun } from '../capture/runner';
+import { serveDirectories } from '../capture/staticServer';
+import { type CorpusExpectation, CSS_CORPUS, cssCorpusPage } from './cssCorpus';
+
+export type CorpusOutcome = CorpusExpectation | 'error' | 'unstable';
+
+export interface CorpusResult {
+ actual: CorpusOutcome;
+ detail: string[];
+ expected: CorpusExpectation;
+ feature: string;
+ id: string;
+ passed: boolean;
+}
+
+export const outcomeOf = (result: CaseResult | undefined): CorpusOutcome => {
+ if (!result || result.errors.length) return 'error';
+ if (result.unstableConditions.length) return 'unstable';
+ if (result.status === 'difference') return 'changed';
+ return result.gaps.length ? 'flagged' : 'equivalent';
+};
+
+const CONCURRENCY = 4;
+
+export const runCssCorpus = async ({ browser, only }: { browser: Browser; only?: string[] }) => {
+ const root = await mkdtemp(path.join(tmpdir(), 'style-eq-css-corpus-'));
+ const entries = CSS_CORPUS.filter((entry) => !only || only.includes(entry.id));
+ for (const entry of entries)
+ for (const side of ['before', 'after'] as const) {
+ await mkdir(path.join(root, entry.id, side), { recursive: true });
+ await writeFile(path.join(root, entry.id, side, 'index.html'), cssCorpusPage(entry, side));
+ }
+ const server = await serveDirectories(root);
+ const results: CorpusResult[] = [];
+ try {
+ const queue = [...entries];
+ await Promise.all(
+ Array.from({ length: CONCURRENCY }, async () => {
+ for (let entry = queue.shift(); entry; entry = queue.shift()) {
+ const capture = await captureRun({
+ browser,
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [375, 1280] },
+ urls: {
+ base: `${server.url}/${entry.id}/before/`,
+ head: `${server.url}/${entry.id}/after/`,
+ },
+ });
+ const [result] = analyzeRun(capture);
+ const actual = outcomeOf(result);
+ results.push({
+ actual,
+ detail: [
+ ...(result?.errors ?? []),
+ ...(result?.gaps ?? []),
+ ...(result?.differingConditions ?? []),
+ ],
+ expected: entry.expected,
+ feature: entry.feature,
+ id: entry.id,
+ passed: actual === entry.expected,
+ });
+ }
+ }),
+ );
+ } finally {
+ await server.close();
+ await rm(root, { force: true, recursive: true });
+ }
+ return entries.map((entry) => results.find((result) => result.id === entry.id)!);
+};
+
+export interface SelfTestReport {
+ css: CorpusResult[];
+ passed: boolean;
+ source: CorpusResult[];
+}
+
+export const formatSelfTest = (report: SelfTestReport) => {
+ const count = (results: CorpusResult[]) =>
+ `${results.filter((entry) => entry.passed).length}/${results.length}`;
+ return [
+ `self-test ${report.passed ? 'passed' : 'FAILED'} · CSS corpus ${count(report.css)} · source corpus ${count(report.source)}`,
+ ...[...report.css, ...report.source]
+ .filter((entry) => !entry.passed)
+ .map(
+ (entry) =>
+ ` ✗ ${entry.id} (${entry.feature}) expected ${entry.expected}, got ${entry.actual}${entry.detail.length ? ` ${entry.detail.slice(0, 3).join(' · ')}` : ''}`,
+ ),
+ ].join('\n');
+};
diff --git a/packages/style-equivalence/src/selftest/sourceCorpus.test.ts b/packages/style-equivalence/src/selftest/sourceCorpus.test.ts
new file mode 100644
index 00000000000..59965500e1c
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/sourceCorpus.test.ts
@@ -0,0 +1,54 @@
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, 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 { runSourceCorpus } from './sourceCorpus/run';
+
+const rootModules = path.resolve(import.meta.dirname, '../../../../node_modules');
+const configFile = path.resolve(
+ import.meta.dirname,
+ '../../test/fixtures/stylex-project/style-equivalence.config.ts',
+);
+let repo: string;
+let records: string;
+
+beforeAll(async () => {
+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-source-corpus-'));
+ records = await mkdtemp(path.join(tmpdir(), 'style-eq-source-records-'));
+ await writeFile(path.join(repo, 'package.json'), '{"name":"corpus","private":true}\n');
+ await writeFile(path.join(repo, '.gitignore'), 'node_modules\n');
+ await symlink(rootModules, path.join(repo, 'node_modules'));
+ const git = (...args: string[]) => execFileSync('git', args, { cwd: repo });
+ git('init', '-q');
+ git('-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'root');
+ git('add', '.');
+ git('-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '-m', 'files');
+}, 30_000);
+
+afterAll(async () => {
+ await rm(repo, { force: true, recursive: true });
+ await rm(records, { force: true, recursive: true });
+});
+
+describe('source corpus', () => {
+ it('reports each pair with its expected outcome', async () => {
+ const results = await runSourceCorpus({ configFile, recordsDir: records, repo });
+ const actual = Object.fromEntries(results.map((entry) => [entry.id, entry.actual]));
+ expect(actual).toMatchObject({
+ 'background-split': 'equivalent',
+ 'cross-component': 'flagged',
+ 'font-inherit': 'changed',
+ });
+ expect(
+ results
+ .filter((entry) => !entry.passed)
+ .map((entry) => `${entry.id}: expected ${entry.expected}, got ${entry.actual}`),
+ ).toEqual([]);
+ expect(execFileSync('git', ['status', '--porcelain'], { cwd: repo, encoding: 'utf8' })).toBe(
+ '',
+ );
+ }, 300_000);
+});
diff --git a/packages/style-equivalence/src/selftest/sourceCorpus/entries.ts b/packages/style-equivalence/src/selftest/sourceCorpus/entries.ts
new file mode 100644
index 00000000000..f4bfba7b199
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/sourceCorpus/entries.ts
@@ -0,0 +1,234 @@
+import type { CorpusExpectation } from '../cssCorpus';
+
+export interface SourceCorpusEntry {
+ base: Record<string, string>;
+ expected: CorpusExpectation;
+ feature: string;
+ head: Record<string, string>;
+ id: string;
+}
+
+const emotion = (
+ styles: string,
+ jsx: string,
+ extra = '',
+) => `import { createStaticStyles, cx } from '@lobehub/ui';
+${extra}
+const styles = createStaticStyles(({ css }) => ({
+${styles}
+}));
+
+export const Sample = ({ active, disabled }: { active?: boolean; disabled?: boolean }) => (
+${jsx}
+);
+`;
+
+const stylexSource = (
+ styles: string,
+ jsx: string,
+ extra = '',
+) => `import * as stylex from '@stylexjs/stylex';
+${extra}
+const styles = stylex.create({
+${styles}
+});
+
+export const Sample = ({ active, disabled }: { active?: boolean; disabled?: boolean }) => (
+${jsx}
+);
+`;
+
+export const SOURCE_CORPUS: SourceCorpusEntry[] = [
+ {
+ base: {
+ 'font-inherit.tsx': emotion(
+ " root: css`font-feature-settings: 'tnum';`,\n button: css`font: inherit; font-size: 12px;`,",
+ ' <div className={styles.root}>\n <button className={styles.button} type="button">A</button>\n </div>',
+ ),
+ },
+ expected: 'changed',
+ feature: 'font: inherit 拆成 longhand',
+ head: {
+ 'font-inherit.tsx': stylexSource(
+ " root: { fontFeatureSettings: \"'tnum'\" },\n button: { fontFamily: 'inherit', fontSize: 12, fontWeight: 'inherit', lineHeight: 'inherit' },",
+ ' <div {...stylex.props(styles.root)}>\n <button {...stylex.props(styles.button)} type="button">A</button>\n </div>',
+ ),
+ },
+ id: 'font-inherit',
+ },
+ {
+ base: {
+ 'background-split.tsx': emotion(
+ ' box: css`background: rgb(255, 0, 0);`,',
+ ' <div className={styles.box} />',
+ ),
+ },
+ expected: 'equivalent',
+ feature: 'background 拆成 color + image none',
+ head: {
+ 'background-split.tsx': stylexSource(
+ " box: { backgroundColor: 'rgb(255, 0, 0)', backgroundImage: 'none' },",
+ ' <div {...stylex.props(styles.box)} />',
+ ),
+ },
+ id: 'background-split',
+ },
+ {
+ base: {
+ 'condition-combos.tsx': emotion(
+ ' a: css`padding: 4px;`,\n b: css`color: rgb(0, 0, 255);`,\n c: css`opacity: 0.5;`,',
+ ' <div className={cx(styles.a, active && styles.b, disabled && styles.c)} />',
+ ),
+ },
+ expected: 'equivalent',
+ feature: '条件组合',
+ head: {
+ 'condition-combos.tsx': stylexSource(
+ " a: { padding: 4 },\n b: { color: 'rgb(0, 0, 255)' },\n c: { opacity: 0.5 },",
+ ' <div {...stylex.props(styles.a, active && styles.b, disabled && styles.c)} />',
+ ),
+ },
+ id: 'condition-combos',
+ },
+ {
+ base: {
+ 'merge-order.tsx': emotion(
+ ' a: css`color: rgb(255, 0, 0);`,\n b: css`color: rgb(0, 128, 0);`,',
+ ' <div className={cx(styles.a, styles.b)} />',
+ ),
+ },
+ expected: 'changed',
+ feature: 'cx 与 stylex.props 合并顺序',
+ head: {
+ 'merge-order.tsx': stylexSource(
+ " a: { color: 'rgb(255, 0, 0)' },\n b: { color: 'rgb(0, 128, 0)' },",
+ ' <div {...stylex.props(styles.b, styles.a)} />',
+ ),
+ },
+ id: 'merge-order',
+ },
+ {
+ base: {
+ 'when-ancestor.tsx': emotion(
+ ' row: css`\n padding: 4px;\n\n &:hover .row-action {\n opacity: 1;\n }\n `,\n action: css`opacity: 0;`,',
+ " <div className={styles.row}>\n <span className={cx(styles.action, 'row-action')}>A</span>\n </div>",
+ ),
+ },
+ expected: 'equivalent',
+ feature: '同组件后代选择器改写成 when.ancestor',
+ head: {
+ 'when-ancestor.tsx': stylexSource(
+ " row: { padding: 4 },\n action: { opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 } },",
+ ' <div {...stylex.props(styles.row, stylex.defaultMarker())}>\n <span {...stylex.props(styles.action)}>A</span>\n </div>',
+ ),
+ },
+ id: 'when-ancestor',
+ },
+ {
+ base: {
+ 'keyframes.module.css':
+ '.spin {\n animation: original-spin 1s linear infinite;\n}\n\n@keyframes original-spin {\n from { opacity: 1; }\n to { opacity: 0.2; }\n}\n',
+ 'keyframes.tsx':
+ "import styles from './keyframes.module.css';\n\nexport const Sample = () => <div className={styles.spin} />;\n",
+ },
+ expected: 'equivalent',
+ feature: 'keyframes',
+ head: {
+ 'keyframes.tsx': stylexSource(
+ " spin: { animationName: spin, animationDuration: '1s', animationTimingFunction: 'linear', animationIterationCount: 'infinite' },",
+ ' <div {...stylex.props(styles.spin)} />',
+ 'const spin = stylex.keyframes({ from: { opacity: 1 }, to: { opacity: 0.2 } });',
+ ),
+ },
+ id: 'keyframes',
+ },
+ {
+ base: {
+ 'nested-hover.tsx': emotion(
+ ' link: css`\n color: rgb(0, 0, 0);\n\n &:hover {\n color: rgb(255, 0, 0);\n }\n `,',
+ ' <a className={styles.link}>A</a>',
+ ),
+ },
+ expected: 'equivalent',
+ feature: '嵌套 :hover',
+ head: {
+ 'nested-hover.tsx': stylexSource(
+ " link: { color: { default: 'rgb(0, 0, 0)', ':hover': 'rgb(255, 0, 0)' } },",
+ ' <a {...stylex.props(styles.link)}>A</a>',
+ ),
+ },
+ id: 'nested-hover',
+ },
+ {
+ base: {
+ 'pseudo-element.tsx': emotion(
+ " mark: css`\n &::before {\n content: '*';\n color: rgb(255, 0, 0);\n }\n `,",
+ ' <span className={styles.mark}>A</span>',
+ ),
+ },
+ expected: 'equivalent',
+ feature: '伪元素',
+ head: {
+ 'pseudo-element.tsx': stylexSource(
+ " mark: { '::before': { content: \"'*'\", color: 'rgb(255, 0, 0)' } },",
+ ' <span {...stylex.props(styles.mark)}>A</span>',
+ ),
+ },
+ id: 'pseudo-element',
+ },
+ {
+ base: {
+ 'constant-interpolation.tsx': emotion(
+ ' box: css`padding: ${GAP}px;`,',
+ ' <div className={styles.box} />',
+ 'const GAP = 8;',
+ ),
+ },
+ expected: 'equivalent',
+ feature: '常量插值',
+ head: {
+ 'constant-interpolation.tsx': stylexSource(
+ ' box: { padding: GAP },',
+ ' <div {...stylex.props(styles.box)} />',
+ 'const GAP = 8;',
+ ),
+ },
+ id: 'constant-interpolation',
+ },
+ {
+ base: {
+ 'jsx-prop-value.tsx': emotion(
+ ' icon: css`width: 12px; height: 12px;`,',
+ ' <Slot icon={<span className={styles.icon} />} />',
+ 'const Slot = ({ icon }: { icon: unknown }) => <div>{icon as never}</div>;',
+ ),
+ },
+ expected: 'equivalent',
+ feature: 'JSX 作为 prop 值',
+ head: {
+ 'jsx-prop-value.tsx': stylexSource(
+ ' icon: { width: 12, height: 12 },',
+ ' <Slot icon={<span {...stylex.props(styles.icon)} />} />',
+ 'const Slot = ({ icon }: { icon: unknown }) => <div>{icon as never}</div>;',
+ ),
+ },
+ id: 'jsx-prop-value',
+ },
+ {
+ base: {
+ 'cross-component.tsx': emotion(
+ ' muted: css`\n .control-label {\n color: rgb(128, 128, 128);\n }\n `,',
+ ' <div className={cx(active && styles.muted)} />',
+ ),
+ },
+ expected: 'flagged',
+ feature: '跨组件选择器',
+ head: {
+ 'cross-component.tsx': stylexSource(
+ " muted: { color: 'rgb(128, 128, 128)' },",
+ ' <div {...stylex.props(active && styles.muted)} />',
+ ),
+ },
+ id: 'cross-component',
+ },
+];
diff --git a/packages/style-equivalence/src/selftest/sourceCorpus/run.ts b/packages/style-equivalence/src/selftest/sourceCorpus/run.ts
new file mode 100644
index 00000000000..b59424298b2
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/sourceCorpus/run.ts
@@ -0,0 +1,113 @@
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { Browser } from '@playwright/test';
+
+import { type CaseRecord, runComparison } from '../../run';
+import type { CorpusResult } from '../run';
+import { SOURCE_CORPUS, type SourceCorpusEntry } from './entries';
+
+export const CORPUS_DIR = 'src/__style_equivalence_corpus__';
+
+const IDENTITY = {
+ GIT_AUTHOR_EMAIL: 'style-equivalence@localhost',
+ GIT_AUTHOR_NAME: 'style-equivalence',
+ GIT_COMMITTER_EMAIL: 'style-equivalence@localhost',
+ GIT_COMMITTER_NAME: 'style-equivalence',
+};
+
+const commitFiles = async (
+ repo: string,
+ parent: string,
+ tree: string,
+ files: Record<string, string>,
+ message: string,
+) => {
+ const scratch = await mkdtemp(path.join(tmpdir(), 'style-eq-index-'));
+ const env = { ...process.env, ...IDENTITY, GIT_INDEX_FILE: path.join(scratch, 'index') };
+ const git = (args: string[], input?: string) =>
+ execFileSync('git', args, { cwd: repo, encoding: 'utf8', env, input }).trim();
+ try {
+ git(['read-tree', tree]);
+ for (const [file, content] of Object.entries(files)) {
+ const blob = git(['hash-object', '-w', '--stdin'], content);
+ git(['update-index', '--add', '--cacheinfo', `100644,${blob},${file}`]);
+ }
+ return git(['commit-tree', git(['write-tree']), '-p', parent, '-m', message]);
+ } finally {
+ await rm(scratch, { force: true, recursive: true });
+ }
+};
+
+const filesOf = (entries: SourceCorpusEntry[], side: 'base' | 'head') =>
+ Object.fromEntries(
+ entries.flatMap((entry) =>
+ Object.entries(entry[side]).map(([file, content]) => [
+ `${CORPUS_DIR}/${entry.id}/${file}`,
+ content,
+ ]),
+ ),
+ );
+
+const outcomeOfEntry = (cases: CaseRecord[], unpaired: number): CorpusResult['actual'] => {
+ if (!cases.length && !unpaired) return 'error';
+ if (cases.some((entry) => entry.category === 'blocking')) return 'error';
+ if (cases.some((entry) => entry.category === 'difference' && !entry.plan.flags.length))
+ return 'changed';
+ if (unpaired || cases.some((entry) => entry.category !== 'equal')) return 'flagged';
+ return 'equivalent';
+};
+
+export interface SourceCorpusOptions {
+ browser?: Browser;
+ configFile: string;
+ only?: string[];
+ recordsDir: string;
+ repo: string;
+}
+
+export const runSourceCorpus = async ({
+ browser,
+ configFile,
+ only,
+ recordsDir,
+ repo,
+}: SourceCorpusOptions): Promise<CorpusResult[]> => {
+ const entries = SOURCE_CORPUS.filter((entry) => !only || only.includes(entry.id));
+ const parent = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim();
+ const base = await commitFiles(repo, parent, parent, filesOf(entries, 'base'), 'corpus base');
+ const head = await commitFiles(repo, base, parent, filesOf(entries, 'head'), 'corpus head');
+ const result = await runComparison({
+ base,
+ browser,
+ calibrate: false,
+ configFile,
+ head,
+ mutations: 0,
+ recordsDir,
+ repo,
+ });
+ return entries.map((entry) => {
+ const directory = `${CORPUS_DIR}/${entry.id}/`;
+ const cases = result.cases.filter((item) => item.plan.file.startsWith(directory));
+ const unpaired = result.plans
+ .filter((plan) => plan.file.startsWith(directory))
+ .reduce((total, plan) => total + plan.unpaired.length, 0);
+ const actual = outcomeOfEntry(cases, unpaired);
+ return {
+ actual,
+ detail: cases
+ .filter((item) => item.category !== 'equal')
+ .map(
+ (item) =>
+ `${item.key} ${item.category}${item.plan.flags.length ? ` [${item.plan.flags.join(',')}]` : ''} ${item.result.errors.join(';')}`,
+ ),
+ expected: entry.expected,
+ feature: entry.feature,
+ id: entry.id,
+ passed: actual === entry.expected,
+ };
+ });
+};
diff --git a/packages/style-equivalence/src/selftest/store.test.ts b/packages/style-equivalence/src/selftest/store.test.ts
new file mode 100644
index 00000000000..51e3c6c14fa
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/store.test.ts
@@ -0,0 +1,24 @@
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { saveSelfTest, SELF_TEST_FILE } from './store';
+
+let dir = '';
+afterEach(() => rm(dir, { force: true, recursive: true }));
+
+describe('saveSelfTest', () => {
+ it('stores the report with when it ran and the verifier version', async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'style-eq-selftest-'));
+ await saveSelfTest(dir, { css: [], passed: true, source: [] }, '2026-11-04T00:00:00.000Z');
+ expect(JSON.parse(await readFile(path.join(dir, SELF_TEST_FILE), 'utf8'))).toEqual({
+ css: [],
+ passed: true,
+ ranAt: '2026-11-04T00:00:00.000Z',
+ source: [],
+ verifierVersion: expect.stringMatching(/^\d+\.\d+\.\d+$/),
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/selftest/store.ts b/packages/style-equivalence/src/selftest/store.ts
new file mode 100644
index 00000000000..57a3766231d
--- /dev/null
+++ b/packages/style-equivalence/src/selftest/store.ts
@@ -0,0 +1,13 @@
+import { writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { VERIFIER_VERSION } from '../run';
+import type { SelfTestReport } from './run';
+
+export const SELF_TEST_FILE = 'self-test.json';
+
+export const saveSelfTest = (recordsDir: string, report: SelfTestReport, ranAt: string) =>
+ writeFile(
+ path.join(recordsDir, SELF_TEST_FILE),
+ `${JSON.stringify({ ...report, ranAt, verifierVersion: VERIFIER_VERSION }, null, 2)}\n`,
+ );
diff --git a/packages/style-equivalence/src/server/api.ts b/packages/style-equivalence/src/server/api.ts
new file mode 100644
index 00000000000..bc5413217ed
--- /dev/null
+++ b/packages/style-equivalence/src/server/api.ts
@@ -0,0 +1,137 @@
+import { execFile } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { readReviews, reviewScope, writeReviews } from '../review/store';
+import { decideVerdict, signCases, type VerdictItem } from '../verdict';
+
+const run = promisify(execFile);
+
+export interface StoredRun {
+ calibration: Array<{ status: string }>;
+ evidence: Record<string, unknown>;
+ extractions: Record<string, unknown>;
+ items: VerdictItem[];
+ mutation: { passed: boolean };
+ plans?: Array<{ file: string; standIns?: Record<string, string[]> }>;
+ recordsDir: string;
+ results: { cases: Array<{ category: string; key: string; plan: { file: string } }> };
+ run: Record<string, unknown> & { repo?: string };
+}
+
+const readJson = async <T>(runDir: string, name: string, fallback: T): Promise<T> => {
+ try {
+ return JSON.parse(await readFile(path.join(runDir, name), 'utf8')) as T;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback;
+ throw error;
+ }
+};
+
+export const loadRun = async (runDir: string): Promise<StoredRun> => {
+ const verdict = await readJson<{ items: Array<VerdictItem & { signoff?: string }> }>(
+ runDir,
+ 'verdict.json',
+ { items: [] },
+ );
+ return {
+ calibration: await readJson(runDir, 'calibration.json', []),
+ evidence: await readJson(runDir, 'evidence.json', {}),
+ extractions: await readJson(runDir, 'extractions.json', {}),
+ items: verdict.items.map(({ signoff: _signoff, ...item }) => item),
+ mutation: await readJson(runDir, 'mutation.json', { passed: false }),
+ plans: await readJson(runDir, 'plan.json', []),
+ recordsDir: path.dirname(runDir),
+ results: await readJson(runDir, 'results.json', { cases: [] }),
+ run: await readJson(runDir, 'run.json', {}),
+ };
+};
+
+export const readSelfTest = async (file: string) =>
+ readJson<unknown>(path.dirname(file), path.basename(file), null);
+
+export const runPr = (stored: StoredRun) =>
+ (stored.run.pr as { number?: number } | undefined)?.number;
+
+export const readRunReviews = (stored: StoredRun) =>
+ readReviews(
+ stored.recordsDir,
+ stored.items.map((item) => item.file),
+ reviewScope(stored.items, runPr(stored)),
+ );
+
+export const currentVerdict = async (stored: StoredRun) => {
+ const reviews = await readRunReviews(stored);
+ return decideVerdict({
+ calibration: stored.calibration,
+ items: stored.items,
+ mutation: stored.mutation,
+ reworks: reviews.reworks,
+ signoffs: reviews.passes,
+ unparsedSelectors: (stored.run.unparsedSelectors as string[] | undefined)?.length,
+ });
+};
+
+export class ApiError extends Error {
+ constructor(
+ readonly status: number,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+export const caseDetail = async (stored: StoredRun, key: string) => {
+ const record = stored.results.cases.find((entry) => entry.key === key);
+ const verdict = await currentVerdict(stored);
+ const item = verdict.items.find((entry) => entry.key === key);
+ if (!record && !item) throw new ApiError(404, `UNKNOWN_CASE:${key}`);
+ const file = record?.plan.file ?? item?.file;
+ return {
+ case: record,
+ evidence: stored.evidence[key],
+ extraction: file ? stored.extractions[file] : undefined,
+ item,
+ };
+};
+
+export const defaultSigner = async (repo: string) => {
+ try {
+ return (await run('git', ['-C', repo, 'config', 'user.name'])).stdout.trim() || 'unknown';
+ } catch {
+ return 'unknown';
+ }
+};
+
+export const applySignoff = async (
+ stored: StoredRun,
+ body: { keys?: unknown; note?: unknown; reason?: unknown; signer?: unknown },
+) => {
+ const repo = stored.run.repo;
+ if (!repo) throw new ApiError(409, 'RUN_HAS_NO_REPOSITORY');
+ if (!Array.isArray(body.keys) || typeof body.reason !== 'string' || typeof body.note !== 'string')
+ throw new ApiError(400, 'EXPECTED_KEYS_REASON_NOTE');
+ let records;
+ try {
+ records = signCases({
+ existing: (await readRunReviews(stored)).passes,
+ items: stored.items,
+ keys: body.keys.map(String),
+ note: body.note,
+ now: new Date().toISOString(),
+ reason: body.reason,
+ signer:
+ typeof body.signer === 'string' && body.signer ? body.signer : await defaultSigner(repo),
+ });
+ } catch (error) {
+ throw new ApiError(409, error instanceof Error ? error.message : String(error));
+ }
+ const byFile = new Map<string, typeof records>();
+ for (const record of records) {
+ const file = stored.items.find((item) => item.key === record.key)!.file;
+ byFile.set(file, [...(byFile.get(file) ?? []), record]);
+ }
+ for (const [file, list] of byFile) await writeReviews(stored.recordsDir, file, { passes: list });
+ return { records, verdict: await currentVerdict(stored) };
+};
diff --git a/packages/style-equivalence/src/server/crop.test.ts b/packages/style-equivalence/src/server/crop.test.ts
new file mode 100644
index 00000000000..d0c12fcd745
--- /dev/null
+++ b/packages/style-equivalence/src/server/crop.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { cropClip } from './inspectCase';
+
+describe('cropClip', () => {
+ const page = { height: 900, width: 1280 };
+ const section = { x: 100, y: 50 };
+
+ it('pads the target box', () => {
+ expect(cropClip(page, section, [100, 20, 20, 10], 16)).toEqual({
+ height: 42,
+ width: 52,
+ x: 184,
+ y: 54,
+ });
+ });
+
+ it('keeps a target that overflows its section whole', () => {
+ expect(cropClip(page, section, [0, -40, 360, 56], 16)).toEqual({
+ height: 82,
+ width: 392,
+ x: 84,
+ y: 0,
+ });
+ });
+
+ it('never reaches outside the page', () => {
+ expect(cropClip(page, { x: 0, y: 0 }, [0, 0, 7, 7], 16)).toEqual({
+ height: 23,
+ width: 23,
+ x: 0,
+ y: 0,
+ });
+ expect(cropClip(page, section, [1170, 840, 10, 10], 16)).toEqual({
+ height: 26,
+ width: 26,
+ x: 1254,
+ y: 874,
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/server/follow.test.ts b/packages/style-equivalence/src/server/follow.test.ts
new file mode 100644
index 00000000000..31de042638e
--- /dev/null
+++ b/packages/style-equivalence/src/server/follow.test.ts
@@ -0,0 +1,136 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { createRunSource, newestRun, parseRunName } from './follow';
+import { startServer } from './index';
+
+const FIRST = '2026-11-05T12-54-12-846Z-784d72f-27c333a';
+const SECOND = '2026-11-05T13-06-44-811Z-784d72f-27c333a';
+const THIRD = '2026-11-05T13-20-00-000Z-784d72f-9a8b7c6';
+
+let records: string;
+
+const addRun = async (
+ name: string,
+ { complete = true, pr, results }: { complete?: boolean; pr?: number; results?: string } = {},
+) => {
+ const dir = path.join(records, name);
+ await mkdir(dir, { recursive: true });
+ const parsed = parseRunName(name);
+ await writeFile(
+ path.join(dir, 'run.json'),
+ JSON.stringify({
+ base: parsed?.base,
+ head: parsed?.head,
+ runId: name,
+ ...(pr ? { pr: { number: pr } } : {}),
+ }),
+ );
+ if (complete)
+ await writeFile(path.join(dir, 'results.json'), results ?? JSON.stringify({ cases: [] }));
+ return dir;
+};
+
+beforeEach(async () => {
+ records = await mkdtemp(path.join(tmpdir(), 'style-eq-follow-'));
+});
+
+afterEach(async () => {
+ await rm(records, { force: true, recursive: true });
+});
+
+describe('the run a report server follows', () => {
+ it('reads the start time, base and head from a run directory name', () => {
+ expect(parseRunName(FIRST)).toMatchObject({
+ base: '784d72f',
+ head: '27c333a',
+ startedAt: '2026-11-05T12:54:12.846Z',
+ });
+ expect(parseRunName(`${FIRST}-2`)!.order).toBeGreaterThan(parseRunName(FIRST)!.order);
+ expect(parseRunName('run-1')).toBeUndefined();
+ });
+
+ it('picks the newest complete run on the same base, whatever its head', async () => {
+ await addRun(FIRST);
+ await addRun(SECOND);
+ await addRun(THIRD);
+ expect(await newestRun(records, FIRST)).toBe(THIRD);
+ });
+
+ it('ignores runs on another base, runs still being written and older runs', async () => {
+ await addRun('2026-11-05T11-00-00-000Z-784d72f-1111111');
+ await addRun(FIRST);
+ await addRun('2026-11-05T13-30-00-000Z-60dee14-27c333a');
+ await addRun(THIRD, { complete: false });
+ expect(await newestRun(records, FIRST)).toBe(FIRST);
+ });
+
+ it('stays on the line of the same pull request when the run has one', async () => {
+ await addRun(FIRST, { pr: 21449 });
+ await addRun(SECOND, { pr: 21449 });
+ await addRun(THIRD, { pr: 21450 });
+ expect(await newestRun(records, FIRST, 21449)).toBe(SECOND);
+ });
+
+ it('keeps a directory it cannot read as a run name where it is', async () => {
+ expect(await newestRun(records, 'run-1')).toBe('run-1');
+ });
+
+ it('switches to a newer run once it lands and reports that it moved', async () => {
+ const first = await addRun(FIRST);
+ const source = await createRunSource({ recordsDir: records, runDir: first });
+ let { dir, stored } = await source.current();
+ expect(source.info(stored, dir)).toMatchObject({
+ pinned: false,
+ requested: FIRST,
+ runId: FIRST,
+ });
+ await addRun(THIRD);
+ ({ dir, stored } = await source.current());
+ expect(source.info(stored, dir)).toMatchObject({
+ head: '9a8b7c6',
+ requested: FIRST,
+ runId: THIRD,
+ startedAt: '2026-11-05T13:20:00.000Z',
+ });
+ });
+
+ it('keeps serving the run it has while the newest one does not parse yet', async () => {
+ const first = await addRun(FIRST);
+ await addRun(THIRD, { results: '{"cases": [' });
+ const source = await createRunSource({ recordsDir: records, runDir: first });
+ const { dir } = await source.current();
+ expect(path.basename(dir)).toBe(FIRST);
+ });
+
+ it('serves exactly the given run when pinned', async () => {
+ const first = await addRun(FIRST);
+ await addRun(THIRD);
+ const source = await createRunSource({ pin: true, recordsDir: records, runDir: first });
+ const { dir, stored } = await source.current();
+ expect(source.info(stored, dir)).toMatchObject({ pinned: true, runId: FIRST });
+ });
+
+ it('answers every request from the newest run, builds included', async () => {
+ const first = await addRun(FIRST);
+ await mkdir(path.join(first, 'dist-base'));
+ await writeFile(path.join(first, 'dist-base/index.html'), 'first build');
+ const server = await startServer({ recordsDir: records, runDir: first, uiDir: records });
+ try {
+ const third = await addRun(THIRD);
+ await mkdir(path.join(third, 'dist-base'));
+ await writeFile(path.join(third, 'dist-base/index.html'), 'third build');
+ expect(await (await fetch(`${server.url}/api/current`)).json()).toMatchObject({
+ requested: FIRST,
+ runId: THIRD,
+ });
+ expect((await (await fetch(`${server.url}/api/run`)).json()).follow.runId).toBe(THIRD);
+ expect(await (await fetch(`${server.url}/base/`)).text()).toBe('third build');
+ } finally {
+ await server.stop();
+ }
+ });
+});
diff --git a/packages/style-equivalence/src/server/follow.ts b/packages/style-equivalence/src/server/follow.ts
new file mode 100644
index 00000000000..3b04c4df9dc
--- /dev/null
+++ b/packages/style-equivalence/src/server/follow.ts
@@ -0,0 +1,105 @@
+import { existsSync } from 'node:fs';
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { loadRun, type StoredRun } from './api';
+
+const RUN_NAME =
+ /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z-([\da-f]+)-([\da-f]+)(?:-(\d+))?$/;
+
+export interface RunName {
+ base: string;
+ head: string;
+ name: string;
+ order: number;
+ startedAt: string;
+}
+
+export const parseRunName = (name: string): RunName | undefined => {
+ const match = RUN_NAME.exec(name);
+ if (!match) return undefined;
+ const [, day, hours, minutes, seconds, millis, base, head, suffix] = match;
+ const startedAt = `${day}T${hours}:${minutes}:${seconds}.${millis}Z`;
+ const time = Date.parse(startedAt);
+ if (Number.isNaN(time)) return undefined;
+ return { base, head, name, order: time * 1000 + Number(suffix ?? 0), startedAt };
+};
+
+const isComplete = (recordsDir: string, name: string) =>
+ existsSync(path.join(recordsDir, name, 'results.json'));
+
+const prOf = async (recordsDir: string, name: string) => {
+ try {
+ const run = JSON.parse(await readFile(path.join(recordsDir, name, 'run.json'), 'utf8'));
+ return (run.pr as { number?: number } | undefined)?.number;
+ } catch {
+ return undefined;
+ }
+};
+
+export const newestRun = async (recordsDir: string, anchor: string, pr?: number) => {
+ const pinned = parseRunName(anchor);
+ if (!pinned) return anchor;
+ const entries = await readdir(recordsDir, { withFileTypes: true }).catch(() => []);
+ const candidates = entries
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => parseRunName(entry.name))
+ .filter((run): run is RunName => !!run && run.base === pinned.base && run.order > pinned.order)
+ .sort((left, right) => right.order - left.order);
+ for (const run of candidates) {
+ if (!isComplete(recordsDir, run.name)) continue;
+ if (pr === undefined || (await prOf(recordsDir, run.name)) === pr) return run.name;
+ }
+ return anchor;
+};
+
+export interface FollowInfo {
+ base: string;
+ head: string;
+ pinned: boolean;
+ requested: string;
+ runId: string;
+ startedAt?: string;
+}
+
+export const createRunSource = async ({
+ pin = false,
+ recordsDir,
+ runDir,
+}: {
+ pin?: boolean;
+ recordsDir: string;
+ runDir: string;
+}) => {
+ const anchor = path.basename(runDir);
+ let loaded = { dir: runDir, stored: await loadRun(runDir) };
+ const pr = (loaded.stored.run.pr as { number?: number } | undefined)?.number;
+ let pending: Promise<typeof loaded> | undefined;
+ const refresh = async () => {
+ const name = await newestRun(recordsDir, anchor, pr);
+ const dir = name === anchor ? runDir : path.join(recordsDir, name);
+ if (dir === loaded.dir) return loaded;
+ try {
+ loaded = { dir, stored: await loadRun(dir) };
+ } catch {
+ return loaded;
+ }
+ return loaded;
+ };
+ const current = async (): Promise<{ dir: string; stored: StoredRun }> => {
+ if (pin) return loaded;
+ pending ??= refresh().finally(() => {
+ pending = undefined;
+ });
+ return pending;
+ };
+ const info = (stored: StoredRun, dir: string): FollowInfo => ({
+ base: String(stored.run.base ?? ''),
+ head: String(stored.run.head ?? ''),
+ pinned: pin,
+ requested: anchor,
+ runId: path.basename(dir),
+ startedAt: parseRunName(path.basename(dir))?.startedAt,
+ });
+ return { current, info };
+};
diff --git a/packages/style-equivalence/src/server/index.ts b/packages/style-equivalence/src/server/index.ts
new file mode 100644
index 00000000000..0a25d2e738f
--- /dev/null
+++ b/packages/style-equivalence/src/server/index.ts
@@ -0,0 +1,207 @@
+import { createReadStream, existsSync } from 'node:fs';
+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import path from 'node:path';
+
+import type { Browser } from '@playwright/test';
+
+import { analyzeRun } from '../analyze/diff';
+import { launchBrowser } from '../capture/browser';
+import { captureRun } from '../capture/runner';
+import type { CaptureState } from '../capture/states';
+import { resolveInside } from '../capture/staticServer';
+import type { ConditionConfig } from '../config';
+import { SELF_TEST_FILE } from '../selftest/store';
+import {
+ ApiError,
+ applySignoff,
+ caseDetail,
+ currentVerdict,
+ readSelfTest,
+ type StoredRun,
+} from './api';
+import { createRunSource } from './follow';
+import { caseShot, caseSnapshot, parseCombo, parseCondition } from './inspectCase';
+import { applyReview, caseReview, reviewPayload } from './review';
+
+const TYPES: Record<string, string> = {
+ '.css': 'text/css',
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript',
+ '.json': 'application/json',
+ '.png': 'image/png',
+ '.svg': 'image/svg+xml',
+ '.woff2': 'font/woff2',
+};
+
+export const DEFAULT_UI_DIR = path.resolve(import.meta.dirname, '../../ui/dist');
+const MAX_BODY = 1024 * 1024;
+
+const PLACEHOLDER =
+ '<!doctype html><meta charset="utf-8"><title>style-equivalence</title><p>The report UI is not built. The API is at <a href="/api/run">/api/run</a>.</p>';
+
+const readBody = (request: IncomingMessage) =>
+ new Promise<unknown>((resolve, reject) => {
+ let size = 0;
+ const chunks: Buffer[] = [];
+ request.on('data', (chunk: Buffer) => {
+ size += chunk.length;
+ if (size > MAX_BODY) reject(new ApiError(413, 'BODY_TOO_LARGE'));
+ else chunks.push(chunk);
+ });
+ request.on('end', () => {
+ try {
+ resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {});
+ } catch {
+ reject(new ApiError(400, 'INVALID_JSON'));
+ }
+ });
+ request.on('error', reject);
+ });
+
+const json = (response: ServerResponse, status: number, value: unknown) => {
+ response.writeHead(status, { 'content-type': 'application/json' });
+ response.end(JSON.stringify(value));
+};
+
+const sendFile = async (response: ServerResponse, root: string, requestPath: string) => {
+ const file = existsSync(root) ? await resolveInside(root, requestPath) : undefined;
+ if (!file) return false;
+ response.writeHead(200, {
+ 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream',
+ });
+ createReadStream(file).pipe(response);
+ return true;
+};
+
+export interface ServerOptions {
+ layoutComponents?: string[];
+ pin?: boolean;
+ port?: number;
+ recordsDir?: string;
+ runDir: string;
+ uiDir?: string;
+}
+
+export const startServer = async ({
+ layoutComponents = [],
+ pin = false,
+ port = 0,
+ recordsDir,
+ runDir,
+ uiDir = DEFAULT_UI_DIR,
+}: ServerOptions) => {
+ const selfTestFile = path.join(recordsDir ?? path.dirname(runDir), SELF_TEST_FILE);
+ const source = await createRunSource({
+ pin,
+ recordsDir: recordsDir ?? path.dirname(runDir),
+ runDir,
+ });
+ let browser: Browser | undefined;
+ let url = '';
+ const rerun = async (stored: StoredRun, key: string) => {
+ browser ??= await launchBrowser();
+ const conditions = stored.run.conditionConfig as ConditionConfig | undefined;
+ if (!conditions) throw new ApiError(409, 'RUN_HAS_NO_CONDITIONS');
+ const cases = encodeURIComponent(JSON.stringify([key]));
+ const capture = await captureRun({
+ browser,
+ conditions,
+ states: stored.run.states as CaptureState[] | undefined,
+ urls: { base: `${url}/base/#cases=${cases}`, head: `${url}/head/#cases=${cases}` },
+ });
+ const [result] = analyzeRun(capture);
+ if (!result) throw new ApiError(404, `CASE_NOT_RENDERED:${key}`);
+ return { result };
+ };
+ const route = async (request: IncomingMessage, response: ServerResponse) => {
+ const { pathname, searchParams } = new URL(request.url ?? '/', 'http://x');
+ const method = request.method ?? 'GET';
+ const { dir, stored } = await source.current();
+ const follow = source.info(stored, dir);
+ if (pathname === '/api/current' && method === 'GET') return json(response, 200, follow);
+ if (pathname === '/api/run' && method === 'GET')
+ return json(response, 200, {
+ calibration: stored.calibration,
+ cases: stored.results.cases,
+ follow,
+ mutation: stored.mutation,
+ run: stored.run,
+ verdict: await currentVerdict(stored),
+ });
+ if (pathname === '/api/review' && method === 'GET')
+ return json(response, 200, { ...(await reviewPayload(stored, layoutComponents)), follow });
+ if (pathname === '/api/review' && method === 'POST')
+ return json(response, 200, {
+ ...(await applyReview(stored, (await readBody(request)) as never)),
+ follow,
+ });
+ if (pathname === '/api/method' && method === 'GET')
+ return json(response, 200, { selfTest: await readSelfTest(selfTestFile) });
+ const caseMatch = /^\/api\/case\/([^/]+)(?:\/(rerun|review|snapshot|shot))?$/.exec(pathname);
+ if (caseMatch) {
+ const key = decodeURIComponent(caseMatch[1]);
+ const action = caseMatch[2];
+ if (action === 'rerun' && method === 'POST')
+ return json(response, 200, await rerun(stored, key));
+ if (!action && method === 'GET') return json(response, 200, await caseDetail(stored, key));
+ if (action === 'review' && method === 'GET')
+ return json(response, 200, await caseReview(stored, key, layoutComponents));
+ if ((action === 'snapshot' || action === 'shot') && method === 'GET') {
+ browser ??= await launchBrowser();
+ const inspect = {
+ browser,
+ combo: parseCombo(searchParams.get('combo')),
+ condition: parseCondition(searchParams.get('condition')),
+ key,
+ url,
+ };
+ if (action === 'snapshot') return json(response, 200, await caseSnapshot(inspect));
+ const side = searchParams.get('side');
+ if (side !== 'base' && side !== 'head') throw new ApiError(400, 'INVALID_SIDE');
+ const image = await caseShot({
+ ...inspect,
+ crop: searchParams.get('crop') === '1',
+ reveal: searchParams.get('reveal') === '1',
+ side,
+ });
+ response.writeHead(200, { 'cache-control': 'max-age=3600', 'content-type': 'image/png' });
+ response.end(image);
+ return;
+ }
+ }
+ if (pathname === '/api/signoff' && method === 'POST')
+ return json(response, 200, await applySignoff(stored, (await readBody(request)) as never));
+ if (pathname.startsWith('/api/')) return json(response, 404, { error: 'NOT_FOUND' });
+ for (const [prefix, directory] of [
+ ['/base/', 'dist-base'],
+ ['/head/', 'dist-head'],
+ ] as const)
+ if (pathname.startsWith(prefix)) {
+ if (
+ !(await sendFile(response, path.join(dir, directory), pathname.slice(prefix.length - 1)))
+ )
+ json(response, 404, { error: 'NOT_FOUND' });
+ return;
+ }
+ if (await sendFile(response, uiDir, pathname)) return;
+ if (existsSync(uiDir) && (await sendFile(response, uiDir, '/'))) return;
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ response.end(PLACEHOLDER);
+ };
+ const server = createServer((request, response) => {
+ route(request, response).catch((error: unknown) => {
+ const status = error instanceof ApiError ? error.status : 500;
+ json(response, status, { error: error instanceof Error ? error.message : String(error) });
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ return {
+ stop: async () => {
+ await browser?.close();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ },
+ url,
+ };
+};
diff --git a/packages/style-equivalence/src/server/inspectCase.ts b/packages/style-equivalence/src/server/inspectCase.ts
new file mode 100644
index 00000000000..e16b0d76f09
--- /dev/null
+++ b/packages/style-equivalence/src/server/inspectCase.ts
@@ -0,0 +1,150 @@
+import type { Browser } from '@playwright/test';
+
+import { ownDifferences } from '../analyze/diff';
+import { capturePage, type PageCondition, type SectionSnapshot } from '../capture/runner';
+import { compareSnapshots, type StyleSnapshot } from '../capture/snapshot';
+import type { CaptureState } from '../capture/states';
+import type { ConditionVariant } from '../config';
+import { ApiError } from './api';
+import { revealCase } from './reveal';
+
+const STATE = /^(default|hover-chain|hover-target|focus-visible|force(-chain)?:[a-z+-]+)$/;
+const VARIANTS = new Set(['reduced-motion', 'rtl']);
+
+export const parseCondition = (label: string | null): PageCondition => {
+ const [theme, width, state, variant] = (label ?? '').split('/');
+ const pixels = Number(width);
+ if (
+ !theme ||
+ !/^[\w-]+$/.test(theme) ||
+ !Number.isInteger(pixels) ||
+ pixels < 200 ||
+ pixels > 4000
+ )
+ throw new ApiError(400, 'INVALID_CONDITION');
+ if (!STATE.test(state ?? '') || (variant && !VARIANTS.has(variant)))
+ throw new ApiError(400, 'INVALID_CONDITION');
+ return {
+ state: state as CaptureState,
+ theme,
+ variant: variant as ConditionVariant | undefined,
+ width: pixels,
+ };
+};
+
+export const parseCombo = (value: string | null) => {
+ const combo = Number(value ?? 0);
+ if (!Number.isInteger(combo) || combo < 0 || combo > 4096)
+ throw new ApiError(400, 'INVALID_COMBO');
+ return combo;
+};
+
+const isSnapshot = (
+ value: SectionSnapshot | undefined,
+): value is StyleSnapshot & { targetKey?: string } => Boolean(value && !('error' in value));
+
+interface CaseRequest {
+ browser: Browser;
+ combo: number;
+ condition: PageCondition;
+ key: string;
+ url: string;
+}
+
+const pageUrl = (url: string, side: 'base' | 'head', key: string, combo: number) =>
+ `${url}/${side}/?case=${encodeURIComponent(key)}&combo=${combo}`;
+
+const sectionOf = async (request: CaseRequest, side: 'base' | 'head') => {
+ const errors: string[] = [];
+ const { page, snapshots } = await capturePage(
+ request.browser,
+ pageUrl(request.url, side, request.key, request.combo),
+ request.condition,
+ errors,
+ );
+ await page.close();
+ return snapshots[`${request.key}|${request.combo}`];
+};
+
+const targetOf = (snapshot: SectionSnapshot | undefined) => {
+ if (!isSnapshot(snapshot))
+ return { error: snapshot ? (snapshot as { error: string }).error : 'CASE_NOT_RENDERED' };
+ const targetKey = snapshot.targetKey ?? 'root';
+ const node = snapshot.nodes.find((item) => item.key === targetKey);
+ return {
+ target: node && {
+ box: node.box,
+ key: node.key,
+ tag: node.tag,
+ values: snapshot.styles[node.style],
+ },
+ targetKey,
+ };
+};
+
+export const caseSnapshot = async (request: CaseRequest) => {
+ const [base, head] = await Promise.all([sectionOf(request, 'base'), sectionOf(request, 'head')]);
+ const all =
+ isSnapshot(base) && isSnapshot(head)
+ ? ownDifferences(compareSnapshots(base, head), base.targetKey ?? 'root')
+ : [];
+ return {
+ base: targetOf(base),
+ differences: all.filter((item) => !item.diagnosticReason),
+ head: targetOf(head),
+ ignored: all
+ .filter((item) => item.diagnosticReason)
+ .map(({ diagnosticReason, key, property }) => ({ key, property, reason: diagnosticReason! })),
+ };
+};
+
+const CROP_PADDING = 16;
+
+export const cropClip = (
+ page: { height: number; width: number },
+ origin: { x: number; y: number },
+ box: number[],
+ padding: number,
+) => {
+ const [x, y, width, height] = box;
+ const left = Math.max(0, origin.x + x - padding);
+ const top = Math.max(0, origin.y + y - padding);
+ const right = Math.min(page.width, origin.x + x + width + padding);
+ const bottom = Math.min(page.height, origin.y + y + height + padding);
+ return { height: bottom - top, width: right - left, x: left, y: top };
+};
+
+export const caseShot = async (
+ request: CaseRequest & { crop?: boolean; reveal?: boolean; side: 'base' | 'head' },
+) => {
+ const errors: string[] = [];
+ const { page, snapshots } = await capturePage(
+ request.browser,
+ pageUrl(request.url, request.side, request.key, request.combo),
+ request.condition,
+ errors,
+ );
+ try {
+ const section = page.locator(
+ `[data-case="${`${request.key}|${request.combo}`.replaceAll('"', '\\"')}"]`,
+ );
+ if (!(await section.count())) throw new ApiError(404, 'CASE_NOT_RENDERED');
+ const snapshot = snapshots[`${request.key}|${request.combo}`];
+ if (request.reveal && isSnapshot(snapshot))
+ await revealCase(page, `${request.key}|${request.combo}`, snapshot.targetKey ?? 'root');
+ const target = request.crop && isSnapshot(snapshot) ? targetOf(snapshot).target : undefined;
+ const origin = target ? await section.boundingBox() : null;
+ if (!target || !origin || target.box[2] <= 0 || target.box[3] <= 0)
+ return await section.screenshot({ animations: 'disabled' });
+ const bounds = await page.evaluate(() => ({
+ height: document.documentElement.scrollHeight,
+ width: document.documentElement.scrollWidth,
+ }));
+ return await page.screenshot({
+ animations: 'disabled',
+ clip: cropClip(bounds, origin, target.box, CROP_PADDING),
+ });
+ } finally {
+ await page.close();
+ }
+};
diff --git a/packages/style-equivalence/src/server/reveal.test.ts b/packages/style-equivalence/src/server/reveal.test.ts
new file mode 100644
index 00000000000..cff3888ec54
--- /dev/null
+++ b/packages/style-equivalence/src/server/reveal.test.ts
@@ -0,0 +1,126 @@
+import type { Browser, Page } from '@playwright/test';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { launchBrowser } from '../capture/browser';
+import { REVEAL_COLORS, revealCase } from './reveal';
+
+let browser: Browser;
+
+beforeAll(async () => {
+ browser = await launchBrowser();
+});
+
+afterAll(async () => {
+ await browser?.close();
+});
+
+const CASE = 'a.tsx|A#0|0';
+
+const openClipped = async () => {
+ const page = await browser.newPage({ viewport: { height: 200, width: 400 } });
+ await page.setContent(`<!doctype html><html><head><style>
+body { margin: 0; background: #fff; }
+.lane { position: relative; overflow: hidden; }
+.t { position: absolute; top: 0; left: 0; width: 40px; height: 40px; background: #00ff00; }
+</style></head><body>
+<section data-case="${CASE}" style="box-sizing:border-box;width:360px;padding:40px;position:relative">
+<div data-synthetic-element="A#0" class="lane"><div data-synthetic-element="A#1" class="t"></div></div>
+</section></body></html>`);
+ return page;
+};
+
+const open = async (targetCss: string) => {
+ const page = await browser.newPage({ viewport: { height: 200, width: 400 } });
+ await page.setContent(`<!doctype html><html><head><style>
+body { margin: 0; background: #fff; }
+.t { ${targetCss} }
+</style></head><body>
+<section data-case="${CASE}" style="box-sizing:border-box;width:360px;padding:40px;position:relative">
+<div data-synthetic-element="A#0"><div data-synthetic-element="A#1" class="t"></div></div>
+</section></body></html>`);
+ return page;
+};
+
+const pixels = (page: Page, image: Buffer, points: Array<[number, number]>) =>
+ page.evaluate(
+ async ({ data, points }) => {
+ const img = new Image();
+ img.src = `data:image/png;base64,${data}`;
+ await img.decode();
+ const canvas = document.createElement('canvas');
+ canvas.width = img.width;
+ canvas.height = img.height;
+ const context = canvas.getContext('2d')!;
+ context.drawImage(img, 0, 0);
+ return points.map(([x, y]) => {
+ const [r, g, b] = context.getImageData(x, y, 1, 1).data;
+ return `#${[r, g, b].map((value) => value.toString(16).padStart(2, '0')).join('')}`;
+ });
+ },
+ { data: image.toString('base64'), points },
+ );
+
+const hex = (color: string) => color.toLowerCase();
+
+const column = (x: number, from: number, to: number) =>
+ Array.from({ length: to - from + 1 }, (_, index): [number, number] => [x, from + index]);
+
+describe('revealCase', () => {
+ it('makes a white box on a white page visible and outlines it', async () => {
+ const page = await open('width: 40px; height: 40px; background: #fff;');
+ const clip = { height: 120, width: 120, x: 0, y: 0 };
+ const before = await pixels(page, await page.screenshot({ clip }), [
+ [5, 5],
+ [60, 60],
+ ]);
+ expect(before).toEqual(['#ffffff', '#ffffff']);
+
+ expect(await revealCase(page, CASE, 'root.0.0')).toBe(true);
+ const [backdrop, inside, ...edge] = await pixels(page, await page.screenshot({ clip }), [
+ [5, 5],
+ [60, 60],
+ ...column(37, 42, 78),
+ ]);
+ expect(backdrop).not.toBe('#ffffff');
+ expect(inside).toBe('#ffffff');
+ const [outsideSection] = await pixels(
+ page,
+ await page.screenshot({ clip: { height: 40, width: 40, x: 360, y: 150 } }),
+ [[20, 20]],
+ );
+ expect(outsideSection).not.toBe('#ffffff');
+ expect(edge).toContain(hex(REVEAL_COLORS.element));
+ await page.close();
+ });
+
+ it('outlines a pseudo-element of the target', async () => {
+ const page = await open(
+ "position: relative; width: 40px; height: 40px; &::before { content: ''; position: absolute; left: 50px; top: 0; width: 20px; height: 20px; background: #fff; }",
+ );
+ await revealCase(page, CASE, 'root.0.0');
+ const edge = await pixels(
+ page,
+ await page.screenshot({ clip: { height: 120, width: 200, x: 0, y: 0 } }),
+ column(87, 41, 59),
+ );
+ expect(edge).toContain(hex(REVEAL_COLORS.pseudo));
+ await page.close();
+ });
+
+ it('shows a target clipped by an ancestor that collapsed to zero height', async () => {
+ const page = await openClipped();
+ const clip = { height: 120, width: 120, x: 0, y: 0 };
+ const [before] = await pixels(page, await page.screenshot({ clip }), [[60, 60]]);
+ expect(before).toBe('#ffffff');
+ await revealCase(page, CASE, 'root.0.0');
+ const [after] = await pixels(page, await page.screenshot({ clip }), [[60, 60]]);
+ expect(after).toBe('#00ff00');
+ await page.close();
+ });
+
+ it('reports a target key that does not exist', async () => {
+ const page = await open('width: 40px; height: 40px;');
+ expect(await revealCase(page, CASE, 'root.4')).toBe(false);
+ await page.close();
+ });
+});
diff --git a/packages/style-equivalence/src/server/reveal.ts b/packages/style-equivalence/src/server/reveal.ts
new file mode 100644
index 00000000000..9db3d0aeeaf
--- /dev/null
+++ b/packages/style-equivalence/src/server/reveal.ts
@@ -0,0 +1,59 @@
+import type { Page } from '@playwright/test';
+
+export const REVEAL_COLORS = {
+ checker: ['#a3a3a3', '#d6d6d6'],
+ element: '#ff2d9b',
+ pseudo: '#1e90ff',
+} as const;
+
+const OUTLINE_GAP = 2;
+
+export const revealCase = (page: Page, caseKey: string, targetKey: string) =>
+ page.evaluate(
+ ({ caseKey, colors, gap, targetKey }) => {
+ const section = document.querySelector<HTMLElement>(`[data-case="${CSS.escape(caseKey)}"]`);
+ if (!section) return false;
+ const skip = (element: Element) =>
+ ['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName);
+ let target: Element | undefined = section;
+ for (const index of targetKey.split('.').slice(1).map(Number))
+ target = target ? [...target.children].filter((child) => !skip(child))[index] : undefined;
+ if (!target || target === section) return false;
+ for (const backdrop of [document.documentElement, document.body])
+ backdrop.style.setProperty(
+ 'background',
+ `repeating-conic-gradient(${colors.checker[0]} 0 25%, ${colors.checker[1]} 0 50%) 0 0 / 12px 12px`,
+ 'important',
+ );
+ for (let node = target.parentElement; node && node !== section; node = node.parentElement) {
+ const box = node.getBoundingClientRect();
+ const { overflowX, overflowY } = getComputedStyle(node);
+ if (
+ (box.width === 0 || box.height === 0) &&
+ (overflowX !== 'visible' || overflowY !== 'visible')
+ )
+ node.style.setProperty('overflow', 'visible', 'important');
+ }
+ target.setAttribute('data-synthetic-reveal', '');
+ const style = document.createElement('style');
+ style.textContent = `[data-synthetic-reveal]::before,[data-synthetic-reveal]::after{outline:1px dashed ${colors.pseudo} !important;outline-offset:${gap}px !important}`;
+ document.head.append(style);
+ const rect = target.getBoundingClientRect();
+ const overlay = document.createElement('div');
+ overlay.setAttribute('data-synthetic-overlay', '');
+ Object.assign(overlay.style, {
+ height: `${rect.height}px`,
+ left: `${rect.left + scrollX}px`,
+ outline: `1px dashed ${colors.element}`,
+ outlineOffset: `${gap}px`,
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: `${rect.top + scrollY}px`,
+ width: `${rect.width}px`,
+ zIndex: '2147483647',
+ });
+ document.body.append(overlay);
+ return true;
+ },
+ { caseKey, colors: REVEAL_COLORS, gap: OUTLINE_GAP, targetKey },
+ );
diff --git a/packages/style-equivalence/src/server/review.test.ts b/packages/style-equivalence/src/server/review.test.ts
new file mode 100644
index 00000000000..a7a23bec7b6
--- /dev/null
+++ b/packages/style-equivalence/src/server/review.test.ts
@@ -0,0 +1,341 @@
+import { mkdir, mkdtemp, readFile, 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 { annotateList, applyNotes, reworkList } from '../cli/review';
+import { loadRun } from './api';
+import { startServer } from './index';
+
+let root: string;
+let runDir: string;
+let server: Awaited<ReturnType<typeof startServer>>;
+
+const element = (id: string, tag: string, slots: string[], extra: object = {}) => ({
+ bindings: [{ expr: slots[0], prop: 'className', spread: false }],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: id.split('#')[0],
+ slots,
+ tag,
+ variables: [],
+ ...extra,
+});
+
+const kase = (
+ id: string,
+ category: string,
+ flags: string[],
+ combos: object[] = [{}],
+ extra: object = {},
+) => ({
+ category,
+ key: `src/A.tsx|${id}`,
+ plan: {
+ combos,
+ elementIds: { base: id, head: id },
+ file: 'src/A.tsx',
+ flags,
+ key: `src/A.tsx|${id}`,
+ variables: [],
+ ...extra,
+ },
+ result: {
+ comboDifferences: [],
+ differingConditions: category === 'difference' ? ['light/1280/default'] : [],
+ errors: [],
+ gaps: [],
+ rootCauses:
+ category === 'difference'
+ ? [{ after: 'red', before: 'black', key: 'root', property: 'color' }]
+ : [],
+ status: category === 'difference' ? 'difference' : 'equal',
+ unstableConditions: [],
+ },
+});
+
+const verdictItem = (id: string, category: string, flags: string[]) => ({
+ category,
+ file: 'src/A.tsx',
+ flags,
+ hash: `hash-${id}`,
+ key: `src/A.tsx|${id}`,
+});
+
+const write = (name: string, value: unknown) =>
+ writeFile(path.join(runDir, name), JSON.stringify(value));
+
+beforeAll(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-review-'));
+ runDir = path.join(root, 'run-1');
+ await mkdir(runDir, { recursive: true });
+ await write('run.json', {
+ base: 'a'.repeat(40),
+ conditions: ['light/1280/default', 'dark/1280/default'],
+ head: 'b'.repeat(40),
+ pr: { branch: 'style/x', number: 21054, title: 'move builtin tool styles' },
+ runId: 'run-1',
+ });
+ await write('results.json', {
+ cases: [
+ kase('A#0', 'difference', []),
+ kase('A#1', 'needs-signoff', ['VARIABLE_UNMODELED'], [{ online: false }, { online: true }]),
+ kase('A#2', 'needs-signoff', ['PLACEMENT_SUBSTITUTED'], [{}], {
+ standIns: { head: ['SkillsIcon'] },
+ }),
+ kase('A#3', 'equal', []),
+ ],
+ });
+ await write('verdict.json', {
+ items: [
+ verdictItem('A#0', 'difference', []),
+ verdictItem('A#1', 'needs-signoff', ['VARIABLE_UNMODELED']),
+ verdictItem('A#2', 'needs-signoff', ['PLACEMENT_SUBSTITUTED']),
+ verdictItem('A#3', 'equal', []),
+ ],
+ });
+ await write('extractions.json', {
+ 'src/A.tsx': {
+ base: { elements: [] },
+ head: {
+ elements: [
+ element('A#0', 'span', ['styles.a']),
+ element('A#1', 'span', ['styles.dot'], {
+ variables: [{ kind: 'unknown', name: 'device' }],
+ }),
+ element('A#2', 'SkillsIcon', ['styles.icon']),
+ element('A#3', 'div', ['styles.box']),
+ ],
+ },
+ },
+ });
+ await write('mutation.json', { passed: true });
+ await write('calibration.json', []);
+ await write('evidence.json', {
+ 'src/A.tsx|A#0': {
+ declarations: {
+ base: { 'styles.a': 'a: css`\n color: black;\n padding: 4px;\n `' },
+ head: { 'styles.a': "a: {\n color: 'red',\n padding: '4px',\n }" },
+ },
+ elements: {
+ base: [
+ {
+ bindings: [{ expr: 'styles.a', prop: 'className', spread: false }],
+ literalProps: {},
+ slots: ['styles.a'],
+ tag: 'span',
+ },
+ ],
+ head: [
+ {
+ bindings: [{ expr: 'stylex.props(styles.a)', prop: '...', spread: true }],
+ literalProps: {},
+ slots: ['styles.a'],
+ tag: 'span',
+ },
+ ],
+ },
+ },
+ 'src/A.tsx|A#2': {
+ declarations: {
+ base: {
+ 'styles.icon': 'icon: css`\n color: red;\n `',
+ 'styles.row': 'row: css`\n gap: 4px;\n `',
+ },
+ head: { 'styles.icon': "icon: { color: 'red' }", 'styles.row': "row: { gap: '4px' }" },
+ },
+ elements: {
+ head: [
+ { bindings: [], literalProps: {}, slots: ['styles.icon'], tag: 'SkillsIcon' },
+ { bindings: [], literalProps: {}, slots: ['styles.row'], tag: 'Flexbox' },
+ ],
+ },
+ },
+ });
+ server = await startServer({ layoutComponents: ['Flexbox'], runDir });
+});
+
+afterAll(async () => {
+ await server?.stop();
+ await rm(root, { force: true, recursive: true });
+});
+
+const post = (body: unknown) =>
+ fetch(`${server.url}/api/review`, {
+ body: JSON.stringify(body),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+const queue = async () => (await (await fetch(`${server.url}/api/review`)).json()) as any;
+
+describe('review API', () => {
+ it('lists only items that need a person, with plain prompts and PR info', async () => {
+ const payload = await queue();
+ expect(payload.items.map((entry: any) => entry.key)).toEqual([
+ 'src/A.tsx|A#0',
+ 'src/A.tsx|A#1',
+ 'src/A.tsx|A#2',
+ ]);
+ const variable = payload.items.find((entry: any) => entry.key === 'src/A.tsx|A#1');
+ expect(variable).toMatchObject({ canPass: true, state: 'todo' });
+ expect(variable.ask).toContain('取决于 device');
+ expect(variable.combos.map((combo: any) => combo.label)).toEqual(['online:否', 'online:是']);
+ const difference = payload.items.find((entry: any) => entry.key === 'src/A.tsx|A#0');
+ expect(difference.summary).toEqual(['文字颜色 black → red']);
+ expect(difference.canPass).toBe(false);
+ expect(difference.styles.blocks).toEqual([
+ {
+ rows: [
+ {
+ after: ['color: red'],
+ before: ['color: black'],
+ differs: true,
+ label: 'color',
+ oneSided: false,
+ },
+ {
+ after: ['padding: 4px'],
+ before: ['padding: 4px'],
+ differs: false,
+ label: 'padding',
+ oneSided: false,
+ },
+ ],
+ slot: 'a',
+ },
+ ]);
+ expect(difference.styles.source.head['styles.a']).toContain("color: 'red'");
+ expect(difference.styles.usage).toEqual({
+ base: ['<span className={styles.a}>'],
+ head: ['<span {...stylex.props(styles.a)}>'],
+ });
+ expect(variable.styles).toEqual({ blocks: [], 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'],
+ ['row', undefined],
+ ]);
+ expect(placed.standIns).toEqual({ head: ['SkillsIcon'] });
+ expect(difference.standIns).toEqual({});
+ expect(payload.items.find((entry: any) => entry.key === 'src/A.tsx|A#2').state).toBe(
+ 'waiting-agent',
+ );
+ expect(payload.pr).toMatchObject({ number: 21054 });
+ expect(payload.counts).toMatchObject({ proven: 1, total: 4 });
+ });
+
+ it('describes any case for the case page and says whether it sits in the review queue', async () => {
+ const view = async (key: string) =>
+ (await fetch(`${server.url}/api/case/${encodeURIComponent(key)}/review`)).json() as any;
+ const equal = await view('src/A.tsx|A#3');
+ expect(equal.queued).toBe(false);
+ expect(equal.conditions).toEqual(['light/1280/default', 'dark/1280/default']);
+ expect(equal.item).toMatchObject({ canPass: false, category: 'equal', key: 'src/A.tsx|A#3' });
+ expect(equal.item.combos).toHaveLength(1);
+ const difference = await view('src/A.tsx|A#0');
+ expect(difference.queued).toBe(true);
+ expect(difference.item.summary).toEqual(['文字颜色 black → red']);
+ const missing = await fetch(
+ `${server.url}/api/case/${encodeURIComponent('src/A.tsx|Z#9')}/review`,
+ );
+ expect(missing.status).toBe(404);
+ });
+
+ it('records a pass in the records reviews', async () => {
+ const response = await post({
+ action: 'pass',
+ key: 'src/A.tsx|A#1',
+ note: '',
+ reviewer: 'innei',
+ });
+ expect(response.status).toBe(200);
+ expect((await queue()).items.find((entry: any) => entry.key === 'src/A.tsx|A#1').state).toBe(
+ 'passed',
+ );
+ const stored = JSON.parse(await readFile(path.join(root, 'reviews/src/A.tsx.json'), 'utf8'));
+ expect(stored.passes[0]).toMatchObject({ key: 'src/A.tsx|A#1', reason: 'REVIEW_PASS' });
+ });
+
+ it('requires a note to send back an item without a rendered difference and refuses passes that are not allowed', async () => {
+ expect((await post({ action: 'rework', key: 'src/A.tsx|A#1', note: '' })).status).toBe(400);
+ expect((await post({ action: 'rework', key: 'src/A.tsx|A#2', note: ' ' })).status).toBe(400);
+ const generated = await post({
+ action: 'rework',
+ key: 'src/A.tsx|A#0',
+ note: '',
+ reviewer: 'innei',
+ });
+ expect(generated.status).toBe(200);
+ expect(
+ (await generated.json()).items.find((entry: any) => entry.key === 'src/A.tsx|A#0').rework
+ .note,
+ ).toBe('不一样:文字颜色 black → red');
+ expect((await post({ action: 'pass', key: 'src/A.tsx|A#0', note: '误报' })).status).toBe(409);
+ expect((await post({ action: 'pass', key: 'src/A.tsx|A#2', note: '' })).status).toBe(409);
+ expect(
+ (
+ await post({
+ action: 'rework',
+ key: 'src/A.tsx|A#0',
+ note: '颜色变红了',
+ reviewer: 'innei',
+ })
+ ).status,
+ ).toBe(200);
+ const payload = await queue();
+ const reworked = payload.items.find((entry: any) => entry.key === 'src/A.tsx|A#0');
+ expect(reworked.state).toBe('reworked');
+ expect(reworked.rework.note).toBe('颜色变红了');
+ expect(payload.verdict.reasons).toContain('rework open 1');
+ });
+});
+
+describe('rework scope', () => {
+ it('does not resolve or show a send-back that belongs to another PR', async () => {
+ const file = path.join(root, 'reviews/src/A.tsx.json');
+ const stored = JSON.parse(await readFile(file, 'utf8'));
+ stored.reworks.push({
+ at: '2026-11-05T00:00:00Z',
+ base: 'x',
+ elementSignature: 'div|styles.box',
+ file: 'src/A.tsx',
+ hash: 'other-hash',
+ head: 'y',
+ key: 'src/A.tsx|A#3',
+ note: '别的 PR 的打回',
+ pr: 99_999,
+ reviewer: 'innei',
+ runId: 'other-run',
+ });
+ await writeFile(file, JSON.stringify(stored));
+ const payload = await queue();
+ expect(payload.resolved.map((entry: any) => entry.key)).not.toContain('src/A.tsx|A#3');
+ const after = JSON.parse(await readFile(file, 'utf8'));
+ expect(after.reworks.find((entry: any) => entry.pr === 99_999).resolvedAt).toBeUndefined();
+ });
+});
+
+describe('rework and annotate commands', () => {
+ it('prints open reworks with the element and the reviewer note', async () => {
+ const text = await reworkList(await loadRun(runDir));
+ expect(text).toContain('#21054');
+ expect(text).toContain('A#0');
+ expect(text).toContain('颜色变红了');
+ });
+
+ it('lists agent-read items and stores notes bound to the current hash', 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' },
+ ]);
+ 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('className 落在根 svg 上');
+ });
+});
diff --git a/packages/style-equivalence/src/server/review.ts b/packages/style-equivalence/src/server/review.ts
new file mode 100644
index 00000000000..79b05b668c8
--- /dev/null
+++ b/packages/style-equivalence/src/server/review.ts
@@ -0,0 +1,331 @@
+import type { StyleElement } from '../extract';
+import type { Combo } from '../plan/combos';
+import { 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 {
+ elementSignature,
+ passRecord,
+ resolvedReworks,
+ type ReviewItem,
+ reviewItems,
+ reworkRecord,
+} from '../review/state';
+import { type ReworkRecord, writeReviews } from '../review/store';
+import {
+ ApiError,
+ currentVerdict,
+ defaultSigner,
+ readRunReviews,
+ runPr,
+ type StoredRun,
+} from './api';
+
+type Sides<T> = Partial<Record<'base' | 'head', T>>;
+
+interface CaseEntry {
+ category: string;
+ key: string;
+ plan: {
+ combos?: Combo[];
+ elementIds?: { base: string; head: string };
+ file: string;
+ standIns?: Sides<string[]>;
+ };
+ result?: {
+ comboDifferences?: Array<{
+ combo: number;
+ condition: string;
+ rootCauses: Array<{ after?: string; before?: string; key: string; property: string }>;
+ }>;
+ differingConditions?: string[];
+ errors?: string[];
+ rootCauses?: Array<{ after?: string; before?: string; key: string; property: string }>;
+ };
+}
+
+interface CaseEvidence {
+ declarations?: Partial<Record<'base' | 'head', Record<string, string>>>;
+ elements?: Partial<
+ Record<
+ 'base' | 'head',
+ Array<{ bindings: StyleElement['bindings']; slots?: string[]; tag: string }>
+ >
+ >;
+}
+
+const usageOf = (element: { bindings: StyleElement['bindings']; tag: string }) => {
+ const props = element.bindings.map((binding) =>
+ binding.spread ? `{...${binding.expr}}` : `${binding.prop}={${binding.expr}}`,
+ );
+ return `<${[element.tag, ...props].join(' ')}>`;
+};
+
+const standIns = (evidence: CaseEvidence | undefined, layout: Set<string>) => {
+ const tags = new Map<string, string>();
+ for (const side of ['head', 'base'] as const)
+ for (const element of evidence?.elements?.[side] ?? [])
+ if (!isIntrinsicTag(element.tag) && !layout.has(element.tag))
+ for (const slot of element.slots ?? []) if (!tags.has(slot)) tags.set(slot, element.tag);
+ return tags;
+};
+
+const stylesOf = (
+ entry: CaseEntry | undefined,
+ evidence: CaseEvidence | undefined,
+ layout: Set<string>,
+) => {
+ const causes = [
+ ...(entry?.result?.rootCauses ?? []),
+ ...(entry?.result?.comboDifferences ?? []).flatMap((difference) => difference.rootCauses),
+ ];
+ const source = Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) => {
+ const declarations = evidence?.declarations?.[side];
+ return declarations && Object.keys(declarations).length ? [[side, declarations]] : [];
+ }),
+ );
+ return {
+ blocks: evidence?.declarations
+ ? declarationBlocks(
+ evidence.declarations.base,
+ evidence.declarations.head,
+ causes.map((cause) => cause.property),
+ ).map(({ key, ...block }) => ({ ...block, standIn: standIns(evidence, layout).get(key) }))
+ : [],
+ source,
+ usage: Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) => {
+ const chain = evidence?.elements?.[side];
+ return chain?.length ? [[side, chain.map(usageOf)]] : [];
+ }),
+ ),
+ };
+};
+
+type Extractions = Record<string, Partial<Record<'base' | 'head', { elements: StyleElement[] }>>>;
+
+export const standInsFor = (
+ key: string,
+ entry: Pick<CaseEntry, 'plan'> | undefined,
+ plans: Array<{ file: string; standIns?: Record<string, string[]> }>,
+): 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 elementFor = (stored: StoredRun, key: string, entry: CaseEntry | undefined) => {
+ const extractions = stored.extractions as Extractions;
+ const unpaired = /^(.*)\|unpaired:(base|head):(.+)$/.exec(key);
+ const [file, side, id] = unpaired
+ ? [unpaired[1], unpaired[2] as 'base' | 'head', unpaired[3]]
+ : [entry?.plan.file ?? '', 'head' as const, entry?.plan.elementIds?.head];
+ return extractions[file]?.[side]?.elements.find((element) => element.id === id);
+};
+
+const titleOf = (key: string, element: StyleElement | undefined) => {
+ const id = key.slice(key.indexOf('|') + 1).replace(/^unpaired:\w+:/, '');
+ const slot = element?.slots[0]?.split('.').pop();
+ return slot ? `${id.split('#')[0]} · ${slot}` : id;
+};
+
+const contextOf = (stored: StoredRun) => {
+ const cases = new Map(
+ (stored.results.cases as unknown as CaseEntry[]).map((entry) => [entry.key, entry]),
+ );
+ const elements = new Map(
+ stored.items.map((item) => [item.key, elementFor(stored, item.key, cases.get(item.key))]),
+ );
+ const signatures = new Map(
+ [...elements].flatMap(([key, element]) => (element ? [[key, elementSignature(element)]] : [])),
+ ) as Map<string, string>;
+ const combos = new Map([...cases].map(([key, entry]) => [key, entry.plan.combos?.length ?? 1]));
+ return { cases, combos, elements, signatures };
+};
+
+const describe = (
+ item: ReviewItem,
+ entry: CaseEntry | undefined,
+ element?: StyleElement,
+ evidence?: CaseEvidence,
+ layout: Set<string> = new Set(),
+ standIns: Sides<string[]> = {},
+) => {
+ const component = element && !isIntrinsicTag(element.tag) ? element.tag : undefined;
+ const binding = element?.bindings[0];
+ const variables = [
+ ...new Set(
+ (element?.variables ?? [])
+ .map((variable) => variable.name)
+ .filter((name) => !PASS_THROUGH_VARIABLES.has(name)),
+ ),
+ ];
+ return {
+ ...item,
+ ask: askSentence(item, {
+ component,
+ prop: binding && (binding.spread ? 'className' : binding.prop),
+ variables,
+ }),
+ comboDifferences: (entry?.result?.comboDifferences ?? []).map((difference) => ({
+ combo: difference.combo,
+ condition: difference.condition,
+ summary: differenceSummary(difference.rootCauses),
+ })),
+ combos: (entry?.plan.combos ?? [{}]).map((combo, index) => ({
+ index,
+ label: comboLabel(combo),
+ })),
+ component,
+ differingConditions: entry?.result?.differingConditions ?? [],
+ errors: entry?.result?.errors ?? [],
+ standIns,
+ styles: stylesOf(entry, evidence, layout),
+ summary: differenceSummary(entry?.result?.rootCauses ?? []),
+ title: titleOf(item.key, element),
+ };
+};
+
+export type ReviewView = ReturnType<typeof describe>;
+
+export const reviewState = async (stored: StoredRun) => {
+ const verdict = await currentVerdict(stored);
+ const reviews = await readRunReviews(stored);
+ const resolved = resolvedReworks(verdict.items, reviews, new Date().toISOString());
+ for (const rework of resolved) {
+ await writeReviews(stored.recordsDir, rework.file, { reworks: [rework] });
+ reviews.reworks.set(rework.key, rework);
+ }
+ const context = contextOf(stored);
+ const items = reviewItems(verdict.items, reviews, context);
+ return {
+ context,
+ items,
+ reviews,
+ verdict: resolved.length ? await currentVerdict(stored) : verdict,
+ };
+};
+
+export const reviewPayload = async (stored: StoredRun, layoutComponents: string[] = []) => {
+ const layout = new Set(layoutComponents);
+ const { context, items, reviews, verdict } = await reviewState(stored);
+ const views = items.map((item) =>
+ describe(
+ item,
+ context.cases.get(item.key),
+ context.elements.get(item.key),
+ stored.evidence[item.key] as CaseEvidence | undefined,
+ layout,
+ standInsFor(item.key, context.cases.get(item.key), stored.plans ?? []),
+ ),
+ );
+ const resolved = [...reviews.reworks.values()].filter((rework) => rework.resolvedAt);
+ return {
+ conditions: (stored.run.conditions as string[] | undefined) ?? [],
+ counts: {
+ proven: stored.items.length - items.length,
+ total: stored.items.length,
+ ...Object.fromEntries(
+ ['changed', 'passed', 'reworked', 'todo', 'waiting-agent'].map((state) => [
+ state,
+ items.filter((item) => item.state === state).length,
+ ]),
+ ),
+ },
+ items: views,
+ pr: stored.run.pr,
+ resolved: resolved.map(({ key, note, resolvedAt }) => ({ key, note, resolvedAt })),
+ run: { base: stored.run.base, head: stored.run.head, runId: stored.run.runId },
+ verdict: { mergeable: verdict.mergeable, reasons: verdict.reasons },
+ };
+};
+
+export const caseReview = async (
+ stored: StoredRun,
+ key: string,
+ layoutComponents: string[] = [],
+) => {
+ const { context, items, verdict } = await reviewState(stored);
+ const queued = items.find((item) => item.key === key);
+ const entry = verdict.items.find((item) => item.key === key);
+ if (!queued && !entry) throw new ApiError(404, `UNKNOWN_CASE:${key}`);
+ const item: ReviewItem = queued ?? {
+ ...entry!,
+ canPass: false,
+ needsAgent: false,
+ state: 'passed',
+ };
+ const caseEntry = context.cases.get(key);
+ return {
+ conditions: (stored.run.conditions as string[] | undefined) ?? [],
+ item: describe(
+ item,
+ caseEntry,
+ context.elements.get(key) ?? elementFor(stored, key, caseEntry),
+ stored.evidence[key] as CaseEvidence | undefined,
+ new Set(layoutComponents),
+ standInsFor(key, caseEntry, stored.plans ?? []),
+ ),
+ queued: Boolean(queued),
+ };
+};
+
+const failure = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ return new ApiError(message.startsWith('NOTE_REQUIRED') ? 400 : 409, message);
+};
+
+export const applyReview = async (
+ stored: StoredRun,
+ body: { action?: unknown; key?: unknown; note?: unknown; reviewer?: unknown },
+) => {
+ if (typeof body.key !== 'string' || (body.action !== 'pass' && body.action !== 'rework'))
+ throw new ApiError(400, 'EXPECTED_KEY_AND_ACTION');
+ const note = typeof body.note === 'string' ? body.note : '';
+ const { context, items } = await reviewState(stored);
+ const item = items.find((entry) => entry.key === body.key);
+ if (!item) throw new ApiError(404, `UNKNOWN_CASE:${body.key}`);
+ const reviewer =
+ typeof body.reviewer === 'string' && body.reviewer
+ ? body.reviewer
+ : await defaultSigner(stored.run.repo ?? '.');
+ const now = new Date().toISOString();
+ try {
+ if (body.action === 'pass') {
+ const reworks: ReworkRecord[] = item.rework ? [{ ...item.rework, resolvedAt: now }] : [];
+ await writeReviews(stored.recordsDir, item.file, {
+ passes: [passRecord(item, note, reviewer, now)],
+ reworks,
+ });
+ } else {
+ const pr = runPr(stored);
+ const view = describe(
+ item,
+ context.cases.get(item.key),
+ context.elements.get(item.key),
+ stored.evidence[item.key] as CaseEvidence | undefined,
+ );
+ const record = reworkRecord(
+ item,
+ {
+ base: String(stored.run.base ?? ''),
+ head: String(stored.run.head ?? ''),
+ note: note.trim() ? note : defaultReworkNote(view),
+ pr,
+ reviewer,
+ runId: String(stored.run.runId ?? ''),
+ signature: context.signatures.get(item.key) ?? '',
+ },
+ now,
+ );
+ await writeReviews(stored.recordsDir, item.file, { reworks: [record] });
+ }
+ } catch (error) {
+ throw failure(error);
+ }
+ return reviewPayload(stored);
+};
diff --git a/packages/style-equivalence/src/server/server.test.ts b/packages/style-equivalence/src/server/server.test.ts
new file mode 100644
index 00000000000..5cf3aff69fd
--- /dev/null
+++ b/packages/style-equivalence/src/server/server.test.ts
@@ -0,0 +1,215 @@
+import { mkdir, 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 { startServer } from './index';
+
+let root: string;
+let runDir: string;
+let repo: string;
+let server: Awaited<ReturnType<typeof startServer>>;
+
+const item = (key: string, category: string, flags: string[] = []) => ({
+ category,
+ file: 'src/A.tsx',
+ flags,
+ hash: `hash-${key}`,
+ key,
+ signoff: 'missing',
+});
+
+const write = (name: string, value: unknown) =>
+ writeFile(path.join(runDir, name), JSON.stringify(value));
+
+beforeAll(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-server-'));
+ runDir = path.join(root, 'run');
+ repo = path.join(root, 'repo');
+ await mkdir(path.join(runDir, 'dist-base'), { recursive: true });
+ await mkdir(path.join(runDir, 'dist-head'), { recursive: true });
+ await mkdir(repo);
+ const page = (color: string) =>
+ `<!doctype html><html><head><style>body{margin:0;font:14px Arial}.t{color:${color}}</style></head><body><div id="app" data-synthetic-ready="true"><main data-synthetic-cases=""><section data-case="src/A.tsx|A#1|0" style="width:360px;padding:8px"><span data-synthetic-element="A#1" class="t">Text</span></section></main></div></body></html>`;
+ await writeFile(path.join(runDir, 'dist-base/index.html'), page('black'));
+ await writeFile(path.join(runDir, 'dist-head/index.html'), page('red'));
+ await writeFile(path.join(root, 'secret.txt'), 'secret');
+ await symlink(path.join(root, 'secret.txt'), path.join(runDir, 'dist-base/leak.txt'));
+ await write('run.json', {
+ base: 'a'.repeat(40),
+ conditionConfig: {
+ themeAttribute: 'data-theme',
+ themes: ['light'],
+ variants: [],
+ widths: [1280],
+ },
+ head: 'b'.repeat(40),
+ repo,
+ runId: 'run-1',
+ states: ['default'],
+ });
+ await write('results.json', {
+ cases: [
+ {
+ category: 'difference',
+ key: 'src/A.tsx|A#0',
+ plan: { file: 'src/A.tsx', flags: [] },
+ result: {},
+ },
+ {
+ category: 'needs-signoff',
+ key: 'src/A.tsx|A#1',
+ plan: { file: 'src/A.tsx', flags: ['PLACEMENT_SUBSTITUTED'] },
+ result: {},
+ },
+ ],
+ });
+ await write('verdict.json', {
+ items: [
+ item('src/A.tsx|A#0', 'difference'),
+ item('src/A.tsx|A#1', 'needs-signoff', ['PLACEMENT_SUBSTITUTED']),
+ ],
+ mergeable: false,
+ reasons: [],
+ });
+ await write('mutation.json', { passed: true });
+ await write('calibration.json', []);
+ await write('evidence.json', {
+ 'src/A.tsx|A#1': { declarations: { head: { 'styles.a': 'a: {}' } } },
+ });
+ server = await startServer({ runDir });
+});
+
+afterAll(async () => {
+ await server?.stop();
+ await rm(root, { force: true, recursive: true });
+});
+
+const post = (url: string, body: unknown) =>
+ fetch(`${server.url}${url}`, {
+ body: JSON.stringify(body),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+describe('report server', () => {
+ it('returns the stored run with its verdict', async () => {
+ const response = await fetch(`${server.url}/api/run`);
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.run.runId).toBe('run-1');
+ expect(body.verdict).toMatchObject({
+ mergeable: false,
+ reasons: ['difference 1', 'needs sign-off 1'],
+ });
+ });
+
+ it('returns one case with its evidence', async () => {
+ const response = await fetch(`${server.url}/api/case/${encodeURIComponent('src/A.tsx|A#1')}`);
+ const body = await response.json();
+ expect(body.case.category).toBe('needs-signoff');
+ expect(body.evidence.declarations.head['styles.a']).toBe('a: {}');
+ expect(body.item.signoff).toBe('missing');
+ });
+
+ it('refuses to sign an unflagged difference', async () => {
+ const response = await post('/api/signoff', {
+ keys: ['src/A.tsx|A#0'],
+ note: 'looks fine',
+ reason: 'TOOL_FALSE_POSITIVE',
+ signer: 'innei',
+ });
+ expect(response.status).toBe(409);
+ expect((await response.json()).error).toMatch(/^UNFLAGGED_DIFFERENCE/);
+ });
+
+ it('writes a valid sign-off into the records reviews and recomputes the verdict', async () => {
+ const response = await post('/api/signoff', {
+ keys: ['src/A.tsx|A#1'],
+ note: 'div stands in for the antd Image',
+ reason: 'PLACEMENT_SUBSTITUTED',
+ signer: 'innei',
+ });
+ expect(response.status).toBe(200);
+ expect((await response.json()).verdict.reasons).toEqual(['difference 1']);
+ const stored = JSON.parse(
+ await readFile(path.join(path.dirname(runDir), 'reviews/src/A.tsx.json'), 'utf8'),
+ );
+ expect(stored.passes).toMatchObject([
+ { hash: 'hash-src/A.tsx|A#1', reason: 'PLACEMENT_SUBSTITUTED' },
+ ]);
+ });
+
+ it('captures one case again from the stored builds', async () => {
+ const response = await post(`/api/case/${encodeURIComponent('src/A.tsx|A#1')}/rerun`, {});
+ expect(response.status).toBe(200);
+ const { result } = await response.json();
+ expect(result).toMatchObject({
+ differingConditions: ['light/1280/default'],
+ status: 'difference',
+ });
+ }, 60_000);
+
+ it('captures one case under one condition with the target values and differences', async () => {
+ const key = encodeURIComponent('src/A.tsx|A#1');
+ const response = await fetch(
+ `${server.url}/api/case/${key}/snapshot?condition=light/1280/hover-target&combo=0`,
+ );
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.base.target.values.color).toBe('rgb(0, 0, 0)');
+ expect(body.head.target.values.color).toBe('rgb(255, 0, 0)');
+ expect(body.differences.map((item: { property: string }) => item.property)).toContain('color');
+ }, 60_000);
+
+ it('renders a screenshot of one side under a forced state', async () => {
+ const key = encodeURIComponent('src/A.tsx|A#1');
+ const response = await fetch(
+ `${server.url}/api/case/${key}/shot?side=head&condition=light/1280/hover-target&combo=0`,
+ );
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type')).toBe('image/png');
+ expect((await response.arrayBuffer()).byteLength).toBeGreaterThan(100);
+ }, 60_000);
+
+ it('crops a screenshot to the target element with padding', async () => {
+ const key = encodeURIComponent('src/A.tsx|A#1');
+ const shot = async (crop: string) =>
+ Buffer.from(
+ await (
+ await fetch(
+ `${server.url}/api/case/${key}/shot?side=head&condition=light/1280/default&combo=0${crop}`,
+ )
+ ).arrayBuffer(),
+ );
+ const width = (png: Buffer) => png.readUInt32BE(16);
+ const full = await shot('');
+ const cropped = await shot('&crop=1');
+ expect(width(full)).toBeGreaterThanOrEqual(376);
+ expect(width(cropped)).toBeLessThan(width(full));
+ expect(width(cropped)).toBeGreaterThan(32);
+ const revealed = await shot('&crop=1&reveal=1');
+ expect(width(revealed)).toBe(width(cropped));
+ expect(revealed.equals(cropped)).toBe(false);
+ }, 60_000);
+
+ it('returns the stored self-test report beside the run', async () => {
+ await writeFile(
+ path.join(root, 'self-test.json'),
+ JSON.stringify({ css: [], passed: true, ranAt: 'now', source: [], verifierVersion: '1.0.0' }),
+ );
+ expect(await (await fetch(`${server.url}/api/method`)).json()).toEqual({
+ selfTest: { css: [], passed: true, ranAt: 'now', source: [], verifierVersion: '1.0.0' },
+ });
+ });
+
+ it('serves the builds and nothing outside them', async () => {
+ expect(await (await fetch(`${server.url}/base/`)).text()).toContain(
+ 'data-case="src/A.tsx|A#1|0"',
+ );
+ expect((await fetch(`${server.url}/base/leak.txt`)).status).toBe(404);
+ expect((await fetch(`${server.url}/base/..%2F..%2Fsecret.txt`)).status).toBe(404);
+ expect((await fetch(`${server.url}/api/case/missing`)).status).toBe(404);
+ });
+});
diff --git a/packages/style-equivalence/src/server/standIns.test.ts b/packages/style-equivalence/src/server/standIns.test.ts
new file mode 100644
index 00000000000..ff458c7c062
--- /dev/null
+++ b/packages/style-equivalence/src/server/standIns.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { standInsFor } from './review';
+
+describe('stand-ins shown on a review screenshot', () => {
+ it('reads the stand-ins of a compared case from its plan', () => {
+ expect(
+ standInsFor('a.tsx|A#0', { plan: { file: 'a.tsx', standIns: { base: ['Tabs'] } } }, []),
+ ).toEqual({
+ base: ['Tabs'],
+ });
+ });
+
+ it('reads the stand-ins of a one-sided element from the file plan', () => {
+ const plans = [{ file: 'a.tsx', standIns: { 'head:A#1': ['Select'] } }];
+ expect(standInsFor('a.tsx|unpaired:head:A#1', undefined, plans)).toEqual({ head: ['Select'] });
+ expect(standInsFor('a.tsx|unpaired:base:A#1', undefined, plans)).toEqual({});
+ });
+});
diff --git a/packages/style-equivalence/src/signoff/hash.ts b/packages/style-equivalence/src/signoff/hash.ts
new file mode 100644
index 00000000000..c55e906dd28
--- /dev/null
+++ b/packages/style-equivalence/src/signoff/hash.ts
@@ -0,0 +1,113 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import type { FileExtraction, LiteralValue, StyleBinding } from '../extract';
+import { elementsOf } from '../plan/descendants';
+import { chainOf, type PlanCase, type Side } from '../plan/planFile';
+import { declarationText, resolveSlot } from '../source/declarations';
+
+export interface HashedElement {
+ attributes?: Record<string, string>;
+ bindings: StyleBinding[];
+ literalProps: Record<string, LiteralValue>;
+ slots: string[];
+ tag: string;
+}
+
+export interface CaseHashInput {
+ declarations: Partial<Record<Side, Record<string, string>>>;
+ elements: Partial<Record<Side, HashedElement[]>>;
+ outcome?: string[];
+ plan?: Pick<PlanCase, 'combos' | 'flags' | 'forward' | 'inner' | 'variables'>;
+ verifierMajor: string;
+}
+
+export interface OutcomeCause {
+ after?: string;
+ before?: string;
+ key: string;
+ property: string;
+}
+
+const sortKeys = (_key: string, value: unknown) =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)),
+ )
+ : value;
+
+export const contentHash = (input: CaseHashInput) =>
+ createHash('sha256').update(JSON.stringify(input, sortKeys)).digest('hex');
+
+export interface CollectHashInput {
+ aliases: Record<string, string>;
+ elementIds?: Partial<Record<Side, string>>;
+ extractions: Partial<Record<Side, FileExtraction>>;
+ outcome?: OutcomeCause[];
+ plan?: PlanCase;
+ roots: Record<Side, string>;
+ sources: Partial<Record<Side, string>>;
+ verifierVersion: string;
+}
+
+export const collectCaseHashInput = (input: CollectHashInput): CaseHashInput => {
+ const result: CaseHashInput = {
+ declarations: {},
+ elements: {},
+ outcome: input.outcome
+ ?.map((cause) =>
+ [cause.key, cause.property, cause.before ?? '', cause.after ?? ''].join('\u0000'),
+ )
+ .sort(),
+ plan: input.plan && {
+ combos: input.plan.combos,
+ flags: input.plan.flags,
+ forward: input.plan.forward,
+ inner: input.plan.inner,
+ variables: input.plan.variables,
+ },
+ verifierMajor: input.verifierVersion.split('.')[0],
+ };
+ for (const side of ['base', 'head'] as const) {
+ const extraction = input.extractions[side];
+ const source = input.sources[side];
+ const id = input.elementIds?.[side] ?? input.plan?.elementIds[side];
+ if (!extraction || !source || !id) continue;
+ const byId = new Map(elementsOf(extraction).map((element) => [element.id, element]));
+ const element = byId.get(id);
+ if (!element) continue;
+ const chain = chainOf(element, byId, input.plan?.chainOmit?.[side]);
+ result.elements[side] = chain.map(({ attributes, bindings, literalProps, slots, tag }) => ({
+ ...(attributes ? { attributes } : {}),
+ bindings,
+ literalProps,
+ slots,
+ tag,
+ }));
+ const code = readFileSync(path.join(input.roots[side], source), 'utf8');
+ const slots = [...new Set(chain.flatMap((item) => item.slots))].sort();
+ result.declarations[side] = Object.fromEntries(
+ slots.map((slot) => {
+ const sites = resolveSlot(input.roots[side], source, code, slot, input.aliases);
+ return [slot, sites.length ? sites.map(declarationText).join('\n') : `UNRESOLVED:${slot}`];
+ }),
+ );
+ }
+ return result;
+};
+
+export const collectFileHashInput = (
+ input: Pick<CollectHashInput, 'roots' | 'sources' | 'verifierVersion'>,
+): CaseHashInput => ({
+ declarations: Object.fromEntries(
+ (['base', 'head'] as const).flatMap((side) => {
+ const source = input.sources[side];
+ return source
+ ? [[side, { [source]: readFileSync(path.join(input.roots[side], source), 'utf8') }]]
+ : [];
+ }),
+ ),
+ elements: {},
+ verifierMajor: input.verifierVersion.split('.')[0],
+});
diff --git a/packages/style-equivalence/src/signoff/signoff.test.ts b/packages/style-equivalence/src/signoff/signoff.test.ts
new file mode 100644
index 00000000000..6272fbb3299
--- /dev/null
+++ b/packages/style-equivalence/src/signoff/signoff.test.ts
@@ -0,0 +1,104 @@
+import { mkdir, mkdtemp, readFile, 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 { extractFile } from '../extract';
+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';
+import { stylexAdapter } from '../extract/adapters/stylex';
+import { moduleReader } from '../pipeline/synthesize';
+import { planFile } from '../plan/planFile';
+import { collectCaseHashInput, contentHash } from './hash';
+import { readSignoffs, signoffPath, writeSignoffs } from './store';
+
+let root: string;
+const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: [] };
+
+const source = `import * as stylex from '@stylexjs/stylex';
+import { styles } from './A.styles';
+export const A = () => <div {...stylex.props(styles.box)} />;
+`;
+const stylesFile = (padding: number) => `import * as stylex from '@stylexjs/stylex';
+export const styles = stylex.create({ box: { padding: ${padding} }, other: { margin: 1 } });
+`;
+
+const hashOf = async (
+ outcome?: Array<{ after?: string; before?: string; key: string; property: string }>,
+) => {
+ const code = await readFile(path.join(root, 'src/A.tsx'), 'utf8');
+ const extraction = extractFile(code, 'src/A.tsx', {
+ ...options,
+ readModule: moduleReader(root, {}),
+ });
+ const plan = planFile('src/A.tsx', extraction, extraction, { layoutComponents: [] });
+ return contentHash(
+ collectCaseHashInput({
+ aliases: {},
+ extractions: { base: extraction, head: extraction },
+ plan: plan.cases[0],
+ roots: { base: root, head: root },
+ sources: { base: 'src/A.tsx', head: 'src/A.tsx' },
+ outcome,
+ verifierVersion: '1.2.3',
+ }),
+ );
+};
+
+beforeAll(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-signoff-'));
+ await mkdir(path.join(root, 'src'));
+ await writeFile(path.join(root, 'src/A.tsx'), source);
+ await writeFile(path.join(root, 'src/A.styles.ts'), stylesFile(4));
+});
+
+afterAll(() => rm(root, { force: true, recursive: true }));
+
+describe('contentHash', () => {
+ it('changes when the declaration a case uses changes, even in an imported module', async () => {
+ const before = await hashOf();
+ expect(await hashOf()).toBe(before);
+ await writeFile(
+ path.join(root, 'src/A.styles.ts'),
+ stylesFile(4).replace('margin: 1', 'margin: 2'),
+ );
+ expect(await hashOf()).toBe(before);
+ await writeFile(path.join(root, 'src/A.styles.ts'), stylesFile(6));
+ expect(await hashOf()).not.toBe(before);
+ });
+});
+
+describe('contentHash outcome', () => {
+ it('changes when what differs changes, so a false-positive sign-off does not carry over', async () => {
+ const cause = {
+ after: 'normal',
+ before: '"tnum"',
+ key: 'root.0',
+ property: 'font-feature-settings',
+ };
+ const signed = await hashOf([cause]);
+ expect(await hashOf([cause])).toBe(signed);
+ expect(await hashOf([{ ...cause, property: 'color' }])).not.toBe(signed);
+ });
+});
+
+describe('signoff store', () => {
+ it('keeps one file per source and merges records by key', async () => {
+ const record = {
+ hash: 'h1',
+ key: 'src/A.tsx|A#0',
+ note: 'div stands in for Image',
+ reason: 'PLACEMENT_SUBSTITUTED',
+ signedAt: '2026-11-04T00:00:00.000Z',
+ signer: 'innei',
+ };
+ await writeSignoffs(root, 'src/A.tsx', [record]);
+ await writeSignoffs(root, 'src/A.tsx', [{ ...record, hash: 'h2' }]);
+ expect(signoffPath(root, 'src/A.tsx')).toBe(
+ path.join(root, '.style-equivalence/signoffs/src/A.tsx.json'),
+ );
+ expect([...(await readSignoffs(root, ['src/A.tsx', 'src/Missing.tsx'])).values()]).toEqual([
+ { ...record, hash: 'h2' },
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/signoff/store.ts b/packages/style-equivalence/src/signoff/store.ts
new file mode 100644
index 00000000000..26da6b7988d
--- /dev/null
+++ b/packages/style-equivalence/src/signoff/store.ts
@@ -0,0 +1,48 @@
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+export const SIGNOFF_DIR = '.style-equivalence/signoffs';
+
+export interface SignoffRecord {
+ hash: string;
+ key: string;
+ note: string;
+ reason: string;
+ reasons?: string[];
+ signedAt: string;
+ signer: string;
+}
+
+export const signoffPath = (root: string, file: string) =>
+ path.join(root, SIGNOFF_DIR, `${file}.json`);
+
+const readFileRecords = async (root: string, file: string): Promise<SignoffRecord[]> => {
+ try {
+ return JSON.parse(await readFile(signoffPath(root, file), 'utf8')) as SignoffRecord[];
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+};
+
+export const readSignoffs = async (root: string, files: string[]) => {
+ const records = new Map<string, SignoffRecord>();
+ for (const file of new Set(files))
+ for (const record of await readFileRecords(root, file)) records.set(record.key, record);
+ return records;
+};
+
+export const writeSignoffs = async (root: string, file: string, records: SignoffRecord[]) => {
+ const merged = new Map((await readFileRecords(root, file)).map((record) => [record.key, record]));
+ for (const record of records) merged.set(record.key, record);
+ const target = signoffPath(root, file);
+ await mkdir(path.dirname(target), { recursive: true });
+ await writeFile(
+ target,
+ `${JSON.stringify(
+ [...merged.values()].sort((a, b) => a.key.localeCompare(b.key)),
+ null,
+ 2,
+ )}\n`,
+ );
+};
diff --git a/packages/style-equivalence/src/source/aliases.test.ts b/packages/style-equivalence/src/source/aliases.test.ts
new file mode 100644
index 00000000000..5ef9730e028
--- /dev/null
+++ b/packages/style-equivalence/src/source/aliases.test.ts
@@ -0,0 +1,117 @@
+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 { globalCssAdapter } from '../extract/adapters/globalCss';
+import { extractFile } from '../extract/index';
+import { stylesheetReader } from '../pipeline/synthesize';
+import { aliasCandidates } from './aliases';
+import { resolveSpecifier } from './declarations';
+
+let root: string;
+
+const put = async (file: string, text: string) => {
+ await mkdir(path.dirname(path.join(root, file)), { recursive: true });
+ await writeFile(path.join(root, file), text);
+};
+
+beforeAll(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'style-eq-aliases-'));
+ await put(
+ 'tsconfig.json',
+ `{
+ // comments are allowed here, as in the app's own tsconfig
+ "compilerOptions": {
+ "paths": {
+ "@/utils/*": ["./packages/utils/src/*", "./src/utils/*"],
+ "@/*": ["./src/*"],
+ "~fixture": ["./tests/fixture.ts"]
+ }
+ }
+ }`,
+ );
+ await put('src/features/shared/breadcrumb.css', '.crumb ol { flex-wrap: nowrap; }\n');
+ await put('src/utils/format.ts', 'export const format = 1;\n');
+ await put('tests/fixture.ts', 'export const fixture = 1;\n');
+ await put(
+ 'node_modules/@flow/react/package.json',
+ JSON.stringify({ exports: { '.': './dist/index.js' }, name: '@flow/react' }),
+ );
+ await put('node_modules/@flow/react/dist/index.js', 'export {};\n');
+ await put('node_modules/@flow/react/dist/style.css', '.flow__node { color: red; }\n');
+});
+
+afterAll(async () => {
+ await rm(root, { force: true, recursive: true });
+});
+
+describe('specifiers resolved the way the app resolves them', () => {
+ it('prefers the longest tsconfig path and keeps its targets in order', () => {
+ expect(aliasCandidates(root, '@/utils/format', {})).toEqual([
+ 'packages/utils/src/format',
+ 'src/utils/format',
+ ]);
+ expect(aliasCandidates(root, '~fixture', {})).toEqual(['tests/fixture.ts']);
+ expect(aliasCandidates(root, 'react', {})).toEqual([]);
+ });
+
+ it('falls through to the next target when the first does not exist', () => {
+ expect(resolveSpecifier(root, 'src/a.tsx', '@/utils/format', {})).toBe('src/utils/format.ts');
+ });
+
+ it('reads a plain stylesheet imported through an alias', () => {
+ const read = stylesheetReader(root, { '@/': 'src/' });
+ expect(read('src/features/a/A.tsx', '@/features/shared/breadcrumb.css')).toContain('.crumb ol');
+ expect(stylesheetReader(root)('src/a.tsx', '@/features/shared/breadcrumb.css')).toContain(
+ 'nowrap',
+ );
+ });
+
+ it('reads a package stylesheet from node_modules even when its exports map hides it', () => {
+ expect(stylesheetReader(root)('src/a.tsx', '@flow/react/dist/style.css')).toContain(
+ '.flow__node',
+ );
+ expect(stylesheetReader(root)('src/a.tsx', '@flow/react/dist/missing.css')).toBeUndefined();
+ });
+
+ it('extracts rules from an aliased stylesheet with no unreadable gap', () => {
+ const code = `import '@/features/shared/breadcrumb.css';
+
+export const A = () => <nav className="crumb" />;
+`;
+ const extraction = extractFile(code, 'src/features/a/A.tsx', {
+ adapters: [globalCssAdapter],
+ layoutComponents: [],
+ readStylesheet: stylesheetReader(root),
+ });
+ expect(extraction.gaps).toEqual([]);
+ expect(extraction.rules.map((rule) => rule.selector)).toEqual(['.crumb ol']);
+ expect(extraction.elements[0].slots).toEqual(['global.crumb']);
+ });
+});
+
+describe('a package stylesheet nobody can read', () => {
+ it('needs no sign-off when both sides import it the same way, and does when one side adds it', async () => {
+ const { planFile } = await import('../plan/planFile');
+ const code = (css: string) => `${css}\nexport const A = () => <div className={styles.a} />;\n`;
+ const extract = (text: string) =>
+ extractFile(text, 'src/a.tsx', {
+ adapters: [globalCssAdapter],
+ layoutComponents: [],
+ readStylesheet: () => undefined,
+ });
+ const both = extract(code("import '@gone/pkg/dist/style.css';"));
+ expect(both.gaps).toEqual(['STYLESHEET_UNREADABLE:@gone/pkg/dist/style.css']);
+ expect(planFile('src/a.tsx', both, both, { layoutComponents: [] }).gaps).toEqual([]);
+ const none = extract(code(''));
+ expect(planFile('src/a.tsx', none, both, { layoutComponents: [] }).gaps).toEqual([
+ 'STYLESHEET_UNREADABLE:@gone/pkg/dist/style.css',
+ ]);
+ const local = extract(code("import './gone.css';"));
+ expect(planFile('src/a.tsx', local, local, { layoutComponents: [] }).gaps).toEqual([
+ 'STYLESHEET_UNREADABLE:./gone.css',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/source/aliases.ts b/packages/style-equivalence/src/source/aliases.ts
new file mode 100644
index 00000000000..9031373b685
--- /dev/null
+++ b/packages/style-equivalence/src/source/aliases.ts
@@ -0,0 +1,90 @@
+import { existsSync, statSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+
+import ts from 'typescript';
+
+interface AliasEntry {
+ exact: boolean;
+ prefix: string;
+ targets: string[];
+}
+
+const tsconfigCache = new Map<string, AliasEntry[]>();
+
+const tsconfigAliases = (root: string): AliasEntry[] => {
+ const cached = tsconfigCache.get(root);
+ if (cached) return cached;
+ const entries: AliasEntry[] = [];
+ const file = path.join(root, 'tsconfig.json');
+ const { config } = existsSync(file) ? ts.readConfigFile(file, ts.sys.readFile) : { config: {} };
+ const options = (config?.compilerOptions ?? {}) as {
+ baseUrl?: string;
+ paths?: Record<string, string[]>;
+ };
+ const base = options.baseUrl ?? '.';
+ for (const [pattern, targets] of Object.entries(options.paths ?? {})) {
+ const wildcard = pattern.endsWith('*');
+ if (pattern.indexOf('*') !== pattern.length - 1 && pattern.includes('*')) continue;
+ entries.push({
+ exact: !wildcard,
+ prefix: wildcard ? pattern.slice(0, -1) : pattern,
+ targets: targets
+ .filter((target) => !wildcard || target.endsWith('*'))
+ .map((target) => path.normalize(path.join(base, wildcard ? target.slice(0, -1) : target))),
+ });
+ }
+ tsconfigCache.set(root, entries);
+ return entries;
+};
+
+const withTrailingSlash = (prefix: string, target: string) =>
+ prefix.endsWith('/') && !target.endsWith('/') ? `${target}/` : target;
+
+export const aliasCandidates = (
+ root: string,
+ specifier: string,
+ aliases: Record<string, string>,
+) => {
+ const entries: AliasEntry[] = [
+ ...Object.entries(aliases).map(([prefix, target]) => ({
+ exact: false,
+ prefix,
+ targets: [target],
+ })),
+ ...tsconfigAliases(root),
+ ];
+ const matches = entries
+ .filter((entry) =>
+ entry.exact ? specifier === entry.prefix : specifier.startsWith(entry.prefix),
+ )
+ .sort((left, right) => right.prefix.length - left.prefix.length);
+ const [best] = matches;
+ if (!best) return [];
+ return matches
+ .filter((entry) => entry.prefix.length === best.prefix.length)
+ .flatMap((entry) =>
+ entry.targets.map((target) =>
+ entry.exact
+ ? target
+ : withTrailingSlash(entry.prefix, target) + specifier.slice(entry.prefix.length),
+ ),
+ );
+};
+
+const isFile = (file: string) => existsSync(file) && statSync(file).isFile();
+
+export const packageFile = (root: string, from: string, specifier: string) => {
+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) return undefined;
+ try {
+ const resolved = createRequire(path.join(root, from)).resolve(specifier);
+ if (isFile(resolved)) return resolved;
+ } catch {
+ /* falls through to the node_modules walk: exports maps can hide plain assets */
+ }
+ for (let dir = path.dirname(path.join(root, from)); ; dir = path.dirname(dir)) {
+ const candidate = path.join(dir, 'node_modules', specifier);
+ if (isFile(candidate)) return candidate;
+ if (dir === path.dirname(dir)) return undefined;
+ }
+};
diff --git a/packages/style-equivalence/src/source/declarations.ts b/packages/style-equivalence/src/source/declarations.ts
new file mode 100644
index 00000000000..287b4d410f4
--- /dev/null
+++ b/packages/style-equivalence/src/source/declarations.ts
@@ -0,0 +1,189 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import postcss from 'postcss';
+import ts from 'typescript';
+
+import { NAMESPACE } from '../extract/importedClasses';
+import { classNamesIn } from '../extract/selectors';
+import { aliasCandidates } from './aliases';
+
+const EXTENSIONS = ['', '.ts', '.tsx', '/index.ts', '/index.tsx'];
+
+export const propertyNameOf = (name: ts.PropertyName) =>
+ ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)
+ ? name.text
+ : ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)
+ ? name.expression.text
+ : undefined;
+
+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;
+ const visit = (node: ts.Node) => {
+ if (
+ !call &&
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.name.text === symbol &&
+ node.initializer &&
+ ts.isCallExpression(node.initializer)
+ )
+ call = node.initializer;
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ if (!call) return undefined;
+ let queue: ts.Node[] = [...call.arguments];
+ while (queue.length) {
+ const next: ts.Node[] = [];
+ for (const node of queue) {
+ if (ts.isPropertyAssignment(node) && propertyNameOf(node.name) === member) return node;
+ ts.forEachChild(node, (child) => {
+ next.push(child);
+ });
+ }
+ queue = next;
+ }
+ return undefined;
+};
+
+export const resolveSpecifier = (
+ root: string,
+ from: string,
+ specifier: string,
+ aliases: Record<string, string>,
+) => {
+ const bases = specifier.startsWith('.')
+ ? [path.join(path.dirname(from), specifier)]
+ : aliasCandidates(root, specifier, aliases);
+ return bases
+ .flatMap((base) => EXTENSIONS.map((extension) => path.normalize(base + extension)))
+ .find((candidate) => {
+ const absolute = path.join(root, candidate);
+ return existsSync(absolute) && path.extname(candidate) !== '';
+ });
+};
+
+export const importsOf = (code: string) => {
+ const sf = parseSource(code);
+ const named = new Map<string, { imported: string; specifier: string }>();
+ const sideEffects: string[] = [];
+ const locals = new Set<string>();
+ for (const statement of sf.statements) {
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
+ const specifier = statement.moduleSpecifier.text;
+ const clause = statement.importClause;
+ if (!clause) {
+ sideEffects.push(specifier);
+ continue;
+ }
+ if (clause.name) named.set(clause.name.text, { imported: 'default', specifier });
+ const bindings = clause.namedBindings;
+ if (bindings && ts.isNamedImports(bindings))
+ for (const element of bindings.elements)
+ named.set(element.name.text, {
+ imported: (element.propertyName ?? element.name).text,
+ specifier,
+ });
+ continue;
+ }
+ if (ts.isVariableStatement(statement))
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name)) locals.add(declaration.name.text);
+ }
+ return { locals, named, sideEffects };
+};
+
+export interface SlotSite {
+ code: string;
+ css: boolean;
+ kind: 'import' | 'source';
+ member: string;
+ path: string;
+ specifier?: string;
+ symbol: string;
+}
+
+export const resolveSlot = (
+ root: string,
+ source: string,
+ code: string,
+ slot: string,
+ aliases: Record<string, string>,
+): SlotSite[] => {
+ const dot = slot.indexOf('.');
+ const [symbol, member] = [slot.slice(0, dot), slot.slice(dot + 1)];
+ const { locals, named, sideEffects } = importsOf(code);
+ const read = (file: string) => readFileSync(path.join(root, file), 'utf8');
+ if (symbol === 'global')
+ return sideEffects.flatMap((specifier) => {
+ const file = resolveSpecifier(root, source, specifier, aliases);
+ if (!file?.endsWith('.css')) return [];
+ return [
+ {
+ code: read(file),
+ css: true,
+ kind: 'import' as const,
+ member,
+ path: file,
+ specifier,
+ symbol,
+ },
+ ];
+ });
+ if (locals.has(symbol))
+ return [{ code, css: false, kind: 'source', member, path: source, symbol }];
+ const [via, inner] = symbol.split(NAMESPACE);
+ if (inner) {
+ const owner = named.get(via);
+ const file = owner && resolveSpecifier(root, source, owner.specifier, aliases);
+ return owner && file
+ ? [
+ {
+ code: read(file),
+ css: false,
+ kind: 'import',
+ member,
+ path: file,
+ specifier: owner.specifier,
+ symbol: inner,
+ },
+ ]
+ : [];
+ }
+ const imported = named.get(symbol);
+ const file = imported && resolveSpecifier(root, source, imported.specifier, aliases);
+ if (!imported || !file) return [];
+ return [
+ {
+ code: read(file),
+ css: file.endsWith('.css'),
+ kind: 'import',
+ member,
+ path: file,
+ specifier: imported.specifier,
+ symbol: imported.imported,
+ },
+ ];
+};
+
+export const classRulesText = (css: string, className: string) => {
+ const texts: string[] = [];
+ postcss.parse(css).walkRules((rule) => {
+ if (!classNamesIn(rule.selector).includes(className)) return;
+ const parents: string[] = [];
+ for (let parent = rule.parent; parent && parent.type === 'atrule'; parent = parent.parent)
+ parents.unshift(`@${parent.name} ${parent.params}`);
+ texts.push([...parents, rule.toString()].join(' '));
+ });
+ return texts.join('\n');
+};
+
+export const declarationText = (site: SlotSite) => {
+ if (site.css) return classRulesText(site.code, site.member);
+ const property = findStyleMember(parseSource(site.code), site.symbol, site.member);
+ return property ? property.getText() : `UNRESOLVED:${site.symbol}.${site.member}`;
+};
diff --git a/packages/style-equivalence/src/source/scope.test.ts b/packages/style-equivalence/src/source/scope.test.ts
new file mode 100644
index 00000000000..f862ab03d33
--- /dev/null
+++ b/packages/style-equivalence/src/source/scope.test.ts
@@ -0,0 +1,129 @@
+import { execFileSync } from 'node:child_process';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { resolveScope } from './scope';
+
+let repo: string;
+const git = (...args: string[]) =>
+ execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim();
+const write = async (file: string, content: string) => {
+ await mkdir(path.dirname(path.join(repo, file)), { recursive: true });
+ await writeFile(path.join(repo, file), content);
+};
+
+beforeEach(async () => {
+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-scope-'));
+ git('init', '-q');
+ git('config', 'user.email', 't@t');
+ git('config', 'user.name', 't');
+ await write(
+ 'src/features/List/style.ts',
+ 'export const styles = createStaticStyles(() => ({ a: css`color: red;` }));\n',
+ );
+ await write(
+ 'src/features/List/Item.tsx',
+ "import { styles } from './style';\nexport const Item = () => <div className={styles.a} />;\n",
+ );
+ await write(
+ 'src/features/Other/Uses.tsx',
+ "import { styles } from '@/features/List/style';\nexport const Uses = () => <i className={styles.a} />;\n",
+ );
+ await write('src/features/Other/Unrelated.tsx', 'export const Unrelated = () => <b />;\n');
+ await write(
+ 'src/features/Card/Card.tsx',
+ 'export const Card = () => <section className="card">a long enough body to keep rename detection stable</section>;\n',
+ );
+ await write('src/features/Card/card.css', '.card { padding: 4px; }\n');
+ await write(
+ 'src/features/Card/Uses.tsx',
+ 'import \'./card.css\';\nexport const C = () => <div className="card" />;\n',
+ );
+ git('add', '.');
+ git('commit', '-qm', 'base');
+});
+
+afterEach(async () => {
+ await rm(repo, { force: true, recursive: true });
+});
+
+describe('resolveScope', () => {
+ it('pulls in unchanged components that import a changed style module', async () => {
+ await write(
+ 'src/features/List/style.ts',
+ "export const styles = stylex.create({ a: { color: 'red' } });\n",
+ );
+ await write('src/features/Card/card.css', '.card { padding: 6px; }\n');
+ git('commit', '-qam', 'head');
+ const scope = await resolveScope({ base: 'HEAD~1', head: 'HEAD', repo });
+ expect(scope.files).toEqual([
+ {
+ base: 'src/features/Card/Uses.tsx',
+ head: 'src/features/Card/Uses.tsx',
+ reason: 'imports-changed-style',
+ },
+ {
+ base: 'src/features/List/Item.tsx',
+ head: 'src/features/List/Item.tsx',
+ reason: 'imports-changed-style',
+ },
+ {
+ base: 'src/features/Other/Uses.tsx',
+ head: 'src/features/Other/Uses.tsx',
+ reason: 'imports-changed-style',
+ },
+ ]);
+ });
+
+ it('pulls in components that import a changed index module through its directory', async () => {
+ const factory = (color: string) =>
+ `export const styles = createStaticStyles(() => ({ a: css\`color: ${color};\` }));\n`;
+ await write('src/features/Panel/styles/index.ts', factory('red'));
+ await write(
+ 'src/features/Panel/Panel.tsx',
+ "import { styles } from './styles';\nexport const Panel = () => <div className={styles.a} />;\n",
+ );
+ await write(
+ 'src/features/Panel/styles/Inner.tsx',
+ "import { styles } from '.';\nexport const Inner = () => <div className={styles.a} />;\n",
+ );
+ git('add', '.');
+ git('commit', '-qm', 'panel');
+ await write('src/features/Panel/styles/index.ts', factory('blue'));
+ git('commit', '-qam', 'head');
+ const scope = await resolveScope({ base: 'HEAD~1', head: 'HEAD', repo });
+ expect(scope.files).toEqual([
+ {
+ base: 'src/features/Panel/Panel.tsx',
+ head: 'src/features/Panel/Panel.tsx',
+ reason: 'imports-changed-style',
+ },
+ {
+ base: 'src/features/Panel/styles/Inner.tsx',
+ head: 'src/features/Panel/styles/Inner.tsx',
+ reason: 'imports-changed-style',
+ },
+ ]);
+ });
+
+ it('pairs a moved component by rename and keeps added and deleted files one-sided', async () => {
+ git('mv', 'src/features/Card/Card.tsx', 'src/features/Card/CardView.tsx');
+ await write('src/features/New/Fresh.tsx', 'export const Fresh = () => <p />;\n');
+ git('rm', '-q', 'src/features/Other/Unrelated.tsx');
+ git('add', '.');
+ git('commit', '-qm', 'head');
+ const scope = await resolveScope({ base: 'HEAD~1', head: 'HEAD', repo });
+ expect(scope.files).toEqual([
+ {
+ base: 'src/features/Card/Card.tsx',
+ head: 'src/features/Card/CardView.tsx',
+ reason: 'renamed',
+ },
+ { head: 'src/features/New/Fresh.tsx', reason: 'added' },
+ { base: 'src/features/Other/Unrelated.tsx', reason: 'deleted' },
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/source/scope.ts b/packages/style-equivalence/src/source/scope.ts
new file mode 100644
index 00000000000..134f31395a1
--- /dev/null
+++ b/packages/style-equivalence/src/source/scope.ts
@@ -0,0 +1,157 @@
+import { execFile, spawn } from 'node:child_process';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+const run = promisify(execFile);
+
+export type ScopeReason = 'added' | 'changed' | 'deleted' | 'imports-changed-style' | 'renamed';
+
+export interface ScopeFile {
+ base?: string;
+ head?: string;
+ reason: ScopeReason;
+}
+
+export interface ScopeOptions {
+ aliases?: Record<string, string>;
+ base: string;
+ head: string;
+ repo: string;
+ restrictTo?: string[];
+}
+
+const COMPONENT = /\.tsx$/;
+export const STYLE_FACTORY =
+ /createStaticStyles|createStyles|stylex\.(?:create|defineVars|defineConsts|keyframes)/;
+const IMPORT = /(?:import|export)\s[^'"]*?from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]/g;
+
+const git = async (repo: string, args: string[]) =>
+ (await run('git', ['-C', repo, ...args], { maxBuffer: 256 * 1024 ** 2 })).stdout;
+
+const show = async (repo: string, revision: string, file: string) => {
+ try {
+ return await git(repo, ['show', `${revision}:${file}`]);
+ } catch {
+ return '';
+ }
+};
+
+const escapeRegex = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+const readBatch = (repo: string, objects: string[]) =>
+ new Promise<string[]>((resolve, reject) => {
+ const child = spawn('git', ['-C', repo, 'cat-file', '--batch'], {
+ stdio: ['pipe', 'pipe', 'inherit'],
+ });
+ const chunks: Buffer[] = [];
+ child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk));
+ child.on('error', reject);
+ child.on('close', () => {
+ const buffer = Buffer.concat(chunks);
+ const contents: string[] = [];
+ let offset = 0;
+ for (let index = 0; index < objects.length; index++) {
+ const newline = buffer.indexOf(10, offset);
+ const header = buffer.subarray(offset, newline).toString();
+ offset = newline + 1;
+ const size = Number(header.split(' ')[2]);
+ if (header.endsWith('missing') || Number.isNaN(size)) {
+ contents.push('');
+ continue;
+ }
+ contents.push(buffer.subarray(offset, offset + size).toString());
+ offset += size + 1;
+ }
+ resolve(contents);
+ });
+ child.stdin.end(objects.map((object) => `${object}\n`).join(''));
+ });
+
+const resolveSpecifier = (from: string, specifier: string, aliases: Record<string, string>) => {
+ let target: string | undefined;
+ if (specifier.startsWith('.')) target = path.posix.join(path.posix.dirname(from), specifier);
+ for (const [prefix, directory] of Object.entries(aliases))
+ if (specifier.startsWith(prefix))
+ target = path.posix.join(directory, specifier.slice(prefix.length));
+ if (!target) return [];
+ target = target.replace(/\/+$/, '');
+ return [target, `${target}.ts`, `${target}.tsx`, `${target}/index.ts`, `${target}/index.tsx`];
+};
+
+export const resolveScope = async ({
+ aliases = { '@/': 'src/' },
+ base,
+ head,
+ repo,
+ restrictTo,
+}: ScopeOptions): Promise<{ files: ScopeFile[] }> => {
+ const allowed = restrictTo && new Set(restrictTo);
+ const status = await git(repo, ['diff', '--name-status', '-M', base, head]);
+ const files = new Map<string, ScopeFile>();
+ const styleModules = new Set<string>();
+ for (const line of status.split('\n').filter(Boolean)) {
+ const [code, first, second] = line.split('\t');
+ if (allowed && !allowed.has(first) && !(second && allowed.has(second))) continue;
+ const kind = code[0];
+ if (kind === 'R' && COMPONENT.test(second)) {
+ files.set(first, { base: first, head: second, reason: 'renamed' });
+ continue;
+ }
+ const file = second ?? first;
+ if (COMPONENT.test(file)) {
+ if (kind === 'A') files.set(file, { head: file, reason: 'added' });
+ else if (kind === 'D') files.set(file, { base: file, reason: 'deleted' });
+ else files.set(file, { base: file, head: file, reason: 'changed' });
+ continue;
+ }
+ if (file.endsWith('.css')) styleModules.add(file);
+ else if (file.endsWith('.ts')) {
+ const sources = await Promise.all([show(repo, base, first), show(repo, head, file)]);
+ if (sources.some((source) => STYLE_FACTORY.test(source))) styleModules.add(file);
+ }
+ }
+
+ const stems = new Set<string>();
+ for (const file of styleModules) {
+ const stem = path.posix.basename(file).replace(/\.[^.]+$/, '');
+ stems.add(stem);
+ if (stem === 'index') stems.add(path.posix.basename(path.posix.dirname(file)));
+ }
+ const candidates = new Set<string>();
+ if (stems.size) {
+ const forms = [`['"/](${[...stems].map(escapeRegex).join('|')})(\\.[a-z]+|/)?['"]`];
+ if (stems.has('index')) forms.push(`['"]\\.\\.?/?['"]`);
+ const pattern = forms.join('|');
+ let output = '';
+ try {
+ output = await git(repo, ['grep', '-l', '-E', pattern, head, '--', '*.tsx']);
+ } catch {
+ output = '';
+ }
+ for (const line of output.split('\n').filter(Boolean)) {
+ const file = line.slice(head.length + 1);
+ if (!files.has(file)) candidates.add(file);
+ }
+ }
+ const ordered = [...candidates].sort();
+ const contents = await readBatch(
+ repo,
+ ordered.map((file) => `${head}:${file}`),
+ );
+ for (const [index, candidate] of ordered.entries()) {
+ const code = contents[index];
+ for (const match of code.matchAll(IMPORT)) {
+ const specifier = match[1] ?? match[2];
+ if (
+ resolveSpecifier(candidate, specifier, aliases).some((target) => styleModules.has(target))
+ ) {
+ files.set(candidate, { base: candidate, head: candidate, reason: 'imports-changed-style' });
+ break;
+ }
+ }
+ }
+
+ return {
+ files: [...files.values()].sort((a, b) => (a.base ?? a.head!).localeCompare(b.base ?? b.head!)),
+ };
+};
diff --git a/packages/style-equivalence/src/source/worktrees.test.ts b/packages/style-equivalence/src/source/worktrees.test.ts
new file mode 100644
index 00000000000..5ba752db585
--- /dev/null
+++ b/packages/style-equivalence/src/source/worktrees.test.ts
@@ -0,0 +1,109 @@
+import { execFileSync } from 'node:child_process';
+import { lstat, mkdir, mkdtemp, readlink, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { prepareRevisions } from './worktrees';
+
+let repo: string;
+let runDir: string;
+const git = (...args: string[]) =>
+ execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim();
+
+beforeEach(async () => {
+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-wt-'));
+ runDir = await mkdtemp(path.join(tmpdir(), 'style-eq-run-'));
+ git('init', '-q');
+ git('config', 'user.email', 't@t');
+ git('config', 'user.name', 't');
+ await writeFile(path.join(repo, 'package.json'), '{"dependencies":{"a":"1.0.0"}}\n');
+ await writeFile(path.join(repo, 'index.tsx'), 'export const A = 1;\n');
+ await mkdir(path.join(repo, 'node_modules'));
+ git('add', 'package.json', 'index.tsx');
+ git('commit', '-qm', 'base');
+});
+
+afterEach(async () => {
+ await rm(repo, { force: true, recursive: true });
+ await rm(runDir, { force: true, recursive: true });
+});
+
+const worktreeList = () => git('worktree', 'list', '--porcelain');
+
+describe('prepareRevisions', () => {
+ it('shares the checkout dependencies when manifests are unchanged and cleans up', async () => {
+ await writeFile(path.join(repo, 'index.tsx'), 'export const A = 2;\n');
+ git('commit', '-qam', 'head');
+ const installs: string[] = [];
+ const revisions = await prepareRevisions({
+ base: 'HEAD~1',
+ head: 'HEAD',
+ install: async (root) => void installs.push(root),
+ repo,
+ runDir,
+ });
+ expect(revisions.dependencyMode).toBe('shared');
+ expect(installs).toEqual([]);
+ expect(await readlink(path.join(revisions.head.root, 'node_modules'))).toBe(
+ path.join(repo, 'node_modules'),
+ );
+ expect(worktreeList()).toContain(revisions.base.root);
+ await revisions.cleanup();
+ expect(worktreeList()).not.toContain(revisions.base.root);
+ expect(worktreeList()).not.toContain(revisions.head.root);
+ });
+
+ it("shares each workspace package's own dependencies too", async () => {
+ await mkdir(path.join(repo, 'packages/runtime/node_modules'), { recursive: true });
+ await writeFile(path.join(repo, 'packages/runtime/package.json'), '{"name":"runtime"}\n');
+ git('add', 'packages/runtime/package.json');
+ git('commit', '-qm', 'workspace');
+ await writeFile(path.join(repo, 'index.tsx'), 'export const A = 3;\n');
+ git('commit', '-qam', 'head');
+ const revisions = await prepareRevisions({
+ base: 'HEAD~1',
+ head: 'HEAD',
+ install: async () => undefined,
+ repo,
+ runDir,
+ });
+ expect(await readlink(path.join(revisions.base.root, 'packages/runtime/node_modules'))).toBe(
+ path.join(repo, 'packages/runtime/node_modules'),
+ );
+ await revisions.cleanup();
+ });
+
+ it('installs each side separately when a manifest changed', async () => {
+ await writeFile(path.join(repo, 'package.json'), '{"dependencies":{"a":"2.0.0"}}\n');
+ git('commit', '-qam', 'head');
+ const installs: string[] = [];
+ const revisions = await prepareRevisions({
+ base: 'HEAD~1',
+ head: 'HEAD',
+ install: async (root) => void installs.push(root),
+ repo,
+ runDir,
+ });
+ expect(revisions.dependencyMode).toBe('isolated');
+ expect(installs.sort()).toEqual([revisions.base.root, revisions.head.root].sort());
+ expect(
+ (
+ await lstat(path.join(revisions.base.root, 'node_modules')).catch(() => undefined)
+ )?.isSymbolicLink(),
+ ).not.toBe(true);
+ await revisions.cleanup();
+ });
+
+ it('removes created worktrees when preparation fails', async () => {
+ await expect(
+ prepareRevisions({ base: 'HEAD', head: 'does-not-exist', repo, runDir }),
+ ).rejects.toThrow();
+ expect(
+ worktreeList()
+ .split('\n')
+ .filter((line) => line.startsWith('worktree ')),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/style-equivalence/src/source/worktrees.ts b/packages/style-equivalence/src/source/worktrees.ts
new file mode 100644
index 00000000000..c4b92c5ecc1
--- /dev/null
+++ b/packages/style-equivalence/src/source/worktrees.ts
@@ -0,0 +1,102 @@
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { symlink } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+const run = promisify(execFile);
+
+export type DependencyMode = 'isolated' | 'shared';
+
+export interface Revision {
+ revision: string;
+ root: string;
+}
+
+export interface PreparedRevisions {
+ base: Revision;
+ cleanup: () => Promise<void>;
+ dependencyMode: DependencyMode;
+ head: Revision;
+}
+
+export interface PrepareOptions {
+ base: string;
+ head: string;
+ install?: (root: string) => Promise<void>;
+ repo: string;
+ runDir: string;
+}
+
+const MANIFESTS = ['pnpm-lock.yaml', 'package.json', '**/package.json', 'pnpm-workspace.yaml'];
+
+const git = (repo: string, args: string[]) =>
+ run('git', ['-C', repo, ...args], { maxBuffer: 64 * 1024 ** 2 });
+
+export const defaultInstall = async (root: string) => {
+ const frozen = existsSync(path.join(root, 'pnpm-lock.yaml')) ? ['--frozen-lockfile'] : [];
+ await run('pnpm', ['install', ...frozen, '--ignore-scripts', '--prefer-offline'], {
+ cwd: root,
+ maxBuffer: 64 * 1024 ** 2,
+ });
+};
+
+const manifestsDiffer = async (repo: string, base: string, head: string) => {
+ try {
+ await git(repo, ['diff', '--quiet', base, head, '--', ...MANIFESTS]);
+ return false;
+ } catch (error) {
+ if ((error as { code?: number }).code === 1) return true;
+ throw error;
+ }
+};
+
+const shareDependencies = async (repo: string, root: string) => {
+ const manifests = (await git(root, ['ls-files', '--', 'package.json', '**/package.json'])).stdout
+ .split('\n')
+ .filter(Boolean);
+ for (const manifest of manifests) {
+ const directory = path.dirname(manifest);
+ const source = path.join(repo, directory, 'node_modules');
+ const target = path.join(root, directory, 'node_modules');
+ if (existsSync(source) && !existsSync(target)) await symlink(source, target);
+ }
+};
+
+export const prepareRevisions = async ({
+ base,
+ head,
+ install = defaultInstall,
+ repo,
+ runDir,
+}: PrepareOptions): Promise<PreparedRevisions> => {
+ const created: string[] = [];
+ const cleanup = async () => {
+ for (const directory of created.splice(0).reverse())
+ await git(repo, ['worktree', 'remove', '--force', directory]).catch(() => undefined);
+ await git(repo, ['worktree', 'prune']).catch(() => undefined);
+ };
+ try {
+ const sides = {} as Record<'base' | 'head', Revision>;
+ for (const [side, revision] of [
+ ['base', base],
+ ['head', head],
+ ] as const) {
+ const root = path.join(runDir, `wt-${side}`);
+ await git(repo, ['worktree', 'add', '--detach', root, revision]);
+ created.push(root);
+ sides[side] = { revision, root };
+ }
+ const dependencyMode: DependencyMode = (await manifestsDiffer(repo, base, head))
+ ? 'isolated'
+ : 'shared';
+ for (const side of Object.values(sides)) {
+ if (dependencyMode === 'shared') await shareDependencies(repo, side.root);
+ else await install(side.root);
+ }
+ return { ...sides, cleanup, dependencyMode };
+ } catch (error) {
+ await cleanup();
+ throw error;
+ }
+};
diff --git a/packages/style-equivalence/src/stack/index.ts b/packages/style-equivalence/src/stack/index.ts
new file mode 100644
index 00000000000..d90d59b2bca
--- /dev/null
+++ b/packages/style-equivalence/src/stack/index.ts
@@ -0,0 +1,180 @@
+import { execFile } from 'node:child_process';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import type { Browser } from '@playwright/test';
+
+import { DEFAULT_MUTATIONS, runComparison, type RunResult } from '../run';
+import { STYLE_FACTORY } from '../source/scope';
+
+const exec = promisify(execFile);
+
+const IDENTITY = {
+ GIT_AUTHOR_EMAIL: 'style-equivalence@localhost',
+ GIT_AUTHOR_NAME: 'style-equivalence',
+ GIT_COMMITTER_EMAIL: 'style-equivalence@localhost',
+ GIT_COMMITTER_NAME: 'style-equivalence',
+};
+
+const git = async (cwd: string, args: string[]) =>
+ (
+ await exec('git', ['-c', 'core.hooksPath=/dev/null', ...args], {
+ cwd,
+ env: { ...process.env, ...IDENTITY },
+ maxBuffer: 64 * 1024 ** 2,
+ })
+ ).stdout.trim();
+
+export interface StackHead {
+ id: string;
+ sha: string;
+}
+
+export interface StackConflict {
+ files: string[];
+ id: string;
+}
+
+export const mergeStack = async ({
+ base,
+ heads,
+ repo,
+}: {
+ base: string;
+ heads: StackHead[];
+ repo: string;
+}) => {
+ const scratch = await mkdtemp(path.join(tmpdir(), 'style-eq-stack-merge-'));
+ const worktree = path.join(scratch, 'merge');
+ const baseSha = await git(repo, ['rev-parse', '--verify', `${base}^{commit}`]);
+ await git(repo, ['worktree', 'add', '--detach', '--quiet', worktree, baseSha]);
+ const merged: string[] = [];
+ const conflicts: StackConflict[] = [];
+ const resolved: StackConflict[] = [];
+ const stage = (index: 2 | 3, file: string) =>
+ git(worktree, ['show', `:${index}:${file}`]).catch(() => '');
+ const comparable = async (file: string) =>
+ /\.(tsx|css)$/.test(file) ||
+ (file.endsWith('.ts') &&
+ (await Promise.all([stage(2, file), stage(3, file)])).some((text) =>
+ STYLE_FACTORY.test(text),
+ ));
+ try {
+ for (const head of heads) {
+ try {
+ await git(worktree, ['merge', '--no-ff', '--no-edit', '--quiet', head.sha]);
+ merged.push(head.id);
+ continue;
+ } catch {
+ const files = (await git(worktree, ['diff', '--name-only', '--diff-filter=U']))
+ .split('\n')
+ .filter(Boolean);
+ const blocking = [];
+ for (const file of files) if (await comparable(file)) blocking.push(file);
+ if (blocking.length || !files.length) {
+ await git(worktree, ['merge', '--abort']).catch(() => undefined);
+ conflicts.push({ files: blocking.length ? blocking : files, id: head.id });
+ continue;
+ }
+ await git(worktree, ['checkout', '--ours', '--', ...files]);
+ await git(worktree, ['add', '--', ...files]);
+ await git(worktree, ['commit', '--no-edit', '--quiet']);
+ merged.push(head.id);
+ resolved.push({ files, id: head.id });
+ }
+ }
+ return {
+ base: baseSha,
+ conflicts,
+ head: await git(worktree, ['rev-parse', 'HEAD']),
+ merged,
+ resolved,
+ };
+ } finally {
+ await git(repo, ['worktree', 'remove', '--force', worktree]).catch(() => undefined);
+ await git(repo, ['worktree', 'prune']);
+ await rm(scratch, { force: true, recursive: true });
+ }
+};
+
+export interface Shard {
+ files: string[];
+ id: string;
+}
+
+export const planShards = (prs: Shard[]): Shard[] => {
+ const taken = new Set<string>();
+ return prs
+ .map(({ files, id }) => ({
+ files: files.filter((file) => !taken.has(file) && (taken.add(file), true)),
+ id,
+ }))
+ .filter((shard) => shard.files.length);
+};
+
+export interface StackOptions {
+ base: string;
+ browser?: Browser;
+ concurrency?: number;
+ configFile: string;
+ heads: StackHead[];
+ mutations?: number;
+ recordsDir: string;
+ repo: string;
+}
+
+export interface StackResult {
+ base: string;
+ conflicts: StackConflict[];
+ head: string;
+ mergeable: boolean;
+ merged: string[];
+ resolved: StackConflict[];
+ shards: Array<Shard & { result: RunResult }>;
+}
+
+export const runStack = async (options: StackOptions): Promise<StackResult> => {
+ const stack = await mergeStack(options);
+ const prs = await Promise.all(
+ options.heads
+ .filter((head) => stack.merged.includes(head.id))
+ .map(async (head) => ({
+ files: (await git(options.repo, ['diff', '--name-only', `${stack.base}...${head.sha}`]))
+ .split('\n')
+ .filter(Boolean),
+ id: head.id,
+ })),
+ );
+ const shards = planShards(prs);
+ const perShard = Math.max(
+ 1,
+ Math.ceil((options.mutations ?? DEFAULT_MUTATIONS) / Math.max(shards.length, 1)),
+ );
+ const results: StackResult['shards'] = [];
+ const queue = [...shards];
+ await Promise.all(
+ Array.from({ length: Math.min(options.concurrency ?? 2, shards.length) }, async () => {
+ for (let shard = queue.shift(); shard; shard = queue.shift()) {
+ const result = await runComparison({
+ base: stack.base,
+ browser: options.browser,
+ configFile: options.configFile,
+ head: stack.head,
+ mutations: options.mutations === 0 ? 0 : perShard,
+ recordsDir: options.recordsDir,
+ repo: options.repo,
+ restrictTo: shard.files,
+ });
+ results.push({ ...shard, result });
+ }
+ }),
+ );
+ const ordered = shards.map((shard) => results.find((entry) => entry.id === shard.id)!);
+ return {
+ ...stack,
+ mergeable: !stack.conflicts.length && ordered.every((entry) => entry.result.verdict.mergeable),
+ shards: ordered,
+ };
+};
diff --git a/packages/style-equivalence/src/stack/stack.test.ts b/packages/style-equivalence/src/stack/stack.test.ts
new file mode 100644
index 00000000000..cbc780980c8
--- /dev/null
+++ b/packages/style-equivalence/src/stack/stack.test.ts
@@ -0,0 +1,77 @@
+import { execFileSync } from 'node:child_process';
+import { 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 { mergeStack, planShards } from './index';
+
+let repo: string;
+const git = (...args: string[]) =>
+ execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], {
+ cwd: repo,
+ encoding: 'utf8',
+ }).trim();
+
+const commitOn = async (branch: string, files: Record<string, string>) => {
+ git('checkout', '-q', '-b', branch, 'main');
+ for (const [file, content] of Object.entries(files))
+ await writeFile(path.join(repo, file), content);
+ git('commit', '-qam', branch);
+ return git('rev-parse', 'HEAD');
+};
+
+beforeAll(async () => {
+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-stack-'));
+ git('init', '-q', '-b', 'main');
+ await writeFile(path.join(repo, 'a.txt'), 'a\n');
+ await writeFile(path.join(repo, 'b.txt'), 'b\n');
+ await writeFile(path.join(repo, 'A.tsx'), 'export const A = 1;\n');
+ await writeFile(path.join(repo, 'legacy.json'), '["one"]\n');
+ git('add', '.');
+ git('commit', '-qm', 'base');
+});
+
+afterAll(() => rm(repo, { force: true, recursive: true }));
+
+describe('mergeStack', () => {
+ it('merges every head and reports the one whose comparable sources conflict', async () => {
+ const heads = [
+ {
+ id: '1',
+ sha: await commitOn('pr-a', { 'A.tsx': 'export const A = 2;\n', 'legacy.json': '["a"]\n' }),
+ },
+ {
+ id: '2',
+ sha: await commitOn('pr-b', { 'b.txt': 'b from pr-b\n', 'legacy.json': '["b"]\n' }),
+ },
+ { id: '3', sha: await commitOn('pr-c', { 'A.tsx': 'export const A = 3;\n' }) },
+ ];
+ git('checkout', '-q', 'main');
+ const result = await mergeStack({ base: 'main', heads, repo });
+ expect(result.merged).toEqual(['1', '2']);
+ expect(result.conflicts).toEqual([{ files: ['A.tsx'], id: '3' }]);
+ expect(result.resolved).toEqual([{ files: ['legacy.json'], id: '2' }]);
+ expect(git('show', `${result.head}:A.tsx`)).toBe('export const A = 2;');
+ expect(git('show', `${result.head}:b.txt`)).toBe('b from pr-b');
+ expect(git('show', `${result.head}:legacy.json`)).toBe('["a"]');
+ expect(git('worktree', 'list').split('\n')).toHaveLength(1);
+ expect(git('status', '--porcelain')).toBe('');
+ });
+});
+
+describe('planShards', () => {
+ it('gives each file to the first PR that touches it and drops empty shards', () => {
+ expect(
+ planShards([
+ { files: ['src/A.tsx', 'src/B.tsx'], id: '1' },
+ { files: ['src/B.tsx'], id: '2' },
+ { files: ['src/C.tsx'], id: '3' },
+ ]),
+ ).toEqual([
+ { files: ['src/A.tsx', 'src/B.tsx'], id: '1' },
+ { files: ['src/C.tsx'], id: '3' },
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/verdict/assemble.ts b/packages/style-equivalence/src/verdict/assemble.ts
new file mode 100644
index 00000000000..4ab0580293a
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/assemble.ts
@@ -0,0 +1,114 @@
+import type { CaseResult } from '../analyze/diff';
+import type { FileExtraction } from '../extract';
+import type { FilePlan, PlanCase, Side } from '../plan/planFile';
+import { readReviews, reviewScope } from '../review/store';
+import {
+ type CaseHashInput,
+ collectCaseHashInput,
+ collectFileHashInput,
+ contentHash,
+} from '../signoff/hash';
+import type { ScopeFile } from '../source/scope';
+import type { CaseCategory } from './categorize';
+import { fileFlags, fileItemKey } from './fileItems';
+import { decideVerdict, type Verdict, type VerdictItem } from './index';
+
+export interface AssembleInput {
+ aliases: Record<string, string>;
+ calibration: Array<{ status: string }>;
+ cases: Array<{
+ category: CaseCategory;
+ key: string;
+ plan: PlanCase;
+ result: Pick<CaseResult, 'gaps' | 'rootCauses'>;
+ }>;
+ extractions: Record<string, Record<Side, FileExtraction>>;
+ mutation: { passed: boolean };
+ plans: FilePlan[];
+ pr?: number;
+ recordsDir: string;
+ roots: Record<Side, string>;
+ scope: ScopeFile[];
+ unparsedSelectors: string[];
+ verifierVersion: string;
+}
+
+export const unpairedKey = (file: string, side: Side, elementId: string) =>
+ `${file}|unpaired:${side}:${elementId}`;
+
+export const assembleVerdict = async (input: AssembleInput) => {
+ const sourcesOf = (file: string) => {
+ const entry = input.scope.find((item) => (item.head ?? item.base) === file);
+ return { base: entry?.base, head: entry?.head };
+ };
+ const evidence: Record<string, CaseHashInput> = {};
+ const hashFor = (
+ key: string,
+ file: string,
+ extra: Partial<Parameters<typeof collectCaseHashInput>[0]>,
+ ) => {
+ evidence[key] = collectCaseHashInput({
+ aliases: input.aliases,
+ extractions: input.extractions[file] ?? {},
+ roots: input.roots,
+ sources: sourcesOf(file),
+ verifierVersion: input.verifierVersion,
+ ...extra,
+ });
+ return contentHash(evidence[key]);
+ };
+ const items: VerdictItem[] = [
+ ...input.cases.map((entry) => ({
+ category: entry.category,
+ file: entry.plan.file,
+ flags: [...entry.plan.flags, ...entry.result.gaps],
+ hash: hashFor(entry.key, entry.plan.file, {
+ outcome: entry.category === 'difference' ? entry.result.rootCauses : undefined,
+ plan: entry.plan,
+ }),
+ key: entry.key,
+ })),
+ ...input.plans.flatMap((plan) =>
+ plan.unpaired.map(({ elementId, side }) => ({
+ category: 'unpaired' as const,
+ file: plan.file,
+ flags: ['UNPAIRED'],
+ hash: hashFor(unpairedKey(plan.file, side, elementId), plan.file, {
+ elementIds: { [side]: elementId },
+ }),
+ key: unpairedKey(plan.file, side, elementId),
+ })),
+ ),
+ ];
+ for (const plan of input.plans) {
+ const flags = fileFlags(plan, input.extractions[plan.file] ?? {});
+ if (!flags.length) continue;
+ const key = fileItemKey(plan.file);
+ evidence[key] = collectFileHashInput({
+ roots: input.roots,
+ sources: sourcesOf(plan.file),
+ verifierVersion: input.verifierVersion,
+ });
+ items.push({
+ category: 'needs-signoff',
+ file: plan.file,
+ flags,
+ hash: contentHash(evidence[key]),
+ key,
+ });
+ }
+ const { passes: signoffs, reworks } = await readReviews(
+ input.recordsDir,
+ items.map((item) => item.file),
+ reviewScope(items, input.pr),
+ );
+ const verdict: Verdict = decideVerdict({
+ calibration: input.calibration,
+ items,
+ mutation: input.mutation,
+ reworks,
+ signoffs,
+ unparsedSelectors: input.unparsedSelectors.length,
+ });
+ return { evidence, verdict };
+};
diff --git a/packages/style-equivalence/src/verdict/categorize.test.ts b/packages/style-equivalence/src/verdict/categorize.test.ts
new file mode 100644
index 00000000000..c335f0be272
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/categorize.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { categorizeCase } from './categorize';
+
+const plan = (flags: string[] = []) => ({ flags }) as never;
+
+describe('categorizeCase', () => {
+ it('sends an equal case with an unmodeled gap to sign-off', () => {
+ expect(categorizeCase(plan(), { gaps: ['CONTAINER_UNMODELED'], status: 'equal' })).toBe(
+ 'needs-signoff',
+ );
+ expect(categorizeCase(plan(), { gaps: [], status: 'equal' })).toBe('equal');
+ expect(categorizeCase(plan(['CROSS_COMPONENT']), { gaps: [], status: 'difference' })).toBe(
+ 'difference',
+ );
+ });
+
+ it('ignores unmodeled gaps on an element whose own chain and file rules did not change', () => {
+ const unchanged = { evidence: ['STYLE_CHAIN_UNCHANGED', 'FILE_RULES_UNCHANGED'], flags: [] };
+ expect(categorizeCase(unchanged, { gaps: ['PSEUDO_UNMODELED'], status: 'equal' })).toBe(
+ 'equal',
+ );
+ expect(
+ categorizeCase(
+ { evidence: ['STYLE_CHAIN_UNCHANGED'], flags: [] },
+ { gaps: ['PSEUDO_UNMODELED'], status: 'equal' },
+ ),
+ ).toBe('needs-signoff');
+ expect(categorizeCase(unchanged, { gaps: [], status: 'difference' })).toBe('difference');
+ });
+});
diff --git a/packages/style-equivalence/src/verdict/categorize.ts b/packages/style-equivalence/src/verdict/categorize.ts
new file mode 100644
index 00000000000..6feeeb7289f
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/categorize.ts
@@ -0,0 +1,18 @@
+import type { CaseResult } from '../analyze/diff';
+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 => {
+ if (result.status === 'error' || result.status === 'unstable') return 'blocking';
+ if (plan.flags.some((flag) => flag.startsWith('STYLEX_UNSUPPORTED:'))) return 'blocking';
+ if (result.status === 'difference') return 'difference';
+ const unchanged = ['STYLE_CHAIN_UNCHANGED', 'FILE_RULES_UNCHANGED'].every((item) =>
+ plan.evidence?.includes(item),
+ );
+ const gaps = unchanged ? [] : result.gaps;
+ return plan.flags.length || gaps.length ? 'needs-signoff' : 'equal';
+};
diff --git a/packages/style-equivalence/src/verdict/fileItems.test.ts b/packages/style-equivalence/src/verdict/fileItems.test.ts
new file mode 100644
index 00000000000..b4080f43b8e
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/fileItems.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { fileFlags, fileItemKey, STYLE_OUTSIDE_JSX } from './fileItems';
+
+const side = (outsideReferences: string[] = []) => ({ outsideReferences });
+
+describe('fileFlags', () => {
+ it('carries file gaps and style references outside JSX into a file-level item', () => {
+ expect(
+ fileFlags(
+ { gaps: ['STYLESHEET_UNREADABLE:./a.css'] },
+ { base: side(['styles@4']), head: side() },
+ ),
+ ).toEqual(['STYLESHEET_UNREADABLE:./a.css', STYLE_OUTSIDE_JSX]);
+ });
+
+ it('has nothing to sign when every style use is inside JSX', () => {
+ expect(fileFlags({ gaps: [] }, { base: side(), head: side() })).toEqual([]);
+ });
+
+ it('keys the item by file', () => {
+ expect(fileItemKey('src/A.tsx')).toBe('src/A.tsx|file');
+ });
+});
diff --git a/packages/style-equivalence/src/verdict/fileItems.ts b/packages/style-equivalence/src/verdict/fileItems.ts
new file mode 100644
index 00000000000..b3ba98d813f
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/fileItems.ts
@@ -0,0 +1,16 @@
+import type { FileExtraction } from '../extract';
+import type { FilePlan, Side } from '../plan/planFile';
+
+export const STYLE_OUTSIDE_JSX = 'STYLE_OUTSIDE_JSX';
+
+export const fileItemKey = (file: string) => `${file}|file`;
+
+export const fileFlags = (
+ plan: Pick<FilePlan, 'gaps'>,
+ pair: Partial<Record<Side, Pick<FileExtraction, 'outsideReferences'>>>,
+) => [
+ ...plan.gaps,
+ ...((['base', 'head'] as const).some((side) => pair[side]?.outsideReferences.length)
+ ? [STYLE_OUTSIDE_JSX]
+ : []),
+];
diff --git a/packages/style-equivalence/src/verdict/index.ts b/packages/style-equivalence/src/verdict/index.ts
new file mode 100644
index 00000000000..c62db2441d9
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/index.ts
@@ -0,0 +1,139 @@
+import type { ReworkRecord } from '../review/store';
+import type { SignoffRecord } from '../signoff/store';
+import type { CaseCategory } from './categorize';
+
+export const FALSE_POSITIVE = 'TOOL_FALSE_POSITIVE';
+export const UNPAIRED = 'UNPAIRED';
+
+export interface VerdictItem {
+ category: CaseCategory | 'unpaired';
+ file: string;
+ flags: string[];
+ hash: string;
+ key: string;
+}
+
+export type SignoffState = 'missing' | 'not-needed' | 'stale' | 'valid';
+
+export const allowedReasons = (item: VerdictItem) => {
+ if (item.category === 'unpaired') return [UNPAIRED];
+ if (item.category === 'difference') return item.flags.length ? [FALSE_POSITIVE] : [];
+ if (item.category === 'needs-signoff') return item.flags;
+ return [];
+};
+
+const needsSignoff = (item: VerdictItem) =>
+ item.category === 'unpaired' ||
+ item.category === 'needs-signoff' ||
+ item.category === 'difference';
+
+const coveredReasons = (item: VerdictItem, record: SignoffRecord | undefined) =>
+ record && record.hash === item.hash ? (record.reasons ?? [record.reason]) : [];
+
+export const signoffState = (
+ item: VerdictItem,
+ record: SignoffRecord | undefined,
+): SignoffState => {
+ if (!needsSignoff(item)) return 'not-needed';
+ if (!record) return 'missing';
+ if (record.hash !== item.hash) return 'stale';
+ const allowed = allowedReasons(item);
+ const covered = coveredReasons(item, record);
+ if (allowed.length && allowed.every((reason) => covered.includes(reason))) return 'valid';
+ return covered.some((reason) => allowed.includes(reason)) ? 'missing' : 'stale';
+};
+
+export interface SignRequest {
+ existing?: Map<string, SignoffRecord>;
+ items: VerdictItem[];
+ keys: string[];
+ note: string;
+ now: string;
+ reason: string;
+ signer: string;
+}
+
+export const signCases = ({ existing, items, keys, note, now, reason, signer }: SignRequest) => {
+ const byKey = new Map(items.map((item) => [item.key, item]));
+ const selected = keys.map((key) => {
+ const item = byKey.get(key);
+ if (!item) throw new Error(`UNKNOWN_CASE:${key}`);
+ return item;
+ });
+ if (selected.length > 1 && selected.some((item) => item.category === 'unpaired'))
+ throw new Error('UNPAIRED_ONE_BY_ONE');
+ for (const item of selected) {
+ if (item.category === 'difference' && !item.flags.length)
+ throw new Error(`UNFLAGGED_DIFFERENCE:${item.key}`);
+ if (!allowedReasons(item).includes(reason))
+ throw new Error(`REASON_NOT_ALLOWED:${item.key}:${reason}`);
+ }
+ if (!note.trim()) throw new Error('NOTE_REQUIRED');
+ return selected.map((item): SignoffRecord => ({
+ hash: item.hash,
+ key: item.key,
+ note,
+ reason,
+ reasons: [...new Set([...coveredReasons(item, existing?.get(item.key)), reason])].sort(),
+ signedAt: now,
+ signer,
+ }));
+};
+
+export interface VerdictInput {
+ calibration: Array<{ status: string }>;
+ items: VerdictItem[];
+ mutation: { passed: boolean };
+ reworks?: Map<string, ReworkRecord>;
+ signoffs: Map<string, SignoffRecord>;
+ unparsedSelectors?: number;
+}
+
+export interface Verdict {
+ items: Array<VerdictItem & { signedReasons: string[]; signoff: SignoffState }>;
+ mergeable: boolean;
+ reasons: string[];
+}
+
+export const decideVerdict = ({
+ calibration,
+ items,
+ mutation,
+ reworks,
+ signoffs,
+ unparsedSelectors,
+}: VerdictInput): Verdict => {
+ const states = items.map((item) => ({
+ ...item,
+ signedReasons: coveredReasons(item, signoffs.get(item.key)).filter((reason) =>
+ allowedReasons(item).includes(reason),
+ ),
+ signoff: signoffState(item, signoffs.get(item.key)),
+ }));
+ const open = (predicate: (item: (typeof states)[number]) => boolean) =>
+ states.filter((item) => predicate(item) && item.signoff !== 'valid');
+ const reasons: string[] = [];
+ const blocking = states.filter((item) => item.category === 'blocking').length;
+ if (blocking) reasons.push(`blocking ${blocking}`);
+ const differences = open((item) => item.category === 'difference');
+ if (differences.length) reasons.push(`difference ${differences.length}`);
+ for (const [category, label] of [
+ ['needs-signoff', 'needs sign-off'],
+ ['unpaired', 'unpaired'],
+ ] as const) {
+ const unsigned = open((item) => item.category === category);
+ if (!unsigned.length) continue;
+ const stale = unsigned.filter((item) => item.signoff === 'stale').length;
+ reasons.push(`${label} ${unsigned.length}${stale ? ` (${stale} stale)` : ''}`);
+ }
+ const hashes = new Map(items.map((item) => [item.key, item.hash]));
+ const openReworks = [...(reworks?.values() ?? [])].filter(
+ (rework) => !rework.resolvedAt && hashes.get(rework.key) === rework.hash,
+ ).length;
+ if (openReworks) reasons.push(`rework open ${openReworks}`);
+ const mismatches = calibration.filter((entry) => entry.status === 'mismatch').length;
+ if (mismatches) reasons.push(`calibration mismatch ${mismatches}`);
+ if (!mutation.passed) reasons.push('mutation not fully caught');
+ if (unparsedSelectors) reasons.push(`selector unparsed ${unparsedSelectors}`);
+ return { items: states, mergeable: !reasons.length, reasons };
+};
diff --git a/packages/style-equivalence/src/verdict/verdict.test.ts b/packages/style-equivalence/src/verdict/verdict.test.ts
new file mode 100644
index 00000000000..7d50b207eb0
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/verdict.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from 'vitest';
+
+import { decideVerdict, signCases, type VerdictItem } from './index';
+
+const item = (
+ key: string,
+ category: VerdictItem['category'],
+ flags: string[] = [],
+): VerdictItem => ({
+ category,
+ file: 'src/A.tsx',
+ flags,
+ hash: `hash-${key}`,
+ key,
+});
+
+const items = [
+ item('src/A.tsx|A#0', 'equal'),
+ item('src/A.tsx|A#1', 'needs-signoff', ['PLACEMENT_SUBSTITUTED']),
+ item('src/A.tsx|A#2', 'needs-signoff', ['PLACEMENT_SUBSTITUTED']),
+ item('src/A.tsx|A#3', 'difference', ['CROSS_COMPONENT']),
+ item('src/A.tsx|unpaired:base:A#9', 'unpaired'),
+];
+
+const sign = (keys: string[], reason: string, list = items) =>
+ signCases({
+ items: list,
+ keys,
+ note: 'checked',
+ now: '2026-11-04T00:00:00.000Z',
+ reason,
+ signer: 'innei',
+ });
+
+const allSigned = () => [
+ ...sign(['src/A.tsx|A#1', 'src/A.tsx|A#2'], 'PLACEMENT_SUBSTITUTED'),
+ ...sign(['src/A.tsx|A#3'], 'TOOL_FALSE_POSITIVE'),
+ ...sign(['src/A.tsx|unpaired:base:A#9'], 'UNPAIRED'),
+];
+
+const verdict = (overrides: Partial<Parameters<typeof decideVerdict>[0]> = {}) =>
+ decideVerdict({
+ calibration: [{ status: 'agree' }],
+ items,
+ mutation: { passed: true },
+ signoffs: new Map(allSigned().map((record) => [record.key, record])),
+ ...overrides,
+ });
+
+describe('signCases', () => {
+ it('refuses to sign an unflagged difference', () => {
+ expect(() =>
+ sign(['src/A.tsx|B#0'], 'TOOL_FALSE_POSITIVE', [item('src/A.tsx|B#0', 'difference')]),
+ ).toThrow('UNFLAGGED_DIFFERENCE');
+ });
+
+ it('only signs a flagged difference as a tool false positive', () => {
+ expect(() => sign(['src/A.tsx|A#3'], 'CROSS_COMPONENT')).toThrow('REASON_NOT_ALLOWED');
+ });
+
+ it('signs a batch only within one reason group and unpaired elements one at a time', () => {
+ expect(() => sign(['src/A.tsx|A#1', 'src/A.tsx|A#3'], 'PLACEMENT_SUBSTITUTED')).toThrow(
+ 'REASON_NOT_ALLOWED',
+ );
+ expect(() =>
+ sign(['src/A.tsx|unpaired:base:A#9', 'src/A.tsx|unpaired:head:A#8'], 'UNPAIRED', [
+ ...items,
+ item('src/A.tsx|unpaired:head:A#8', 'unpaired'),
+ ]),
+ ).toThrow('UNPAIRED_ONE_BY_ONE');
+ expect(
+ sign(['src/A.tsx|A#1', 'src/A.tsx|A#2'], 'PLACEMENT_SUBSTITUTED').map(
+ (record) => record.hash,
+ ),
+ ).toEqual(['hash-src/A.tsx|A#1', 'hash-src/A.tsx|A#2']);
+ });
+});
+
+describe('decideVerdict', () => {
+ it('is mergeable only when every term holds', () => {
+ expect(verdict()).toMatchObject({ mergeable: true, reasons: [] });
+ expect(verdict({ mutation: { passed: false } }).reasons).toEqual(['mutation not fully caught']);
+ expect(verdict({ calibration: [{ status: 'mismatch' }] }).reasons).toEqual([
+ 'calibration mismatch 1',
+ ]);
+ expect(verdict({ items: [...items, item('src/A.tsx|C#0', 'blocking')] }).reasons).toEqual([
+ 'blocking 1',
+ ]);
+ expect(verdict({ items: [...items, item('src/A.tsx|D#0', 'difference')] }).reasons).toEqual([
+ 'difference 1',
+ ]);
+ expect(verdict({ signoffs: new Map() }).mergeable).toBe(false);
+ });
+
+ it('refuses a run whose page held selectors it could not evaluate', () => {
+ const result = decideVerdict({
+ calibration: [],
+ items: [],
+ mutation: { passed: true },
+ signoffs: new Map(),
+ unparsedSelectors: 2,
+ });
+ expect(result).toMatchObject({ mergeable: false, reasons: ['selector unparsed 2'] });
+ });
+
+ it('counts unsigned unpaired elements apart from unsigned cases', () => {
+ expect(verdict({ signoffs: new Map() }).reasons).toEqual([
+ 'difference 1',
+ 'needs sign-off 2',
+ 'unpaired 1',
+ ]);
+ });
+
+ it('treats a sign-off whose hash no longer matches as stale', () => {
+ const changed = items.map((entry) =>
+ entry.key === 'src/A.tsx|A#1' ? { ...entry, hash: 'hash-after-source-change' } : entry,
+ );
+ const result = verdict({ items: changed });
+ expect(result.mergeable).toBe(false);
+ expect(result.reasons).toEqual(['needs sign-off 1 (1 stale)']);
+ expect(result.items.find((entry) => entry.key === 'src/A.tsx|A#1')?.signoff).toBe('stale');
+ });
+});
+
+describe('sign-off coverage', () => {
+ const twoFlags = [
+ item('src/A.tsx|C#0', 'needs-signoff', ['CROSS_COMPONENT', 'PLACEMENT_SUBSTITUTED']),
+ ];
+ const state = (records: ReturnType<typeof sign>) =>
+ decideVerdict({
+ calibration: [],
+ items: twoFlags,
+ mutation: { passed: true },
+ signoffs: new Map(records.map((record) => [record.key, record])),
+ }).items[0];
+
+ it('stays unsigned until every flag on the case has been signed', () => {
+ const first = sign(['src/A.tsx|C#0'], 'PLACEMENT_SUBSTITUTED', twoFlags);
+ expect(state(first)).toMatchObject({
+ signedReasons: ['PLACEMENT_SUBSTITUTED'],
+ signoff: 'missing',
+ });
+ });
+
+ it('adds a reason to the existing record when the hash still matches', () => {
+ const first = sign(['src/A.tsx|C#0'], 'PLACEMENT_SUBSTITUTED', twoFlags);
+ const second = signCases({
+ existing: new Map(first.map((record) => [record.key, record])),
+ items: twoFlags,
+ keys: ['src/A.tsx|C#0'],
+ note: 'checked the outer row',
+ now: '2026-11-04T01:00:00.000Z',
+ reason: 'CROSS_COMPONENT',
+ signer: 'innei',
+ });
+ expect(second[0].reasons).toEqual(['CROSS_COMPONENT', 'PLACEMENT_SUBSTITUTED']);
+ expect(state(second).signoff).toBe('valid');
+ });
+});
diff --git a/packages/style-equivalence/src/vite-env.d.ts b/packages/style-equivalence/src/vite-env.d.ts
new file mode 100644
index 00000000000..11f02fe2a00
--- /dev/null
+++ b/packages/style-equivalence/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/packages/style-equivalence/test/fixtures/mini-project/host.css b/packages/style-equivalence/test/fixtures/mini-project/host.css
new file mode 100644
index 00000000000..3e34fb1b46e
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-project/host.css
@@ -0,0 +1,8 @@
+:root {
+ --ink: rgb(17 17 17);
+ --ink-alias: rgb(17 17 17);
+}
+
+body {
+ font-family: Arial, sans-serif;
+}
diff --git a/packages/style-equivalence/test/fixtures/mini-project/host.tsx b/packages/style-equivalence/test/fixtures/mini-project/host.tsx
new file mode 100644
index 00000000000..fd44626c2e5
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-project/host.tsx
@@ -0,0 +1,5 @@
+import './host.css';
+
+import type { ReactNode } from 'react';
+
+export const Host = ({ children }: { children: ReactNode }) => <div data-host="">{children}</div>;
diff --git a/packages/style-equivalence/test/fixtures/mini-project/style-equivalence.config.ts b/packages/style-equivalence/test/fixtures/mini-project/style-equivalence.config.ts
new file mode 100644
index 00000000000..73eb5e95afe
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-project/style-equivalence.config.ts
@@ -0,0 +1,17 @@
+import react from '@vitejs/plugin-react';
+
+import type { ProjectConfig } from '../../../src/config';
+import { cssModulesAdapter } from '../../../src/extract/adapters/cssModules';
+import { emotionStaticAdapter } from '../../../src/extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../../../src/extract/adapters/globalCss';
+
+const config: ProjectConfig = {
+ adapters: [emotionStaticAdapter, cssModulesAdapter, globalCssAdapter],
+ aliases: {},
+ conditions: { themeAttribute: 'data-theme', themes: ['light', 'dark'], widths: [375, 1280] },
+ hostWrapper: 'host.tsx',
+ layoutComponents: [],
+ vite: async () => ({ plugins: [react()] }),
+};
+
+export default config;
diff --git a/packages/style-equivalence/test/fixtures/mini-repo/package.json b/packages/style-equivalence/test/fixtures/mini-repo/package.json
new file mode 100644
index 00000000000..43172a17880
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-repo/package.json
@@ -0,0 +1,4 @@
+{
+ "name": "mini-repo",
+ "private": true
+}
diff --git a/packages/style-equivalence/test/fixtures/mini-repo/src/Card.module.css b/packages/style-equivalence/test/fixtures/mini-repo/src/Card.module.css
new file mode 100644
index 00000000000..9298c1defb1
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-repo/src/Card.module.css
@@ -0,0 +1,13 @@
+.card {
+ padding: 8px;
+}
+
+.active {
+ border-color: var(--ink-alias);
+ color: rgb(0 0 255);
+}
+
+.title {
+ font-weight: 600;
+ color: var(--ink);
+}
diff --git a/packages/style-equivalence/test/fixtures/mini-repo/src/Card.tsx b/packages/style-equivalence/test/fixtures/mini-repo/src/Card.tsx
new file mode 100644
index 00000000000..5a34b6560fa
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/mini-repo/src/Card.tsx
@@ -0,0 +1,7 @@
+import styles from './Card.module.css';
+
+export const Card = ({ active }: { active: boolean }) => (
+ <div className={active ? `${styles.card} ${styles.active}` : styles.card}>
+ <span className={styles.title}>Card</span>
+ </div>
+);
diff --git a/packages/style-equivalence/test/fixtures/stylex-project/host.tsx b/packages/style-equivalence/test/fixtures/stylex-project/host.tsx
new file mode 100644
index 00000000000..f5a598ddaef
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/stylex-project/host.tsx
@@ -0,0 +1,5 @@
+import type { ReactNode } from 'react';
+
+export const Host = ({ children }: { children: ReactNode }) => (
+ <div style={{ fontFamily: 'Arial, sans-serif' }}>{children}</div>
+);
diff --git a/packages/style-equivalence/test/fixtures/stylex-project/style-equivalence.config.ts b/packages/style-equivalence/test/fixtures/stylex-project/style-equivalence.config.ts
new file mode 100644
index 00000000000..bcf2e5610f3
--- /dev/null
+++ b/packages/style-equivalence/test/fixtures/stylex-project/style-equivalence.config.ts
@@ -0,0 +1,30 @@
+import stylex from '@stylexjs/unplugin/vite';
+import react from '@vitejs/plugin-react';
+
+import type { ProjectConfig } from '../../../src/config';
+import { cssModulesAdapter } from '../../../src/extract/adapters/cssModules';
+import { emotionStaticAdapter } from '../../../src/extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../../../src/extract/adapters/globalCss';
+import { stylexAdapter } from '../../../src/extract/adapters/stylex';
+
+const config: ProjectConfig = {
+ adapters: [emotionStaticAdapter, stylexAdapter, cssModulesAdapter, globalCssAdapter],
+ aliases: {},
+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [1280] },
+ cxFallback: { name: 'cx', source: '@lobehub/ui' },
+ hostWrapper: 'host.tsx',
+ layoutComponents: [],
+ vite: async (root) => ({
+ dedupe: ['react', 'react-dom', '@emotion/react', '@emotion/css', '@stylexjs/stylex'],
+ plugins: [
+ react(),
+ stylex({
+ dev: false,
+ runtimeInjection: true,
+ unstable_moduleResolution: { rootDir: root, type: 'commonJS' },
+ }),
+ ],
+ }),
+};
+
+export default config;
diff --git a/packages/style-equivalence/vitest.config.mts b/packages/style-equivalence/vitest.config.mts
new file mode 100644
index 00000000000..8ea0e05a6a6
--- /dev/null
+++ b/packages/style-equivalence/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ exclude: ['**/node_modules/**', 'test/fixtures/**'],
+ hookTimeout: 60_000,
+ testTimeout: 120_000,
+ },
+});
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 55f991090f6..c44fcc3a7d4 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -63,7 +63,7 @@ allowBuilds:
workerd: true
overrides:
- '@lobehub/ui': ^6.12.0
+ '@lobehub/ui': ^6.13.1
'@lobehub/icons': ^6.0.0
# Exact: an editor release can move its lexical version, and the root pins
# lexical; lift both together.
diff --git a/scripts/stylexMigration/classify.ts b/scripts/stylexMigration/classify.ts
index d57a9ab97b4..ff4dcb3688a 100644
--- a/scripts/stylexMigration/classify.ts
+++ b/scripts/stylexMigration/classify.ts
@@ -6,7 +6,9 @@
* - B: pseudo-classes / attributes on the element itself (`&:hover`) — codemod
* - C: descendant or ancestor coupling (`& .child`, `.parent:hover &`) — manual,
* stylex.defaultMarker() / stylex.when.ancestor() or an xstyle prop
- * - D: tag or third-party DOM selectors (`li`, `svg`, `.ProseMirror`) — scoped CSS
+ * - D: tag or third-party DOM selectors (`li`, `svg`, `.ProseMirror`) — manual: the
+ * component's classNames / styles slots or an xstyle prop; a createStaticStyles
+ * fallback only for DOM no prop reaches (editor content, rendered markdown)
*/
import legacyImports from './legacyImports.json';
diff --git a/scripts/stylexMigration/index.ts b/scripts/stylexMigration/index.ts
index 3abcfbfa0ca..51cba3bac04 100644
--- a/scripts/stylexMigration/index.ts
+++ b/scripts/stylexMigration/index.ts
@@ -60,6 +60,16 @@ export const scanRepo = (root = repoRoot): FileReport[] => {
export const readLegacyFiles = (): string[] =>
JSON.parse(readFileSync(legacyFilesPath, 'utf8')) as string[];
+export const plainCssImportersPath = path.join(import.meta.dirname, 'plainCssImporters.json');
+
+export const readPlainCssImporters = (): string[] =>
+ JSON.parse(readFileSync(plainCssImportersPath, 'utf8')) as string[];
+
+const PLAIN_CSS_IMPORT =
+ /^import\s+(?:[^'"]+\s+from\s+)?["'](?:\.{1,2}|@)\/(?:[^"']*\/)?[^/"']+(?<!\.module)\.css(?:\?[^"']*)?["']/m;
+
+export const importsPlainCss = (source: string) => PLAIN_CSS_IMPORT.test(source);
+
/** Listed files that no longer use an emotion style import, or no longer exist. */
export const findStaleLegacyFiles = (reports: FileReport[], legacy = readLegacyFiles()) => {
const current = new Set(reports.map((r) => r.file));
diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.json
index c23282b1846..6e6846096ea 100644
--- a/scripts/stylexMigration/legacyFiles.json
+++ b/scripts/stylexMigration/legacyFiles.json
@@ -18,18 +18,7 @@
"packages/alint/fixtures/ui-no-decorative-chrome/bad-boxed-section.tsx",
"packages/alint/fixtures/ui-restrained-color/bad-colored-type-and-link.tsx",
"packages/alint/fixtures/ui-restrained-color/good-status-and-gray-meta.tsx",
- "packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx",
- "packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx",
- "packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx",
- "packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx",
- "packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx",
- "packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx",
- "packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx",
- "packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx",
"packages/builtin-tool-agent-documents/src/client/Inspector/_styles.ts",
- "packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx",
- "packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx",
- "packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx",
"packages/builtin-tool-agent-documents/src/client/shared/styles.ts",
"packages/builtin-tool-agent-management/src/client/Inspector/CallAgent/index.tsx",
"packages/builtin-tool-agent-management/src/client/Inspector/CreateAgent/index.tsx",
@@ -39,41 +28,8 @@
"packages/builtin-tool-agent-management/src/client/Inspector/SearchAgent/index.tsx",
"packages/builtin-tool-agent-management/src/client/Inspector/UpdateAgent/index.tsx",
"packages/builtin-tool-agent-management/src/client/Inspector/UpdatePrompt/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx",
- "packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx",
- "packages/builtin-tool-browser/src/client/Inspector/Browser.tsx",
- "packages/builtin-tool-browser/src/client/Render/PageAction.tsx",
"packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx",
"packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx",
- "packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx",
- "packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx",
- "packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx",
- "packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx",
- "packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx",
- "packages/builtin-tool-dashboard/src/client/Inspector/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/BatchCreateAgents/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateAgent/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateGroup/index.tsx",
@@ -81,162 +37,51 @@
"packages/builtin-tool-group-agent-builder/src/client/Inspector/InviteAgent/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/RemoveAgent/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateAgentPrompt/index.tsx",
- "packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx",
"packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroupPrompt/index.tsx",
- "packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx",
- "packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx",
"packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx",
"packages/builtin-tool-group-management/src/client/Inspector/ExecuteAgentTask/index.tsx",
"packages/builtin-tool-group-management/src/client/Inspector/ExecuteAgentTasks/index.tsx",
"packages/builtin-tool-group-management/src/client/Inspector/Speak/index.tsx",
- "packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx",
- "packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx",
- "packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx",
- "packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx",
"packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx",
- "packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx",
- "packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx",
- "packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx",
- "packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx",
- "packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx",
"packages/builtin-tool-image-generation/src/client/Inspector/index.tsx",
- "packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx",
- "packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx",
"packages/builtin-tool-image-generation/src/client/Render/GetImageModelParameters.tsx",
"packages/builtin-tool-image-generation/src/client/Render/ListImageModels.tsx",
"packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx",
- "packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx",
- "packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx",
"packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx",
"packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/style.ts",
"packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx",
"packages/builtin-tool-lobe-agent/src/client/Inspector/UpdatePlan/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx",
- "packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx",
"packages/builtin-tool-lobe-agent/src/client/components/SortableTodoList/AddItemRow.tsx",
"packages/builtin-tool-lobe-agent/src/client/components/SortableTodoList/TodoItemRow.tsx",
- "packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx",
- "packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx",
- "packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx",
- "packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx",
- "packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx",
- "packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx",
"packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx",
- "packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx",
- "packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx",
"packages/builtin-tool-local-system/src/client/components/FileItem.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx",
- "packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx",
- "packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx",
"packages/builtin-tool-memory/src/client/components/MemoryCardParts.tsx",
- "packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx",
- "packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx",
"packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx",
- "packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx",
"packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx",
"packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx",
- "packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx",
- "packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx",
- "packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx",
- "packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx",
- "packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx",
- "packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx",
- "packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx",
- "packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx",
- "packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx",
- "packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx",
- "packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx",
- "packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx",
- "packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx",
- "packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx",
- "packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx",
- "packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx",
- "packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx",
"packages/builtin-tool-task/src/client/Intervention/CreateGoal.tsx",
- "packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx",
- "packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx",
- "packages/builtin-tool-task/src/client/Render/EditTask/index.tsx",
- "packages/builtin-tool-task/src/client/Render/RunTask/index.tsx",
- "packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx",
- "packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx",
"packages/builtin-tool-task/src/client/Render/shared.tsx",
- "packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx",
"packages/builtin-tool-video-generation/src/client/Inspector/index.tsx",
- "packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx",
- "packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx",
- "packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx",
"packages/builtin-tool-video-generation/src/client/Render/GetVideoModelParameters.tsx",
"packages/builtin-tool-video-generation/src/client/Render/ListVideoModels.tsx",
"packages/builtin-tool-web-browsing/src/client/Placeholder/Search.tsx",
"packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx",
- "packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx",
- "packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx",
"packages/builtin-tool-web-browsing/src/client/Render/PageContent/Loading.tsx",
"packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx",
"packages/builtin-tool-web-browsing/src/client/Render/Search/ConfigForm/style.tsx",
- "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx",
- "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx",
- "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx",
- "packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx",
"packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Inspector/_styles.ts",
"packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/style.ts",
- "packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx",
- "packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx",
"packages/builtin-tool-web-onboarding/src/client/Inspector/_styles.ts",
- "packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx",
- "packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx",
- "packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx",
"packages/builtin-tools/src/codex/CollabToolRender.tsx",
"packages/builtin-tools/src/codex/ErrorInspector.tsx",
- "packages/builtin-tools/src/codex/FileChangeInspector.tsx",
- "packages/builtin-tools/src/codex/FileChangeRender.tsx",
- "packages/builtin-tools/src/codex/McpToolRender.tsx",
- "packages/builtin-tools/src/codex/WebSearchRender.tsx",
"packages/builtin-tools/src/github/RunCommandInspector.tsx",
- "packages/builtin-tools/src/github/RunCommandRender.tsx",
- "packages/builtin-tools/src/notebook/DocumentCard.tsx",
- "packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx",
"packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx",
- "packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx",
- "packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx",
"packages/shared-tool-ui/src/Inspector/GitHub/Inspector.tsx",
- "packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx",
- "packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx",
- "packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx",
"packages/shared-tool-ui/src/Inspector/Linear/Inspector.tsx",
- "packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx",
"packages/shared-tool-ui/src/Inspector/Twitter/Inspector.tsx",
"packages/shared-tool-ui/src/Render/GitHub/index.tsx",
"packages/shared-tool-ui/src/Render/Linear/index.tsx",
- "packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx",
- "packages/shared-tool-ui/src/Render/RunCommand/index.tsx",
"packages/shared-tool-ui/src/components/FileChangeStats/index.tsx",
- "packages/shared-tool-ui/src/components/FilePathDisplay.tsx",
- "packages/shared-tool-ui/src/components/OptionCard.tsx",
- "packages/shared-tool-ui/src/components/TodoProgress/index.tsx",
"packages/shared-tool-ui/src/styles.ts",
"src/features/Acceptance/CriterionList/CriterionRow.tsx",
"src/features/Acceptance/Report/EvidenceComparisonCard.tsx",
@@ -312,10 +157,6 @@
"src/features/Acceptance/Workspace/AcceptanceRow.tsx",
"src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx",
"src/features/Acceptance/Workspace/index.tsx",
- "src/features/AddAgentMemberModal/AgentItem.tsx",
- "src/features/AddAgentMemberModal/AvailableAgentList.tsx",
- "src/features/AddAgentMemberModal/SelectedAgentList.tsx",
- "src/features/AddAgentMemberModal/index.tsx",
"src/features/AgentBreadcrumb/index.tsx",
"src/features/AgentBuilder/TopicSelector.tsx",
"src/features/AgentChannel/PlatformCard.tsx",
@@ -377,10 +218,6 @@
"src/features/AgentProfileCard/AgentProfilePopup.tsx",
"src/features/AgentProfileCard/index.tsx",
"src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx",
- "src/features/AgentSetting/AgentGraphRuntime/index.tsx",
- "src/features/AgentSetting/AgentOpening/OpeningMessage.tsx",
- "src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx",
- "src/features/AgentSetting/SettingsModalLayout.tsx",
"src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx",
"src/features/AgentSidebar/Topic/List/Item/index.tsx",
"src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx",
@@ -485,7 +322,6 @@
"src/features/ChatTerminal/Content.tsx",
"src/features/ChatTerminal/SplitView.tsx",
"src/features/CommandMenu/styles.ts",
- "src/features/CommunityWorkspaceSettings/index.tsx",
"src/features/ConnectAgent/index.tsx",
"src/features/Connectors/ConnectorDetail/ToolPermissionGroup.tsx",
"src/features/Connectors/ConnectorDetail/ToolPermissionRow.tsx",
@@ -722,16 +558,6 @@
"src/features/HomeInbox/index.tsx",
"src/features/HomeLayout/style.ts",
"src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx",
- "src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx",
- "src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx",
- "src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx",
- "src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx",
- "src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx",
- "src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx",
- "src/features/HomeSidebar/Header/components/InboxModal/Content.tsx",
- "src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx",
- "src/features/HomeSidebar/Header/components/InboxModal/index.tsx",
- "src/features/HomeSidebar/Header/components/User.tsx",
"src/features/HotkeyHelperPanel/HotkeyContent.tsx",
"src/features/Integrations/Github/Automation.tsx",
"src/features/Integrations/Github/Connections.tsx",
@@ -830,7 +656,6 @@
"src/features/PluginDevModal/MCPManifestForm/MCPTypeSelect.tsx",
"src/features/PluginDevModal/PluginPreview/ApiVisualizer.tsx",
"src/features/PluginDevModal/PluginPreview/EmptyState.tsx",
- "src/features/PluginSettings/index.tsx",
"src/features/Portal/AcceptanceCheck/Body.tsx",
"src/features/Portal/Artifacts/Body/Renderer/SVG.tsx",
"src/features/Portal/DashboardWidget/Body.tsx",
@@ -906,62 +731,6 @@
"src/features/SelfLearning/Portrait/WarmupCard.tsx",
"src/features/SelfLearning/Portrait/styles.ts",
"src/features/SelfLearning/index.tsx",
- "src/features/Setting/Footer.tsx",
- "src/features/Settings/Layout/style.ts",
- "src/features/Settings/about/features/About.tsx",
- "src/features/Settings/about/features/Version.tsx",
- "src/features/Settings/apikey/features/ApiKey.tsx",
- "src/features/Settings/apikey/features/ApiKeyDetail.tsx",
- "src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx",
- "src/features/Settings/apikey/features/ApiKeyModal/Content.tsx",
- "src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx",
- "src/features/Settings/apikey/features/EditableCell/index.tsx",
- "src/features/Settings/appearance/features/Font/FallbackFontList.tsx",
- "src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx",
- "src/features/Settings/common/features/Appearance/Preview.tsx",
- "src/features/Settings/creds/features/style.ts",
- "src/features/Settings/integrations/index.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx",
- "src/features/Settings/oauth-apps/features/AppDetail/index.tsx",
- "src/features/Settings/oauth-apps/features/AppItem/index.tsx",
- "src/features/Settings/oauth-apps/features/AppListSkeleton.tsx",
- "src/features/Settings/oauth-apps/features/AppLogo/index.tsx",
- "src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx",
- "src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx",
- "src/features/Settings/oauth-apps/features/OAuthApps.tsx",
- "src/features/Settings/oauth-apps/features/SecretModal/index.tsx",
- "src/features/Settings/profile/features/AvatarRow.tsx",
- "src/features/Settings/profile/features/ProfileRow.tsx",
- "src/features/Settings/provider/(list)/ProviderGrid/style.ts",
- "src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx",
- "src/features/Settings/provider/_layout/Desktop/style.ts",
- "src/features/Settings/provider/detail/github/index.tsx",
- "src/features/Settings/provider/detail/ollama/Container.tsx",
- "src/features/Settings/provider/detail/vertexai/index.tsx",
- "src/features/Settings/provider/features/ModelList/EmptyModels.tsx",
- "src/features/Settings/provider/features/ModelList/ModelItem.tsx",
- "src/features/Settings/provider/features/ModelList/SkeletonList.tsx",
- "src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx",
- "src/features/Settings/provider/features/ProviderConfig/Checker.tsx",
- "src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx",
- "src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx",
- "src/features/Settings/provider/features/ProviderConfig/index.tsx",
- "src/features/Settings/proxy/features/SaveBar.tsx",
- "src/features/Settings/skill/features/LeftPanel.tsx",
- "src/features/Settings/skill/features/SkillDetail/index.tsx",
- "src/features/Settings/skill/features/SkillList.tsx",
- "src/features/Settings/skill/features/style.ts",
- "src/features/Settings/skill/index.tsx",
- "src/features/Settings/stats/features/overview/ShareButton/Preview.tsx",
- "src/features/Settings/stats/features/usage/UsageTable.tsx",
- "src/features/Settings/trash/features/ProjectFilter.tsx",
- "src/features/Settings/trash/features/TrashList.tsx",
- "src/features/SettingsSearch/SearchResults.tsx",
- "src/features/SettingsSearch/anchor.tsx",
"src/features/ShareModal/ShareImage/style.ts",
"src/features/ShareModal/SharePdf/PdfPreview.tsx",
"src/features/ShareModal/SharePdf/index.tsx",
@@ -980,7 +749,6 @@
"src/features/SkillsList/SkillsList.tsx",
"src/features/TaskDock/Item.tsx",
"src/features/TaskDock/index.tsx",
- "src/features/ToolSetting/ChannelItem.tsx",
"src/features/ToolTag/index.tsx",
"src/features/TopicComment/MessageCommentBadge.tsx",
"src/features/TopicDoctorModal/Content.tsx",
@@ -995,8 +763,6 @@
"src/features/WorkGallery/WorkPreview.tsx",
"src/features/WorkGallery/WorkPreviewCard.tsx",
"src/features/WorkGallery/index.tsx",
- "src/features/WorkspaceSetting/Labels/LabelFormModal.tsx",
- "src/features/WorkspaceSetting/Labels/index.tsx",
"src/routes/(main)/(create)/components/GenerationModelItem.tsx",
"src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx",
"src/routes/(main)/(create)/features/GenerationInput/GenerationModelNotice/index.tsx",
diff --git a/scripts/stylexMigration/oxlint.mjs b/scripts/stylexMigration/oxlint.mjs
index d8430d1fc5f..25e40a04ae7 100644
--- a/scripts/stylexMigration/oxlint.mjs
+++ b/scripts/stylexMigration/oxlint.mjs
@@ -6,9 +6,13 @@ const readJson = (file) => JSON.parse(readFileSync(new URL(file, import.meta.url
const legacyImports = readJson('./legacyImports.json');
// `excludeFiles` entries are globs: route segments like `[benchmarkId]` and `(main)`
// would otherwise be read as character classes and groups.
-const legacyFiles = readJson('./legacyFiles.json').map((file) =>
- file.replaceAll(/[!()*+?@[\]{}]/g, String.raw`\$&`),
-);
+const escapeGlob = (file) => file.replaceAll(/[!()*+?@[\]{}]/g, String.raw`\$&`);
+const legacyFiles = readJson('./legacyFiles.json').map(escapeGlob);
+const plainCssImporters = readJson('./plainCssImporters.json').map(escapeGlob);
+const pluginEntry = {
+ name: 'stylex-migration',
+ specifier: fileURLToPath(new URL('./oxlintPlugin.mjs', import.meta.url)),
+};
/**
* StyleX migration guard. New code may not import the emotion-backed style APIs
@@ -21,12 +25,7 @@ export const stylexMigrationOverrides = [
// Tests mock @lobehub/ui, including its style factories; the guard is about
// shipped code.
excludeFiles: [...legacyFiles, '**/*.test.{ts,tsx}', '**/__tests__/**'],
- jsPlugins: [
- {
- name: 'stylex-migration',
- specifier: fileURLToPath(new URL('./oxlintPlugin.mjs', import.meta.url)),
- },
- ],
+ jsPlugins: [pluginEntry],
rules: {
'stylex-migration/no-emotion-styles': [
'error',
@@ -44,6 +43,25 @@ export const stylexMigrationOverrides = [
],
},
},
+ {
+ files: ['**/*.{ts,tsx}'],
+ excludeFiles: [...plainCssImporters, '**/*.test.{ts,tsx}', '**/__tests__/**'],
+ jsPlugins: [pluginEntry],
+ rules: {
+ 'stylex-migration/no-plain-css': [
+ 'error',
+ {
+ patterns: [
+ {
+ message:
+ 'Style the element with StyleX: a slot prop (classNames / styles), a pseudo-class on the slot element, or an xstyle prop (see the react skill). Only DOM no prop reaches keeps its nested rule in createStaticStyles.',
+ regex: String.raw`^(?:\.{1,2}|@)/(?:.*/)?[^/]+(?<!\.module)\.css(?:\?.*)?$`,
+ },
+ ],
+ },
+ ],
+ },
+ },
{
// The other StyleX rules come from the preset's `stylex` option; sort-keys is
// left to perfectionist/sort-objects, which already orders keys.
diff --git a/scripts/stylexMigration/oxlint.test.ts b/scripts/stylexMigration/oxlint.test.ts
index 5b3c6629ce7..8b12edcb2a1 100644
--- a/scripts/stylexMigration/oxlint.test.ts
+++ b/scripts/stylexMigration/oxlint.test.ts
@@ -7,7 +7,7 @@ import path from 'node:path';
import { defineConfig } from '@lobehub/oxlint-config';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
-import { readLegacyFiles } from '.';
+import { readLegacyFiles, readPlainCssImporters } from '.';
import { stylexMigrationOverrides } from './oxlint.mjs';
const repoRoot = path.resolve(import.meta.dirname, '../..');
@@ -68,3 +68,68 @@ describe('stylex-migration/no-emotion-styles config', () => {
);
}, 120_000);
});
+
+describe('stylex-migration/no-plain-css config', () => {
+ const cssRule = 'stylex-migration(no-plain-css)';
+ let dir: string;
+
+ const lint = (files: Record<string, string>) => {
+ for (const [file, source] of Object.entries(files)) {
+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
+ writeFileSync(path.join(dir, file), source);
+ }
+ const { stdout } = spawnSync(
+ oxlintBin,
+ ['-c', '.oxlintrc.json', '-f', 'json', ...Object.keys(files)],
+ { cwd: dir, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 },
+ );
+ const { diagnostics } = JSON.parse(stdout) as {
+ diagnostics: { code?: string; filename: string }[];
+ };
+ return new Set(diagnostics.filter((d) => d.code === cssRule).map((d) => d.filename));
+ };
+
+ beforeAll(() => {
+ dir = mkdtempSync(path.join(os.tmpdir(), 'stylex-plain-css-'));
+ const config = defineConfig(
+ { sortImports: false, sortKeys: false },
+ ...(stylexMigrationOverrides as Parameters<typeof defineConfig>[1][]),
+ );
+ writeFileSync(path.join(dir, '.oxlintrc.json'), JSON.stringify(config));
+ });
+
+ afterAll(() => {
+ rmSync(dir, { force: true, recursive: true });
+ });
+
+ it('reports relative and alias plain CSS imports, not CSS modules or package stylesheets', () => {
+ const reported = lint({
+ 'src/features/A/relative.tsx': "import './a.css';\n",
+ 'src/features/A/alias.tsx': "import '@/features/A/a.css';\n",
+ 'src/features/A/parent.tsx': "import '../shared.css';\n",
+ 'src/features/A/module.tsx': "import styles from './a.module.css';\n\nexport { styles };\n",
+ 'src/features/A/package.tsx': "import '@lobehub/ui/style.css';\n",
+ 'src/features/A/a.test.tsx': "import './a.css';\n",
+ });
+ expect(reported).toEqual(
+ new Set([
+ 'src/features/A/alias.tsx',
+ 'src/features/A/parent.tsx',
+ 'src/features/A/relative.tsx',
+ ]),
+ );
+ }, 120_000);
+
+ it('exempts every listed importer and an import disabled with a reason', () => {
+ const listed = Object.fromEntries(
+ readPlainCssImporters().map((file) => [file, "import './x.css';\n"]),
+ );
+ expect(Object.keys(listed).length).toBeGreaterThan(0);
+ const reported = lint({
+ ...listed,
+ 'src/features/B/editor.tsx':
+ "// oxlint-disable-next-line stylex-migration/no-plain-css -- ProseMirror content has no slot\nimport './editor.css';\n",
+ });
+ expect([...reported]).toEqual([]);
+ }, 120_000);
+});
diff --git a/scripts/stylexMigration/oxlintPlugin.mjs b/scripts/stylexMigration/oxlintPlugin.mjs
index 60a65ddfff0..970ef21c1b5 100644
--- a/scripts/stylexMigration/oxlintPlugin.mjs
+++ b/scripts/stylexMigration/oxlintPlugin.mjs
@@ -9,5 +9,8 @@ import core from '@lobehub/oxlint-config/plugins/eslint-core';
*/
export default {
meta: { name: 'stylex-migration' },
- rules: { 'no-emotion-styles': core.rules['no-restricted-imports'] },
+ rules: {
+ 'no-emotion-styles': core.rules['no-restricted-imports'],
+ 'no-plain-css': core.rules['no-restricted-imports'],
+ },
};
diff --git a/scripts/stylexMigration/plainCssImporters.json b/scripts/stylexMigration/plainCssImporters.json
new file mode 100644
index 00000000000..a40ec63f529
--- /dev/null
+++ b/scripts/stylexMigration/plainCssImporters.json
@@ -0,0 +1,38 @@
+[
+ "apps/auth/app/root.tsx",
+ "apps/share/app/root.tsx",
+ "apps/share/src/entry.tsx",
+ "apps/workbench/app/root.tsx",
+ "apps/workbench/src/entry.tsx",
+ "apps/workbench/src/localReport/entry.tsx",
+ "packages/canvas-runtime/src/index.tsx",
+ "packages/style-equivalence/src/report/main.tsx",
+ "packages/style-equivalence/test/fixtures/mini-project/host.tsx",
+ "scripts/stylexMigration/styleEquivalenceHost.tsx",
+ "scripts/stylexMigration/verification/fixtures/FixtureHost.tsx",
+ "src/components/CodeEditorPane/index.tsx",
+ "src/components/CommentList/CommentItem.tsx",
+ "src/components/GalleyGrid/Grid.tsx",
+ "src/components/GeneratingBorder/index.tsx",
+ "src/components/GuideModal/index.tsx",
+ "src/components/InlineTable/index.tsx",
+ "src/components/Loading/BrandTextLoading/index.tsx",
+ "src/components/Menu/index.tsx",
+ "src/components/Skeleton/Settings/Section.tsx",
+ "src/components/Skeleton/Settings/Sections.tsx",
+ "src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts",
+ "src/features/Acceptance/Report/TerminalEvidence/styles.ts",
+ "src/features/AgentChannel/PlatformDetail/Body.tsx",
+ "src/features/Auth/OAuthCallback/Success.tsx",
+ "src/features/Auth/OAuthDevice/DeviceSuccess.tsx",
+ "src/features/ChatInput/ControlBar/BranchSwitcher.tsx",
+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx",
+ "src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx",
+ "src/features/CommunitySkillDetail/Details/Install/Platform.tsx",
+ "src/features/CommunitySkillDetail/Details/Overview/index.tsx",
+ "src/features/Conversation/Messages/index.tsx",
+ "src/initialize.ts",
+ "src/layout/GlobalProvider/AppTheme.tsx",
+ "src/routes/(main)/community/(detail)/features/ShareButton.tsx",
+ "src/routes/(mobile)/_layout/NavBar.tsx"
+]
diff --git a/scripts/stylexMigration/plainCssImporters.test.ts b/scripts/stylexMigration/plainCssImporters.test.ts
new file mode 100644
index 00000000000..e2af8556594
--- /dev/null
+++ b/scripts/stylexMigration/plainCssImporters.test.ts
@@ -0,0 +1,31 @@
+// @vitest-environment node
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { importsPlainCss, readPlainCssImporters } from '.';
+
+const repoRoot = path.resolve(import.meta.dirname, '../..');
+
+describe('plainCssImporters.json', () => {
+ it('lists only files that still import a plain stylesheet', () => {
+ const stale = readPlainCssImporters().filter((file) => {
+ const absolute = path.join(repoRoot, file);
+ return !existsSync(absolute) || !importsPlainCss(readFileSync(absolute, 'utf8'));
+ });
+ expect(stale).toEqual([]);
+ });
+
+ it('stays sorted so removals diff as single lines', () => {
+ const files = readPlainCssImporters();
+ expect(files).toEqual([...files].sort());
+ });
+
+ it('tells plain stylesheets apart from CSS modules and package stylesheets', () => {
+ expect(importsPlainCss("import './a.css';")).toBe(true);
+ expect(importsPlainCss("import '@/styles/stylex.css';")).toBe(true);
+ expect(importsPlainCss("import styles from './a.module.css';")).toBe(false);
+ expect(importsPlainCss("import '@lobehub/ui/style.css';")).toBe(false);
+ });
+});
diff --git a/scripts/stylexMigration/style-equivalence.config.ts b/scripts/stylexMigration/style-equivalence.config.ts
new file mode 100644
index 00000000000..bfe4986bdbc
--- /dev/null
+++ b/scripts/stylexMigration/style-equivalence.config.ts
@@ -0,0 +1,93 @@
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import react from '@vitejs/plugin-react';
+import type { Plugin } from 'vite';
+
+import type { ProjectConfig } from '../../packages/style-equivalence/src/config';
+import { cssModulesAdapter } from '../../packages/style-equivalence/src/extract/adapters/cssModules';
+import { emotionStaticAdapter } from '../../packages/style-equivalence/src/extract/adapters/emotionStatic';
+import { globalCssAdapter } from '../../packages/style-equivalence/src/extract/adapters/globalCss';
+import { stylexAdapter } from '../../packages/style-equivalence/src/extract/adapters/stylex';
+import type * as LobeUiImportsModule from '../../plugins/vite/lobeUiImports';
+import type * as MarkdownImportModule from '../../plugins/vite/markdownImport';
+import type * as StylexModule from '../../plugins/vite/stylex';
+import { fixtureCalibration } from './styleEquivalenceCalibration';
+import { workspaceExports } from './verification/build/fixtureResolvers';
+
+const fromRevision = async <T>(root: string, file: string) => {
+ const target = existsSync(path.join(root, file))
+ ? path.join(root, file)
+ : path.resolve(import.meta.dirname, '../..', file);
+ return (await import(pathToFileURL(target).href)) as T;
+};
+
+const lenient = (plugin: Plugin): Plugin => ({
+ ...plugin,
+ async resolveId(...args) {
+ try {
+ return await (plugin.resolveId as (...input: unknown[]) => unknown).apply(this, args);
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith('WORKSPACE_EXPORT_UNSUPPORTED'))
+ return undefined;
+ throw error;
+ }
+ },
+});
+
+const config: ProjectConfig = {
+ adapters: [emotionStaticAdapter, stylexAdapter, cssModulesAdapter, globalCssAdapter],
+ aliases: { '@/': 'src/' },
+ calibration: fixtureCalibration,
+ conditions: { themeAttribute: 'data-theme', themes: ['light', 'dark'], widths: [375, 1280] },
+ cxFallback: { name: 'cx', source: '@lobehub/ui' },
+ hostWrapper: 'styleEquivalenceHost.tsx',
+ layoutComponents: ['Flexbox', 'Center', 'Block'],
+ realComponents: {
+ Tabs: {
+ leaf: true,
+ sample: (content) =>
+ `items={[{ key: 'first', label: 'Ag 文本 Text' }, { key: 'second', label: <>${content}</> }]}`,
+ source: '@lobehub/ui',
+ },
+ Text: { source: '@lobehub/ui', tag: { default: 'div', prop: 'as' } },
+ },
+ vite: async (root) => {
+ const { stylexPlugin } = await fromRevision<typeof StylexModule>(
+ root,
+ 'plugins/vite/stylex.ts',
+ );
+ const { lobeUiImports } = await fromRevision<typeof LobeUiImportsModule>(
+ root,
+ 'plugins/vite/lobeUiImports.ts',
+ );
+ const { viteMarkdownImport } = await fromRevision<typeof MarkdownImportModule>(
+ root,
+ 'plugins/vite/markdownImport.ts',
+ );
+ return {
+ alias: [],
+ dedupe: ['react', 'react-dom', '@emotion/react', '@emotion/css', '@stylexjs/stylex'],
+ define: {
+ '__CI__': 'false',
+ '__DEV__': 'false',
+ '__ELECTRON__': 'false',
+ '__MOBILE__': 'false',
+ '__REACT_SCAN__': 'false',
+ '__TEST__': 'false',
+ 'process.env': '{}',
+ },
+ plugins: [
+ lenient(await workspaceExports(root)),
+ stylexPlugin({ overlaySrcDirs: [path.join(root, 'src')] }),
+ react(),
+ ...lobeUiImports(),
+ viteMarkdownImport(),
+ ],
+ tsconfigPaths: true,
+ };
+ },
+};
+
+export default config;
diff --git a/scripts/stylexMigration/styleEquivalenceCalibration.ts b/scripts/stylexMigration/styleEquivalenceCalibration.ts
new file mode 100644
index 00000000000..6ed523083ca
--- /dev/null
+++ b/scripts/stylexMigration/styleEquivalenceCalibration.ts
@@ -0,0 +1,70 @@
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import type {
+ CalibrationAdapter,
+ CalibrationVerdict,
+} from '../../packages/style-equivalence/src/calibration';
+import { resolveBrowserExecutable } from '../../packages/style-equivalence/src/capture/browser';
+import { fixtureIds, getStyleFixture } from './verification/fixtures/fixtureRegistry';
+
+const VERDICTS: Record<string, CalibrationVerdict> = {
+ DIFFERENT: 'difference',
+ EQUAL_IN_SAMPLES: 'equal',
+};
+
+const componentStatus = (output: string) => {
+ for (const line of output.trim().split('\n').reverse()) {
+ if (!line.startsWith('{') || !line.includes('"component"')) continue;
+ try {
+ return (JSON.parse(line) as { component?: { sampledStyleStatus?: string } }).component
+ ?.sampledStyleStatus;
+ } catch {
+ continue;
+ }
+ }
+ return undefined;
+};
+
+export const fixtureCalibration: CalibrationAdapter = {
+ fixturesFor: (files) =>
+ fixtureIds.flatMap((id) => {
+ const file = getStyleFixture(id).component.candidate.source;
+ return files.includes(file) ? [{ file, id }] : [];
+ }),
+ run: ({ base, fixtureId, head, repo, runDir }) =>
+ new Promise((resolve) => {
+ const browser = resolveBrowserExecutable();
+ const child = spawn(
+ 'bun',
+ [
+ path.join(repo, 'scripts/stylexMigration/verification/run.ts'),
+ '--base',
+ base,
+ '--head',
+ head,
+ '--restore-dependencies',
+ '--dependency-network',
+ '--fixture',
+ fixtureId,
+ '--fixture-dependencies',
+ '--output',
+ path.join(runDir, 'calibration'),
+ ...(browser ? ['--browser', browser] : []),
+ ],
+ { cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] },
+ );
+ let output = '';
+ child.stdout.on('data', (chunk) => (output += chunk));
+ child.stderr.on('data', (chunk) => (output += chunk));
+ child.on('error', (error) => resolve({ detail: error.message, verdict: 'inconclusive' }));
+ child.on('exit', (code) => {
+ const status = componentStatus(output);
+ const evidence = output.match(/^Evidence: (.+)$/m)?.[1];
+ resolve({
+ detail: `exit ${code ?? 'signal'} · ${status ?? 'no component result'}${evidence ? ` · ${evidence}` : ''}`,
+ verdict: (status && VERDICTS[status]) || 'inconclusive',
+ });
+ });
+ }),
+};
diff --git a/scripts/stylexMigration/styleEquivalenceHost.tsx b/scripts/stylexMigration/styleEquivalenceHost.tsx
new file mode 100644
index 00000000000..5e927e13e7b
--- /dev/null
+++ b/scripts/stylexMigration/styleEquivalenceHost.tsx
@@ -0,0 +1,14 @@
+import '@lobehub/ui/theme.css';
+import '@lobehub/ui/global.css';
+import '@lobehub/ui/style.css';
+import '@/styles/stylex.css';
+
+import { ConfigProvider } from '@lobehub/ui';
+import * as motion from 'motion/react-m';
+import type { ReactNode } from 'react';
+
+export const Host = ({ children }: { children: ReactNode }) => (
+ <ConfigProvider enableCustomFonts={false} motion={motion}>
+ <div style={{ fontFamily: 'Arial, sans-serif' }}>{children}</div>
+ </ConfigProvider>
+);
diff --git a/scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts b/scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts
index 20a4511cc54..8fcc9a1f504 100644
--- a/scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts
+++ b/scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts
@@ -54,47 +54,62 @@ afterEach(async () => {
});
describe('real Node CLI process exit contract', () => {
- it('returns 2 for a partial plan instead of a successful empty comparison', async () => {
+ it('returns 0 for a collected plan without claiming a gate verdict', async () => {
const { root, base } = await setup();
- expect((await run(root, ['--base', base, '--head', 'HEAD', '--plan-only'])).code).toBe(2);
- expect(await artifact(root)).toMatchObject({
- gateEligible: false,
+ const result = await run(root, ['--base', base, '--head', 'HEAD', '--plan-only']);
+ expect(result.code).toBe(0);
+ const preflight = await artifact(root);
+ expect(preflight).toMatchObject({
mode: 'preflight',
- status: 'NEEDS_REVIEW',
+ reasonCodes: expect.arrayContaining(['PLAN_ONLY']),
});
+ expect(preflight).not.toHaveProperty('gateEligible');
+ expect(preflight).not.toHaveProperty('status');
+ const summary = JSON.parse(result.stdout.trim().split('\n').at(-1)!);
+ expect(summary).not.toHaveProperty('gateEligible');
+ expect(summary).not.toHaveProperty('status');
});
- it('exports isolated source snapshots but stays blocked until dependencies and binding are proven', async () => {
+ it('exports isolated source snapshots and records the unproven dependency and binding gaps', async () => {
const { root, base } = await setup();
- expect((await run(root, ['--base', base, '--head', 'HEAD'])).code).toBe(2);
+ expect((await run(root, ['--base', base, '--head', 'HEAD'])).code).toBe(0);
const result = await artifact(root);
expect(result.snapshots.base.fileCount).toBe(1);
expect(result.snapshots.candidate.dependencyRestore).toBe('NOT_RESTORED');
- expect(result.reasonCodes).toContain('BROWSER_VERIFICATION_NOT_RUN');
+ expect(result.reasonCodes).toEqual(
+ expect.arrayContaining(['BROWSER_VERIFICATION_NOT_RUN', 'DEPENDENCY_SNAPSHOT_NOT_RESTORED']),
+ );
+ expect(await artifact(root, 'source-cleanup.json')).toMatchObject({
+ removed: ['base-source', 'candidate-source'],
+ });
});
- it('uses exit 4 only for a proven identical candidate tree, not a fake PASS', async () => {
+ it('retains source exports only on an explicit debugging request', async () => {
+ const { root, base } = await setup();
+ expect((await run(root, ['--base', base, '--head', 'HEAD', '--keep-sources'])).code).toBe(0);
+ const result = await artifact(root);
+ expect(
+ await readFile(path.join(result.snapshots.base.directory, 'component.ts'), 'utf8'),
+ ).toContain('1');
+ });
+
+ it('records an identical candidate tree as no style impact', async () => {
const { root } = await setup();
- expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD'])).code).toBe(4);
- expect(await artifact(root)).toMatchObject({
- gateEligible: false,
- status: 'NOT_APPLICABLE',
- reasonCodes: ['NO_STYLE_IMPACT'],
- });
+ expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD'])).code).toBe(0);
+ expect(await artifact(root)).toMatchObject({ reasonCodes: ['NO_STYLE_IMPACT'] });
});
- it('keeps even an empty plan non-gating', async () => {
+ it('collects an empty plan', async () => {
const { root } = await setup();
- expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--plan-only'])).code).toBe(2);
+ expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--plan-only'])).code).toBe(0);
});
it('returns 3 and records an error when a revision cannot be resolved', async () => {
const { root } = await setup();
expect((await run(root, ['--base', 'missing-ref', '--head', 'HEAD'])).code).toBe(3);
- expect(await artifact(root, 'error.json')).toMatchObject({
- gateEligible: false,
- status: 'ERROR',
- });
+ const error = await artifact(root, 'error.json');
+ expect(error).toMatchObject({ mode: 'preflight', status: 'ERROR' });
+ expect(error).not.toHaveProperty('gateEligible');
});
it('rejects invalid and unsupported options without a success result', async () => {
diff --git a/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts b/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts
index 7717d01bdc5..5d70fa9696e 100644
--- a/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts
+++ b/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts
@@ -29,13 +29,15 @@ it('retains each failed component and attempts the rest without fabricating comp
// Both exported source entries are genuinely missing. No build/browser mock.
const result = await runFixtureBatch(options);
expect(result.summary).toMatchObject({ planned: 2, completed: 0, errors: 2, equalInSamples: 0 });
- expect(result.errors[0]).toContain('DotsLoading');
- expect(result.errors[1]).toContain('UnreadDot');
- expect(result.fixtureResults).toEqual([]);
+ expect(result.entries.map(({ fixtureId, outcome }) => ({ fixtureId, outcome }))).toEqual([
+ { fixtureId: 'DotsLoading', outcome: 'ERROR' },
+ { fixtureId: 'UnreadDot', outcome: 'ERROR' },
+ ]);
+ expect(result.entries.every((entry) => !entry.summary)).toBe(true);
for (const fixture of options.fixtures) {
const directory = path.join(options.output, 'components', fixture.id);
const error = JSON.parse(await readFile(path.join(directory, 'fixture-error.json'), 'utf8'));
- expect(error).toMatchObject({ fixtureId: fixture.id, gateEligible: false });
+ expect(error).toMatchObject({ fixtureId: fixture.id });
const artifacts = JSON.parse(
await readFile(path.join(directory, 'artifacts.json'), 'utf8'),
) as Array<{ path: string; sha256: string }>;
diff --git a/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts b/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts
index f7a5f113086..058aabdcf7f 100644
--- a/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts
+++ b/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts
@@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import { expect, it } from 'vitest';
-it('accepts compiled markers, custom properties, dynamic styles and nested conditions', () => {
+it('accepts compiled markers, custom properties, dynamic styles, nested conditions, class names and inline styles in any order', () => {
const filename = fileURLToPath(new URL('./sx-arguments.contract.ts', import.meta.url));
const source = `
import * as stylex from '@stylexjs/stylex';
@@ -14,11 +14,12 @@ it('accepts compiled markers, custom properties, dynamic styles and nested condi
dynamic: (color: string) => ({ color, '--operator-color': color }),
});
const marker = stylex.defineMarker();
- sx([styles.root, styles.custom, marker, stylex.defaultMarker()]);
- sx([styles.dynamic('blue'), [true, false, null, undefined, styles.root]]);
+ sx(styles.root, styles.custom, marker, stylex.defaultMarker());
+ sx(styles.dynamic('blue'), [true, false, null, undefined, styles.root]);
sx(styles.root, 'caller-class', { margin: 1 });
- // @ts-expect-error Raw CSS objects are not compiled StyleX arguments.
- sx({ color: 'red' });
+ sx(styles.root, { color: 'red' }, 'caller-class');
+ // @ts-expect-error A number is neither a style, a class name nor an inline style.
+ sx(styles.root, 1);
`;
const options: ts.CompilerOptions = {
esModuleInterop: true,
diff --git a/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts b/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts
index 738a6455f6b..7d3c280e5c4 100644
--- a/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts
+++ b/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts
@@ -22,7 +22,6 @@ const required: ConditionRequirement = {
};
const plan: ConditionProbePlan = {
blocked: [],
- gateEligible: false,
gaps: [],
mode: 'same-target-condition-partitions',
scheduling: 'round-robin-trigger-state-direction',
@@ -83,7 +82,6 @@ describe('condition keys use measured per-node evidence', () => {
);
expect(result.keys.map((key) => key.status)).toEqual(['OBSERVED', 'MISSING_PROBE']);
expect(result.summary.missing).toBe(1);
- expect(result.gateEligible).toBe(false);
});
it('does not use an unstable A/A capture or an evidence-free record', () => {
expect(summarizeConditionCoverage([plan], [sample], []).keys[0].status).toBe('PROBE_UNSTABLE');
diff --git a/scripts/stylexMigration/verification/analysis/conditionCoverage.ts b/scripts/stylexMigration/verification/analysis/conditionCoverage.ts
index 0167e71d668..fe0182361f2 100644
--- a/scripts/stylexMigration/verification/analysis/conditionCoverage.ts
+++ b/scripts/stylexMigration/verification/analysis/conditionCoverage.ts
@@ -9,8 +9,7 @@ const matchesCell = (id: string, width: number, planned: number) => {
return width > lower && width < upper;
};
-/** Per side/rule/node/partition/direction/operation records, still not certified
- * gate witnesses. In particular a rule hit in one cell cannot close another. */
+// A rule hit in one side/rule/node/partition/direction/operation cell cannot close another.
export const summarizeConditionCoverage = (
plans: ConditionProbePlan[],
evidence: RuleProbeEvidence[],
@@ -79,7 +78,6 @@ export const summarizeConditionCoverage = (
}),
);
return {
- gateEligible: false as const,
keys,
limitations: [...new Set(plans.flatMap((plan) => plan.limitations))],
summary: {
diff --git a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts
index edca0a4c77c..d737fe85706 100644
--- a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts
+++ b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts
@@ -111,7 +111,6 @@ describe('source-bound condition partition planning', () => {
).toBe(true);
expect(plan.reused).toBeGreaterThan(0);
expect(new Set(plan.requirements.map((key) => key.id)).size).toBe(plan.requirements.length);
- expect(plan.gateEligible).toBe(false);
});
it('does not cross unrelated media/container paths, but keeps their intersection on a shared target', () => {
const media = makeSeed({ conditions: [{ kind: 'CSSMediaRule', text: '(max-width:700px)' }] });
diff --git a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts
index 97a6f4926c8..cfad4ed1c0d 100644
--- a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts
+++ b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts
@@ -1,6 +1,10 @@
+import type { WidthCondition } from '../../../../packages/style-equivalence/src/capture/conditionPartitions';
+import {
+ matchesWidth,
+ partitionWidthCells,
+} from '../../../../packages/style-equivalence/src/capture/conditionPartitions';
+import type { CaptureRoot } from '../browser/surfaces';
import type { FixtureProbe } from '../pipeline/probePlanner';
-import type { WidthCondition } from './conditionPartitions';
-import { matchesWidth, partitionWidthCells } from './conditionPartitions';
import type { RuleObservation, RuleWitnessPlan } from './ruleWitnesses';
export interface ConditionSeed {
@@ -33,9 +37,8 @@ export interface ConditionRequirement {
export const readConditionHostInPage = (selectors: {
'hover'?: string;
'focus-visible'?: string;
+ 'roots'?: CaptureRoot[];
}) => {
- const root = document.querySelector('[data-case-root]');
- if (!root) throw new Error('CONDITION_ROOT_MISSING');
const keys = new Map<Element, string>();
const walk = (element: Element, key: string) => {
keys.set(element, key);
@@ -43,16 +46,20 @@ export const readConditionHostInPage = (selectors: {
.filter((child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName))
.forEach((child, index) => walk(child, `${key}.${index}`));
};
- walk(root, 'root');
+ for (const surface of selectors.roots ?? [{ selector: '[data-case-root]', keyPrefix: '' }]) {
+ const root = document.querySelector(surface.selector);
+ if (!root) throw new Error('CONDITION_ROOT_MISSING');
+ walk(root, `${surface.keyPrefix}root`);
+ }
const host = document.querySelector('[data-component-mount]')?.firstElementChild;
if (!host || !keys.has(host)) throw new Error('CONTROLLED_CONTAINER_MISSING');
return {
hostKey: keys.get(host)!,
hostWritingMode: getComputedStyle(host).writingMode,
legacyTriggerKeys: Object.fromEntries(
- Object.entries(selectors).map(([state, selector]) => [
+ (['hover', 'focus-visible'] as const).map((state) => [
state,
- selector ? keys.get(document.querySelector(selector)!) : undefined,
+ selectors[state] ? keys.get(document.querySelector(selectors[state])!) : undefined,
]),
),
};
@@ -266,7 +273,6 @@ export const planConditionProbes = (options: {
const scheduled = ordered.slice(0, Math.max(0, options.remaining));
return {
blocked,
- gateEligible: false as const,
gaps: [
...new Set([
...blocked.map((entry) => entry.reason),
diff --git a/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts b/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts
index f06c1f65012..4e68f6069c8 100644
--- a/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts
+++ b/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts
@@ -76,7 +76,6 @@ it('reports an untouched second interaction target instead of closing the rule a
);
expect(result.rules[0].status).toBe('PARTIAL_ACTIVATION');
expect(result.rules[0].missingActivationKeys).toEqual(['root.1']);
- expect(result.gateEligible).toBe(false);
});
it('keeps unmounted source branches in the denominator', () => {
diff --git a/scripts/stylexMigration/verification/analysis/ruleCoverage.ts b/scripts/stylexMigration/verification/analysis/ruleCoverage.ts
index b9fecfbbd73..bc4c876b52d 100644
--- a/scripts/stylexMigration/verification/analysis/ruleCoverage.ts
+++ b/scripts/stylexMigration/verification/analysis/ruleCoverage.ts
@@ -8,7 +8,6 @@ export interface RuleProbeEvidence {
variant: string;
}
-/** Diagnostic activation coverage, never a substitute for all required gate keys. */
export const summarizeRuleCoverage = (
plans: Array<{ plan: RuleWitnessPlan; side: 'base' | 'candidate'; variant: string }>,
evidence: RuleProbeEvidence[],
@@ -92,7 +91,6 @@ export const summarizeRuleCoverage = (
variants: group.map((rule) => rule.variant),
}));
return {
- gateEligible: false as const,
gaps,
mode: 'diagnostic-source-slot-cssom-activation' as const,
rules,
diff --git a/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts b/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts
index 1c5a84e117f..e754531ebca 100644
--- a/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts
+++ b/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts
@@ -1,9 +1,10 @@
import type { Page } from '@playwright/test';
import { z } from 'zod';
+import { parseWidthCondition } from '../../../../packages/style-equivalence/src/capture/conditionPartitions';
import type { collectRulesInPage } from '../browser/ruleInventory';
import type { RuntimeCompositions } from '../browser/runtimeCompositions';
-import { parseWidthCondition } from './conditionPartitions';
+import type { CaptureRoot } from '../browser/surfaces';
import { analyzeSelector } from './selectorAnalysis';
import type { StyleBindingPlan } from './styleBindings';
@@ -153,11 +154,10 @@ export type RuleWitnessPlan = ReturnType<typeof planRuleWitnesses>;
export const collectRuleWitnessesInPage = (input: {
nonce: string;
rules: RuleWitnessPlan['rules'];
+ roots?: CaptureRoot[];
}) => {
if (!/^[a-f\d]{16}$/.test(input.nonce)) throw new Error('INVALID_WITNESS_NAMESPACE');
if (input.rules.length > 1000) throw new Error('RULE_WITNESS_BUDGET_EXCEEDED');
- const root = document.querySelector('[data-case-root]');
- if (!root) throw new Error('RULE_WITNESS_ROOT_MISSING');
const keys = new Map<Element, string>();
const walk = (element: Element, key: string) => {
keys.set(element, key);
@@ -165,7 +165,11 @@ export const collectRuleWitnessesInPage = (input: {
.filter((child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName))
.forEach((child, index) => walk(child, `${key}.${index}`));
};
- walk(root, 'root');
+ for (const surface of input.roots ?? [{ selector: '[data-case-root]', keyPrefix: '' }]) {
+ const root = document.querySelector(surface.selector);
+ if (!root) throw new Error('RULE_WITNESS_ROOT_MISSING');
+ walk(root, `${surface.keyPrefix}root`);
+ }
const absoluteSelector = (element: Element) => {
const segments: string[] = [];
for (
@@ -214,12 +218,12 @@ export const collectRuleWitnessesInPage = (input: {
const triggers =
rule.states.length === 1
? [...document.querySelectorAll(rule.states[0].selector)].filter((element) =>
- root.contains(element),
+ keys.has(element),
)
: [];
if (triggers.length > 512) throw new Error('RULE_TRIGGER_BUDGET_EXCEEDED');
const targets = [...document.querySelectorAll(rule.targetSelector)]
- .filter((element) => root.contains(element))
+ .filter((element) => keys.has(element))
.map((element) => {
const computed = getComputedStyle(element, rule.pseudo);
const containers: Array<{
diff --git a/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts b/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts
index e4264258fc1..30dd1e55aa1 100644
--- a/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts
+++ b/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts
@@ -75,7 +75,6 @@ describe('bounded activation-gap supplementation', () => {
expect(result.scheduled).toHaveLength(1);
expect(result.scheduled[0].interaction).toEqual({ key: 'root.1', state: 'hover', tag: 'TR' });
expect(result.requirements[0].key).toBe('root.1');
- expect(result.gateEligible).toBe(false);
});
it('deduplicates a paired B/M gap but never drops overflow requirements', () => {
const result = planSupplementalProbes({
diff --git a/scripts/stylexMigration/verification/analysis/supplementalProbes.ts b/scripts/stylexMigration/verification/analysis/supplementalProbes.ts
index b5adf95146e..ee8915d3cf9 100644
--- a/scripts/stylexMigration/verification/analysis/supplementalProbes.ts
+++ b/scripts/stylexMigration/verification/analysis/supplementalProbes.ts
@@ -74,6 +74,5 @@ export const planSupplementalProbes = (options: {
requirements,
scheduled,
blocked: planned.slice(scheduled.length),
- gateEligible: false as const,
};
};
diff --git a/scripts/stylexMigration/verification/browser/capture.ts b/scripts/stylexMigration/verification/browser/capture.ts
index 6fc3dc6c176..abb0cf81920 100644
--- a/scripts/stylexMigration/verification/browser/capture.ts
+++ b/scripts/stylexMigration/verification/browser/capture.ts
@@ -1,12 +1,15 @@
import type { CDPSession, Page } from '@playwright/test';
+import type { StyleSnapshot } from '../../../../packages/style-equivalence/src/capture/snapshot';
+import { captureInPage } from '../../../../packages/style-equivalence/src/capture/snapshot';
import { createFastCapture } from './fastCapture';
-import type { StyleSnapshot } from './snapshot';
-import { captureInPage } from './snapshot';
+import type { CaptureRoot, CaptureScope, CaptureSurface } from './surfaces';
+import { resolveCaptureSurfacesInPage } from './surfaces';
export interface ComponentSnapshot {
attributes: Array<{ attributes: Array<[string, string]>; key: string; text: string }>;
backend: 'hybrid' | 'strict';
+ scope?: CaptureScope;
tree: StyleSnapshot;
}
@@ -19,14 +22,17 @@ export interface CaptureTiming {
total?: number;
}
-export const captureComponent = async (
+const captureRoot = async (
page: Page,
cdp: CDPSession,
timing?: CaptureTiming,
+ root: CaptureRoot = { keyPrefix: '', selector: '[data-case-root]' },
): Promise<ComponentSnapshot> => {
const started = performance.now();
let phaseStarted = started;
+ const scope = { ...root, originSelector: '[data-case-root]' };
const { captureMetadata: metadata, ...prepared } = await page.evaluate(captureInPage, {
+ ...scope,
animationTime: 0,
collectMetadata: true,
});
@@ -34,7 +40,7 @@ export const captureComponent = async (
if (timing) timing.metadata = performance.now() - phaseStarted;
phaseStarted = performance.now();
if (metadata.standard.join('\0') !== metadata.rootProperties.toSorted().join('\0')) {
- const tree = await page.evaluate(captureInPage, {});
+ const tree = await page.evaluate(captureInPage, scope);
if (timing) {
timing.standard = performance.now() - phaseStarted;
timing.total = performance.now() - started;
@@ -49,6 +55,7 @@ export const captureComponent = async (
properties: metadata.rootProperties,
prepared,
nodeStyles: metadata.custom.length > 0,
+ scope,
});
const tree = await capture(0, timing ? (timing.fast = {}) : undefined);
if (timing) timing.standard = performance.now() - phaseStarted;
@@ -57,3 +64,41 @@ export const captureComponent = async (
if (timing) timing.total = performance.now() - started;
return { attributes: metadata.attributes, backend: 'hybrid', tree };
};
+
+export const captureComponent = async (
+ page: Page,
+ cdp: CDPSession,
+ timing?: CaptureTiming,
+ options?: { surfaces: CaptureSurface[]; variant?: string },
+): Promise<ComponentSnapshot> => {
+ if (!options) return captureRoot(page, cdp, timing);
+ const started = performance.now();
+ const scope = await page.evaluate(resolveCaptureSurfacesInPage, options);
+ if (scope.roots.length === 1) return { ...(await captureRoot(page, cdp, timing)), scope };
+ const snapshots: ComponentSnapshot[] = [];
+ // CDP marker inventories are document-local and must not race each other.
+ for (const root of scope.roots) snapshots.push(await captureRoot(page, cdp, undefined, root));
+ const tree: StyleSnapshot = {
+ animations: [],
+ durationMs: performance.now() - started,
+ nodes: [],
+ propertyReads: 0,
+ styles: [],
+ };
+ for (const snapshot of snapshots) {
+ const offset = tree.styles.length;
+ tree.nodes.push(
+ ...snapshot.tree.nodes.map((node) => ({ ...node, style: node.style + offset })),
+ );
+ tree.styles.push(...snapshot.tree.styles);
+ tree.animations.push(...snapshot.tree.animations);
+ tree.propertyReads += snapshot.tree.propertyReads;
+ }
+ if (timing) timing.total = performance.now() - started;
+ return {
+ attributes: snapshots.flatMap((snapshot) => snapshot.attributes),
+ backend: snapshots.every((snapshot) => snapshot.backend === 'hybrid') ? 'hybrid' : 'strict',
+ scope,
+ tree,
+ };
+};
diff --git a/scripts/stylexMigration/verification/browser/compareSnapshots.ts b/scripts/stylexMigration/verification/browser/compareSnapshots.ts
index 302d4b566a4..50b112b4a9b 100644
--- a/scripts/stylexMigration/verification/browser/compareSnapshots.ts
+++ b/scripts/stylexMigration/verification/browser/compareSnapshots.ts
@@ -1,5 +1,5 @@
+import { compareSnapshots } from '../../../../packages/style-equivalence/src/capture/snapshot';
import type { ComponentSnapshot } from './capture';
-import { compareSnapshots } from './snapshot';
export const compareComponents = (before: ComponentSnapshot, after: ComponentSnapshot) => {
const raw = compareSnapshots(before.tree, after.tree);
diff --git a/scripts/stylexMigration/verification/browser/fastCapture.ts b/scripts/stylexMigration/verification/browser/fastCapture.ts
index dce32d0e7fb..9b17c096019 100644
--- a/scripts/stylexMigration/verification/browser/fastCapture.ts
+++ b/scripts/stylexMigration/verification/browser/fastCapture.ts
@@ -1,7 +1,7 @@
import type { CDPSession, Page } from '@playwright/test';
-import type { StyleSnapshot } from './snapshot';
-import { captureInPage } from './snapshot';
+import type { StyleSnapshot } from '../../../../packages/style-equivalence/src/capture/snapshot';
+import { captureInPage } from '../../../../packages/style-equivalence/src/capture/snapshot';
/** Blink batches standard computed properties and interns their values in DOMSnapshot.
* Custom properties are not accepted by this CDP method. Resolved consumers still are.
@@ -10,7 +10,12 @@ import { captureInPage } from './snapshot';
export const createFastCapture = async (
page: Page,
cdp: CDPSession,
- options?: { properties: string[]; prepared: StyleSnapshot; nodeStyles?: boolean },
+ options?: {
+ properties: string[];
+ prepared: StyleSnapshot;
+ nodeStyles?: boolean;
+ scope?: { selector: string; keyPrefix: string; originSelector: string };
+ },
) => {
const properties =
options?.properties ??
@@ -37,6 +42,7 @@ export const createFastCapture = async (
const metadata =
options?.prepared ??
(await page.evaluate(captureInPage, {
+ ...options?.scope,
animationTime,
properties: ['animation-name'],
}));
@@ -57,7 +63,12 @@ export const createFastCapture = async (
const attributes = nodes.attributes?.[index] ?? [];
for (let item = 0; item < attributes.length; item += 2) {
if (snapshot.strings[attributes[item]] !== 'data-experiment-node') continue;
- const key = normalKeys[Number(snapshot.strings[attributes[item + 1]])];
+ const marker = snapshot.strings[attributes[item + 1]];
+ const prefix = options?.scope?.keyPrefix ?? '';
+ if (!marker.startsWith(prefix)) continue;
+ const ordinal = marker.slice(prefix.length);
+ if (!/^\d+$/.test(ordinal)) continue;
+ const key = normalKeys[Number(ordinal)];
if (key) keys.set(index, key);
}
}
@@ -90,6 +101,7 @@ export const createFastCapture = async (
let fallbackReads = 0;
if (missing.length) {
const fallback = await page.evaluate(captureInPage, {
+ ...options?.scope,
animationTime,
properties,
styleKeys: missing,
diff --git a/scripts/stylexMigration/verification/browser/probes.ts b/scripts/stylexMigration/verification/browser/probes.ts
index 9c7d42728b7..46f73c826f6 100644
--- a/scripts/stylexMigration/verification/browser/probes.ts
+++ b/scripts/stylexMigration/verification/browser/probes.ts
@@ -1,8 +1,16 @@
import type { Page } from '@playwright/test';
+import type {
+ RuleInventory,
+ StyleDifference,
+ StyleSnapshot,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
+import {
+ captureInPage,
+ compareSnapshots,
+ inventoryInPage,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
import { createFastCapture } from './fastCapture';
-import type { RuleInventory, StyleDifference, StyleSnapshot } from './snapshot';
-import { captureInPage, compareSnapshots, inventoryInPage } from './snapshot';
import { createWitness } from './witness';
export interface Probe {
diff --git a/scripts/stylexMigration/verification/browser/screenshotEvidence.test.ts b/scripts/stylexMigration/verification/browser/screenshotEvidence.test.ts
new file mode 100644
index 00000000000..9247c5dbc33
--- /dev/null
+++ b/scripts/stylexMigration/verification/browser/screenshotEvidence.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment node
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { chromium } from '@playwright/test';
+import { expect, it } from 'vitest';
+
+import { captureScreenshotEvidence } from './screenshotEvidence';
+
+it('distinguishes stable equal pixels, a real repaint, and a noisy A/A control', async () => {
+ const output = await mkdtemp(path.join(tmpdir(), 'stylex-pixel-test-'));
+ const browser = await chromium.launch({ headless: true });
+ try {
+ const pages = await Promise.all(
+ Array.from({ length: 3 }, () => browser.newPage({ viewport: { width: 100, height: 100 } })),
+ );
+ await Promise.all(
+ pages.map((page) =>
+ page.setContent(
+ '<style>body{margin:0}div{width:20px;height:20px;background:red}</style><div></div>',
+ ),
+ ),
+ );
+ const equal = await captureScreenshotEvidence(pages, output, 'equal');
+ expect(equal.aaStable).toBe(true);
+ expect(equal.candidate.changedPixels).toBe(0);
+ await pages[2].locator('div').evaluate((node) => {
+ node.style.background = 'blue';
+ });
+ const changed = await captureScreenshotEvidence(pages, output, 'changed');
+ expect(changed.aaStable).toBe(true);
+ expect(changed.candidate.changedPixels).toBe(400);
+ expect(await readFile(path.join(output, 'changed-diff.png'))).not.toHaveLength(0);
+ await pages[1].locator('div').evaluate((node) => {
+ node.style.background = 'green';
+ });
+ expect((await captureScreenshotEvidence(pages, output, 'noisy')).aaStable).toBe(false);
+ } finally {
+ await browser.close();
+ await rm(output, { force: true, recursive: true });
+ }
+});
diff --git a/scripts/stylexMigration/verification/browser/screenshotEvidence.ts b/scripts/stylexMigration/verification/browser/screenshotEvidence.ts
new file mode 100644
index 00000000000..9b12d053145
--- /dev/null
+++ b/scripts/stylexMigration/verification/browser/screenshotEvidence.ts
@@ -0,0 +1,98 @@
+import { writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Page } from '@playwright/test';
+
+/** Detached browser canvases decode PNGs; no image packages or network needed. */
+export const compareImagesInPage = async (encoded: string[]) => {
+ const images = await Promise.all(
+ encoded.map(async (value) => {
+ const bytes = Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/png' }));
+ const canvas = document.createElement('canvas');
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ const context = canvas.getContext('2d')!;
+ context.drawImage(bitmap, 0, 0);
+ bitmap.close();
+ return { canvas, pixels: context.getImageData(0, 0, canvas.width, canvas.height).data };
+ }),
+ );
+ if (images.length !== 3) throw new Error('SCREENSHOT_CONTROL_REQUIRES_THREE_IMAGES');
+ const compare = (left: (typeof images)[number], right: (typeof images)[number]) => {
+ if (left.canvas.width !== right.canvas.width || left.canvas.height !== right.canvas.height)
+ throw new Error('SCREENSHOT_DIMENSIONS_CHANGED');
+ let changed = 0;
+ let maxChannelDelta = 0;
+ const mask = new Uint8ClampedArray(left.pixels.length);
+ for (let offset = 0; offset < left.pixels.length; offset += 4) {
+ let different = false;
+ for (let channel = 0; channel < 4; channel++) {
+ const delta = Math.abs(left.pixels[offset + channel] - right.pixels[offset + channel]);
+ maxChannelDelta = Math.max(maxChannelDelta, delta);
+ different ||= delta !== 0;
+ }
+ if (different) changed++;
+ mask.set(different ? [255, 0, 128, 255] : [255, 255, 255, 255], offset);
+ }
+ const context = right.canvas.getContext('2d')!;
+ context.putImageData(new ImageData(mask, right.canvas.width, right.canvas.height), 0, 0);
+ return {
+ changedPixels: changed,
+ maxChannelDelta,
+ pixels: left.pixels.length / 4,
+ heatmap: right.canvas.toDataURL('image/png').split(',')[1],
+ };
+ };
+ const control = compare(images[0], images[1]);
+ const candidate = compare(images[0], images[2]);
+ return {
+ candidate,
+ control: { changedPixels: control.changedPixels, maxChannelDelta: control.maxChannelDelta },
+ height: images[0].canvas.height,
+ width: images[0].canvas.width,
+ };
+};
+
+/** Viewport-only diagnostic. Pixel equality never overrides a computed-style failure. */
+export const captureScreenshotEvidence = async (pages: Page[], output: string, name: string) => {
+ if (pages.length !== 3 || !/^[a-z\d-]+$/i.test(name))
+ throw new Error('INVALID_SCREENSHOT_REQUEST');
+ for (const page of pages) {
+ const viewport = page.viewportSize();
+ if (!viewport || viewport.width * viewport.height > 4_000_000)
+ throw new Error('SCREENSHOT_PIXEL_BUDGET_EXCEEDED');
+ }
+ const images = await Promise.all(
+ pages.map((page) =>
+ page.screenshot({
+ animations: 'allow',
+ caret: 'hide',
+ fullPage: false,
+ type: 'png',
+ }),
+ ),
+ );
+ const comparison = await pages[0].evaluate(
+ compareImagesInPage,
+ images.map((image) => image.toString('base64')),
+ );
+ const files = ['base', 'aa', 'candidate'].map((side) => `${name}-${side}.png`);
+ await Promise.all(
+ images.map((image, index) => writeFile(path.join(output, files[index]), image, { flag: 'wx' })),
+ );
+ const heatmap = `${name}-diff.png`;
+ await writeFile(path.join(output, heatmap), Buffer.from(comparison.candidate.heatmap, 'base64'), {
+ flag: 'wx',
+ });
+ const { heatmap: _, ...candidate } = comparison.candidate;
+ return {
+ aaStable: comparison.control.changedPixels === 0,
+ artifactFiles: [...files, heatmap],
+ candidate,
+ control: comparison.control,
+ height: comparison.height,
+ scope: 'current-viewport-only' as const,
+ width: comparison.width,
+ };
+};
diff --git a/scripts/stylexMigration/verification/browser/screenshotPlan.test.ts b/scripts/stylexMigration/verification/browser/screenshotPlan.test.ts
new file mode 100644
index 00000000000..ccbddbdd03d
--- /dev/null
+++ b/scripts/stylexMigration/verification/browser/screenshotPlan.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldCaptureScreenshot } from './screenshotPlan';
+
+describe('bounded per-variant screenshot fallback', () => {
+ it('does not spend every screenshot on raw class-name differences in the first variant', () => {
+ expect(shouldCaptureScreenshot(['first', 'last'], ['first'], 'first', false)).toBe(false);
+ expect(shouldCaptureScreenshot(['first', 'last'], ['first'], 'last', false)).toBe(true);
+ });
+
+ it('reserves room for later variants even when an early variant has real differences', () => {
+ const variants = Array.from({ length: 18 }, (_, index) => String(index));
+ const captured = Array.from({ length: 7 }, () => '0');
+ expect(shouldCaptureScreenshot(variants, captured, '0', true)).toBe(false);
+ for (const variant of variants.slice(1)) {
+ expect(shouldCaptureScreenshot(variants, captured, variant, false)).toBe(true);
+ captured.push(variant);
+ }
+ expect(captured).toHaveLength(24);
+ expect(shouldCaptureScreenshot(variants, captured, 'new', true)).toBe(false);
+ });
+});
diff --git a/scripts/stylexMigration/verification/browser/screenshotPlan.ts b/scripts/stylexMigration/verification/browser/screenshotPlan.ts
new file mode 100644
index 00000000000..afb6a527cdb
--- /dev/null
+++ b/scripts/stylexMigration/verification/browser/screenshotPlan.ts
@@ -0,0 +1,15 @@
+export const screenshotCaptureLimit = 24;
+
+/** Keep a bounded pixel fallback, reserving one capture for each later variant. */
+export const shouldCaptureScreenshot = (
+ variants: string[],
+ capturedVariants: string[],
+ variant: string,
+ hasDifferences: boolean,
+) => {
+ const limit = screenshotCaptureLimit;
+ if (capturedVariants.length >= limit) return false;
+ if (!capturedVariants.includes(variant)) return true;
+ const reserved = variants.filter((id) => !capturedVariants.includes(id)).length;
+ return hasDifferences && capturedVariants.length + reserved < limit;
+};
diff --git a/scripts/stylexMigration/verification/browser/surfaces.ts b/scripts/stylexMigration/verification/browser/surfaces.ts
new file mode 100644
index 00000000000..e4bd5fffc6f
--- /dev/null
+++ b/scripts/stylexMigration/verification/browser/surfaces.ts
@@ -0,0 +1,67 @@
+export interface CaptureSurface {
+ id: string;
+ kind: 'component' | 'host' | 'portal';
+ selector: string;
+ variants?: string[];
+}
+
+export interface CaptureRoot {
+ keyPrefix: string;
+ selector: string;
+}
+
+export interface CaptureScope {
+ roots: CaptureRoot[];
+ surfaces: Array<{ id: string; kind: CaptureSurface['kind']; matches: number }>;
+}
+
+/** Serializable browser function. Only declared portal roots extend the scope. */
+export const resolveCaptureSurfacesInPage = (input: {
+ surfaces: CaptureSurface[];
+ variant?: string;
+}): CaptureScope => {
+ const root = document.querySelector('[data-case-root]');
+ if (!root) throw new Error('CAPTURE_ROOT_MISSING');
+ const marker = 'data-stylex-verification-surface';
+ document.querySelectorAll(`[${marker}]`).forEach((element) => element.removeAttribute(marker));
+ const external: Array<{ element: Element; keyPrefix: string }> = [];
+ const surfaces = [];
+ for (const surface of input.surfaces) {
+ if (surface.variants && !surface.variants.includes(input.variant ?? '')) continue;
+ let matches: Element[];
+ try {
+ matches = [...document.querySelectorAll(surface.selector)];
+ } catch {
+ throw new Error(`SURFACE_SELECTOR_INVALID:${surface.id}`);
+ }
+ if (!matches.length) throw new Error(`SURFACE_NOT_MOUNTED:${surface.id}`);
+ surfaces.push({ id: surface.id, kind: surface.kind, matches: matches.length });
+ for (const [index, element] of matches.entries()) {
+ if (root.contains(element)) continue;
+ if (surface.kind !== 'portal') throw new Error(`SURFACE_OUTSIDE_ROOT:${surface.id}`);
+ if (element.contains(root)) throw new Error(`SURFACE_CONTAINS_ROOT:${surface.id}`);
+ external.push({ element, keyPrefix: `surface:${encodeURIComponent(surface.id)}:${index}/` });
+ }
+ }
+ // Nested/overlapping declarations are captured once, from their outer root.
+ const unique = external.filter(
+ (entry, index) =>
+ !external.some(
+ (other, otherIndex) =>
+ otherIndex !== index &&
+ other.element.contains(entry.element) &&
+ (other.element !== entry.element || otherIndex < index),
+ ),
+ );
+ if (unique.length > 32) throw new Error('CAPTURE_SURFACE_BUDGET_EXCEEDED');
+ return {
+ roots: [
+ { keyPrefix: '', selector: '[data-case-root]' },
+ ...unique.map(({ element, keyPrefix }) => {
+ element.setAttribute(marker, keyPrefix);
+ return { keyPrefix, selector: `[${marker}="${keyPrefix}"]` };
+ }),
+ ],
+ surfaces,
+ };
+};
diff --git a/scripts/stylexMigration/verification/browser/witness.ts b/scripts/stylexMigration/verification/browser/witness.ts
index c8c8637a0f6..1b24d6614e8 100644
--- a/scripts/stylexMigration/verification/browser/witness.ts
+++ b/scripts/stylexMigration/verification/browser/witness.ts
@@ -1,6 +1,6 @@
import type { Page } from '@playwright/test';
-import type { RuleInventory } from './snapshot';
+import type { RuleInventory } from '../../../../packages/style-equivalence/src/capture/snapshot';
/** Independent marker rules prove that a discovered branch was actually activated.
* These internal-only custom properties are excluded from the product snapshot.
diff --git a/scripts/stylexMigration/verification/build/buildFixtures.ts b/scripts/stylexMigration/verification/build/buildFixtures.ts
index 130ede53311..b342a9604b1 100644
--- a/scripts/stylexMigration/verification/build/buildFixtures.ts
+++ b/scripts/stylexMigration/verification/build/buildFixtures.ts
@@ -1,12 +1,12 @@
import { readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
-import { compileFixtureTools } from './compileFixtureTools';
-import { prepareFixtureHost } from '../fixtures/host';
+import { bindingObserverExport, prepareStyleBindings } from '../analysis/styleBindings';
import type { StyleFixture } from '../fixtures/fixtureRegistry';
-import { runIsolatedProcess } from './isolatedProcess';
+import { prepareFixtureHost } from '../fixtures/host';
import { writeJson } from '../reporting/report';
-import { bindingObserverExport, prepareStyleBindings } from '../analysis/styleBindings';
+import { compileFixtureTools } from './compileFixtureTools';
+import { runIsolatedProcess } from './isolatedProcess';
export const buildComponentFixture = async (
root: string,
@@ -26,6 +26,12 @@ export const buildComponentFixture = async (
...bindingPlan,
observerExport: bindingObserverExport(bindingPlan),
});
+ await writeJson(tools, 'fixture-boundaries.json', fixture.moduleBoundaries);
+ await writeFile(
+ path.join(tools, 'fixtureResolvers.ts'),
+ await readFile(path.join(sourceDirectory, 'build/fixtureResolvers.ts')),
+ { flag: 'wx' },
+ );
await writeFile(
path.join(tools, 'fixtureBuildWorker.ts'),
await readFile(path.join(sourceDirectory, 'build/fixtureBuildWorker.ts')),
@@ -55,6 +61,9 @@ export const buildComponentFixture = async (
durationMs: performance.now() - started,
fixtureHashes,
fixtureId: fixture.id,
+ dataBoundaries: JSON.parse(
+ await readFile(path.join(tools, 'fixture-boundary-hits.json'), 'utf8'),
+ ) as string[],
modules: JSON.parse(await readFile(path.join(tools, 'build-modules.json'), 'utf8')) as string[],
sandbox: 'macos-sandbox-exec',
toolchain: { node: process.version, compiler },
diff --git a/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts b/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts
index 44abd1e939e..f5e9cdd97d0 100644
--- a/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts
+++ b/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts
@@ -7,6 +7,8 @@ import react from '@vitejs/plugin-react';
import type { Plugin } from 'vite';
import { build } from 'vite';
+import { fixtureDataBoundary, type ModuleBoundary, workspaceExports } from './fixtureResolvers';
+
/** Bundled into the source snapshot, then executed as a separate Node process. */
const main = async () => {
const root = await realpath(process.cwd());
@@ -29,6 +31,17 @@ const main = async () => {
pathToFileURL(path.join(tools, 'compiler/lobeUiImports.mjs')).href
);
const modules = new Set<string>();
+ const boundaryHits = new Set<string>();
+ const boundaries = JSON.parse(
+ await readFile(path.join(tools, 'fixture-boundaries.json'), 'utf8'),
+ ) as ModuleBoundary[];
+ const dataBoundary = fixtureDataBoundary(
+ root,
+ path.join(tools, 'host'),
+ boundaries,
+ boundaryHits,
+ );
+ const workspaceResolver = await workspaceExports(root);
const observer = JSON.parse(await readFile(path.join(tools, 'style-bindings.json'), 'utf8')) as {
composition: { edits: Array<{ start: number; end: number; text: string }> };
observerExport: string;
@@ -92,6 +105,8 @@ const main = async () => {
logLevel: 'error',
plugins: [
audit,
+ dataBoundary,
+ workspaceResolver,
bindingObserver,
stylexPlugin({ overlaySrcDirs: [path.join(root, 'src')] }),
react(),
@@ -117,6 +132,11 @@ const main = async () => {
root: path.join(tools, 'host'),
});
if (!modules.has(source)) throw new Error('COMPONENT_NOT_IN_BUILD_GRAPH');
+ await writeFile(
+ path.join(tools, 'fixture-boundary-hits.json'),
+ JSON.stringify([...boundaryHits].sort()),
+ { flag: 'wx' },
+ );
await writeFile(path.join(tools, 'build-modules.json'), JSON.stringify([...modules].sort()), {
flag: 'wx',
});
diff --git a/scripts/stylexMigration/verification/build/fixtureResolvers.test.ts b/scripts/stylexMigration/verification/build/fixtureResolvers.test.ts
new file mode 100644
index 00000000000..6df8bba93e5
--- /dev/null
+++ b/scripts/stylexMigration/verification/build/fixtureResolvers.test.ts
@@ -0,0 +1,110 @@
+import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { fixtureDataBoundary, workspaceExports } from './fixtureResolvers';
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true })));
+});
+const setup = async () => {
+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'stylex-resolver-')));
+ roots.push(root);
+ await mkdir(path.join(root, 'packages/example'), { recursive: true });
+ await mkdir(path.join(root, 'host'));
+ await writeFile(path.join(root, 'host/data.ts'), 'export const value = 1;');
+ await writeFile(path.join(root, 'packages/example/index.ts'), 'export const value = 2;');
+ await writeFile(
+ path.join(root, 'packages/example/package.json'),
+ JSON.stringify({
+ name: '@example/pkg',
+ exports: {
+ '.': './index.ts',
+ './conditional': { import: './index.ts' },
+ './escape': './../../outside.ts',
+ },
+ }),
+ );
+ await writeFile(path.join(root, 'outside.ts'), '');
+ return root;
+};
+
+// Vite accepts an object hook or a function; these plugins deliberately use functions.
+const resolver = (plugin: Awaited<ReturnType<typeof workspaceExports>>) => {
+ if (typeof plugin.resolveId !== 'function') throw new Error('EXPECTED_RESOLVE_FUNCTION');
+ const hook = plugin.resolveId;
+ return (id: string, importer: string | undefined, _options: object) =>
+ hook.call({} as never, id, importer, { isEntry: false });
+};
+
+describe('snapshot fixture resolvers', () => {
+ it('replaces only the declared edge and records it', async () => {
+ const root = await setup();
+ const hits = new Set<string>();
+ const resolve = resolver(
+ fixtureDataBoundary(
+ root,
+ path.join(root, 'host'),
+ [
+ {
+ importer: 'src/component.tsx',
+ source: '@/store/test',
+ replacement: 'data.ts',
+ },
+ ],
+ hits,
+ ),
+ );
+ expect(await resolve('@/store/test', path.join(root, 'src/other.tsx'), {})).toBeUndefined();
+ expect(await resolve('@/store/test', path.join(root, 'src/component.tsx'), {})).toBe(
+ path.join(root, 'host/data.ts'),
+ );
+ expect([...hits]).toEqual(['src/component.tsx:@/store/test']);
+ expect(
+ await resolve(path.join(root, 'src/store/test'), path.join(root, 'src/component.tsx'), {}),
+ ).toBe(path.join(root, 'host/data.ts'));
+ });
+
+ it('rejects symlink escapes from the fixture boundary', async () => {
+ const root = await setup();
+ await symlink(path.join(root, 'outside.ts'), path.join(root, 'host/escape.ts'));
+ const resolve = resolver(
+ fixtureDataBoundary(
+ root,
+ path.join(root, 'host'),
+ [
+ {
+ importer: 'src/component.tsx',
+ source: 'data',
+ replacement: 'escape.ts',
+ },
+ ],
+ new Set(),
+ ),
+ );
+ await expect(resolve('data', path.join(root, 'src/component.tsx'), {})).rejects.toThrow(
+ 'FIXTURE_BOUNDARY_ESCAPE',
+ );
+ });
+
+ it('uses version-local explicit exports and fails closed on unsupported maps', async () => {
+ const root = await setup();
+ const resolve = resolver(await workspaceExports(root));
+ expect(await resolve('@example/pkg', undefined, {})).toBe(
+ path.join(root, 'packages/example/index.ts'),
+ );
+ expect(await resolve('react', undefined, {})).toBeUndefined();
+ await expect(resolve('@example/pkg/conditional', undefined, {})).rejects.toThrow(
+ 'WORKSPACE_EXPORT_UNSUPPORTED',
+ );
+ await expect(resolve('@example/pkg/missing', undefined, {})).rejects.toThrow(
+ 'WORKSPACE_EXPORT_UNSUPPORTED',
+ );
+ await expect(resolve('@example/pkg/escape', undefined, {})).rejects.toThrow(
+ 'WORKSPACE_EXPORT_ESCAPE',
+ );
+ });
+});
diff --git a/scripts/stylexMigration/verification/build/fixtureResolvers.ts b/scripts/stylexMigration/verification/build/fixtureResolvers.ts
new file mode 100644
index 00000000000..37f554b0784
--- /dev/null
+++ b/scripts/stylexMigration/verification/build/fixtureResolvers.ts
@@ -0,0 +1,84 @@
+import { readdir, readFile, realpath } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Plugin } from 'vite';
+
+export interface ModuleBoundary {
+ importer: string;
+ replacement: string;
+ source: string;
+}
+
+/** Only exact, declared import edges are replaced; never blanket store/UI aliases. */
+export const fixtureDataBoundary = (
+ root: string,
+ host: string,
+ boundaries: ModuleBoundary[],
+ hits: Set<string>,
+): Plugin => ({
+ name: 'verification-explicit-data-boundaries',
+ enforce: 'pre',
+ async resolveId(id, importer) {
+ if (!importer) return;
+ const cleanImporter = importer.split('?')[0];
+ const canonicalSource = (source: string) =>
+ source.startsWith('@/') ? path.join(root, 'src', source.slice(2))
+ : source.startsWith('.') ? path.resolve(path.dirname(cleanImporter), source) : source;
+ const boundary = boundaries.find(
+ (entry) => path.resolve(root, entry.importer) === cleanImporter &&
+ (entry.source === id || canonicalSource(entry.source) === canonicalSource(id)),
+ );
+ if (!boundary) return;
+ const replacement = await realpath(path.resolve(host, boundary.replacement));
+ if (!replacement.startsWith(host + path.sep)) throw new Error('FIXTURE_BOUNDARY_ESCAPE');
+ hits.add(`${boundary.importer}:${boundary.source}`);
+ return replacement;
+ },
+});
+
+interface WorkspacePackage {
+ directory: string;
+ exports: Record<string, unknown>;
+}
+
+/** Resolve only explicit source exports in this snapshot, not checkout workspace links. */
+export const workspaceExports = async (root: string): Promise<Plugin> => {
+ const packages = new Map<string, WorkspacePackage>();
+ const scan = async (directory: string, depth: number): Promise<void> => {
+ const entries = await readdir(directory, { withFileTypes: true });
+ if (entries.some((entry) => entry.name === 'package.json')) {
+ const manifest = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8'));
+ if (typeof manifest.name !== 'string') return;
+ const exports =
+ typeof manifest.exports === 'string'
+ ? { '.': manifest.exports }
+ : (manifest.exports ?? { '.': manifest.module ?? manifest.main });
+ packages.set(manifest.name, { directory, exports });
+ return;
+ }
+ if (depth === 0) return;
+ for (const entry of entries)
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')
+ await scan(path.join(directory, entry.name), depth - 1);
+ };
+ await scan(path.join(root, 'packages'), 3);
+ return {
+ name: 'verification-snapshot-workspace-exports',
+ enforce: 'pre',
+ async resolveId(id) {
+ const parts = id.split('/');
+ const packageName = parts.splice(0, id.startsWith('@') ? 2 : 1).join('/');
+ const workspace = packages.get(packageName);
+ if (!workspace) return;
+ const key = parts.length ? `./${parts.join('/')}` : '.';
+ const entry = workspace.exports[key];
+ // Conditional and wildcard exports need an explicit adapter; do not guess.
+ if (typeof entry !== 'string' || !entry.startsWith('./'))
+ throw new Error(`WORKSPACE_EXPORT_UNSUPPORTED:${id}`);
+ const resolved = await realpath(path.join(workspace.directory, entry));
+ if (!resolved.startsWith(workspace.directory + path.sep))
+ throw new Error(`WORKSPACE_EXPORT_ESCAPE:${id}`);
+ return resolved;
+ },
+ };
+};
diff --git a/scripts/stylexMigration/verification/cli.ts b/scripts/stylexMigration/verification/cli.ts
index 9d4ce02b5da..40d80d21404 100644
--- a/scripts/stylexMigration/verification/cli.ts
+++ b/scripts/stylexMigration/verification/cli.ts
@@ -3,12 +3,13 @@ import path from 'node:path';
import { parseArgs } from 'node:util';
import { fixtureIds, getStyleFixture } from './fixtures/fixtureRegistry';
-import { exitCode } from './gate/gate';
import { runPreflight } from './pipeline/preflight';
+import { armRunWatchdog } from './pipeline/runWatchdog';
import { fingerprintSources, writeJson } from './reporting/report';
+import { recordSourceCleanup } from './source/cleanupSnapshots';
import { resolvePullRequest } from './source/pullRequest';
-const help = `StyleX migration verification — local M1 foundation (advisory only)
+const help = `StyleX migration verification — calibration evidence collector (not a PR gate)
bun run stylex:verify --base <ref> --head <ref> [--plan-only]
bun run stylex:verify --pr <number> [--repo owner/name] [--plan-only]
@@ -19,13 +20,15 @@ const help = `StyleX migration verification — local M1 foundation (advisory on
bun run stylex:verify self-test [--browser <executable>]
Options: --output <parent-directory>, --repository <local-path>, --help
+--screenshots captures up to three diagnostic A/A/B viewport image sets per component.
+Temporary source/dependency exports are removed after success or failure; --keep-sources retains them for debugging.
Available fixtures: ${fixtureIds.join(', ')}
Revision objects must exist locally. No Git fetch, GitHub writes or PR merges.
Dependency restore is opt-in, offline by default; --dependency-network explicitly enables public npm preparation.
Dependency scripts/hooks and credentials are disabled; component builds run in an offline macOS sandbox.
Default: export both complete source trees and report remaining verification gaps.
-No PR receives PASS until isolated dependencies and certified fixture binding exist.
-Exit: PASS 0 (self-test only), FAIL 1, NEEDS_REVIEW 2, ERROR 3, no change 4.
+The PR gate is bun run style-eq; this command only collects calibration evidence.
+Exit: collection ran 0, self-test regression 1, ERROR 3.
`;
const main = async () => {
@@ -41,11 +44,13 @@ const main = async () => {
'fixtures': { type: 'string' },
'fixture-dependencies': { type: 'boolean' },
'help': { short: 'h', type: 'boolean' },
+ 'keep-sources': { type: 'boolean' },
'output': { type: 'string' },
'plan-only': { type: 'boolean' },
'pr': { type: 'string' },
'pnpm': { type: 'string' },
'restore-dependencies': { type: 'boolean' },
+ 'screenshots': { type: 'boolean' },
'repo': { type: 'string' },
'repository': { type: 'string' },
},
@@ -66,6 +71,8 @@ const main = async () => {
if (values['restore-dependencies'] && (selfTest || values['plan-only']))
throw new Error('DEPENDENCY_RESTORE_REQUIRES_FULL_SOURCE');
if (values.fixture && values.fixtures) throw new Error('CONFLICTING_FIXTURE_OPTIONS');
+ if (values.screenshots && !values.fixture && !values.fixtures)
+ throw new Error('SCREENSHOTS_REQUIRE_FIXTURE');
const selectedFixtures = values.fixtures?.split(',').map((id) => id.trim());
if (
selectedFixtures &&
@@ -109,20 +116,20 @@ const main = async () => {
const output = await mkdtemp(path.join(parent, `${selfTest ? 'self-test' : 'run'}-`));
console.log(`Evidence: ${output}`);
// Bounded process watchdog also covers page.evaluate calls without protocol timeouts.
- const watchdog = setTimeout(
- () => {
- console.error('ERROR: VERIFICATION_TIME_BUDGET_EXCEEDED');
- process.exit(3);
- },
- values['restore-dependencies'] ? 900_000 : 120_000,
- );
- watchdog.unref();
+ let cleanupPromise: Promise<void> | undefined;
+ const cleanup = () =>
+ (cleanupPromise ??=
+ selfTest || values['keep-sources'] ? Promise.resolve() : recordSourceCleanup(output));
+ const stopWatchdog = armRunWatchdog({
+ cleanup,
+ durationMs: values['restore-dependencies'] ? 900_000 : 120_000,
+ });
try {
if (selfTest) {
const { runSelfTest } = await import('./selfTest');
const result = await runSelfTest(output, verifierHash, values.browser);
console.log(JSON.stringify(result));
- process.exitCode = exitCode(result.status);
+ process.exitCode = result.status === 'PASS' ? 0 : 1;
return;
}
let base = values.base;
@@ -166,24 +173,22 @@ const main = async () => {
pullRequest,
repository,
verifierHash,
+ screenshots: values.screenshots,
});
console.log(
JSON.stringify({
changedFiles: result.fixtures.unmappedFiles.length + result.fixtures.candidates.length,
component: result.componentSummary,
componentBatch: result.componentBatchSummary,
- gateEligible: result.gateEligible,
reasonCodes: result.reasonCodes,
report: path.join(output, 'report.html'),
- status: result.status,
units: result.unresolvedUnitIds.length,
}),
);
- process.exitCode = exitCode(result.status);
+ process.exitCode = 0;
} catch (error) {
console.error(error);
await writeJson(output, 'error.json', {
- gateEligible: false,
message: error instanceof Error ? error.message : String(error),
mode: selfTest ? 'self-test' : 'preflight',
schemaVersion: 1,
@@ -192,7 +197,8 @@ const main = async () => {
});
process.exitCode = 3;
} finally {
- clearTimeout(watchdog);
+ stopWatchdog();
+ await cleanup();
}
};
diff --git a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts
index ee37762fba9..982c61ddaf2 100644
--- a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts
+++ b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts
@@ -68,7 +68,6 @@ it('preserves source inputs and resolution policy, excludes unrelated importers
'reviewed patch',
);
expect(result.evidence.reasonCodes).toContain('FIXTURE_CAPSULE_WORKSPACE_PEER_CONTEXT_UNPROVEN');
- expect(result.evidence.gateEligible).toBe(false);
expect(await readFile(path.join(root, 'package.json'), 'utf8')).toBe(original);
const second = await fixture();
expect((await prepareFixtureDependencies(second, inputs, 'LiteTable')).hash).toBe(result.hash);
diff --git a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts
index b019064e36b..f53836f271f 100644
--- a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts
+++ b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts
@@ -104,7 +104,6 @@ export const prepareFixtureDependencies = async (
const evidence = {
fixtureId: fixtureIds.length === 1 ? fixtureIds[0] : undefined,
fixtureIds,
- gateEligible: false,
policy: 'reviewed-fixture-roots-v2',
reasonCodes: ['FIXTURE_CAPSULE_WORKSPACE_PEER_CONTEXT_UNPROVEN'],
roots: dependencies,
diff --git a/scripts/stylexMigration/verification/fixtures/FixtureBusinessData.ts b/scripts/stylexMigration/verification/fixtures/FixtureBusinessData.ts
new file mode 100644
index 00000000000..d50177dadb6
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/FixtureBusinessData.ts
@@ -0,0 +1,31 @@
+import { useState } from 'react';
+
+// Explicit style-only data boundary: never replaces DOM, styles or UI primitives.
+const notExercised = async () => {
+ throw new Error('BUSINESS_MUTATION_OUTSIDE_STYLE_FIXTURE');
+};
+const homeActions = { removeGroup: notExercised, updateGroupName: notExercised };
+
+export const useHomeStore = <T>(selector: (state: typeof homeActions) => T): T =>
+ selector(homeActions);
+
+export const useSidebarGroupVisibility = () => {
+ const [visible, setVisible] = useState(
+ new URL(location.href).searchParams.get('variant') !== 'hidden',
+ );
+ return {
+ isSidebarGroupVisible: () => visible,
+ setSidebarGroupVisible: async (_id: string, next: boolean) => setVisible(next),
+ };
+};
+
+// PreviewToolbar imports this sibling, but ToolbarActionButton never renders it.
+// Fail closed if a future fixture accidentally mounts it.
+export const UnmountedBreadcrumb = () => {
+ throw new Error('UNMOUNTED_SIBLING_RENDERED_IN_STYLE_FIXTURE');
+};
+
+const chatActions = { openLocalFile: notExercised };
+export const useChatStore = <T>(selector: (state: typeof chatActions) => T): T =>
+ selector(chatActions);
+export const useProjectFiles = () => ({ data: { entries: [] } });
diff --git a/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx b/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx
index 680820e8579..67c6b7bdc03 100644
--- a/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx
+++ b/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx
@@ -20,11 +20,13 @@ export const startFixture = (
Fixture: ComponentType<{ variant: string }>,
variants: string[],
containerMode: 'component-root' | 'fixture-wrapper',
+ appearances: Record<string, 'light' | 'dark'> = {},
) => {
const root = document.getElementById('app');
if (!root) throw new Error('FIXTURE_ROOT_MISSING');
const variant = new URL(location.href).searchParams.get('variant') ?? variants[0];
if (!variants.includes(variant)) throw new Error('UNKNOWN_STYLE_VARIANT');
+ document.documentElement.dataset.theme = appearances[variant] ?? 'light';
document.body.style.margin = '0';
document.body.style.fontFamily = 'Arial, sans-serif';
createRoot(root).render(
diff --git a/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx b/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx
index ce4f6c98e81..c0bf9bca9de 100644
--- a/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx
+++ b/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx
@@ -3,12 +3,12 @@ import { OptionCard } from 'verification:component';
export const Fixture = ({ variant }: { variant: string }) => (
<OptionCard
description="Deterministic description"
- disabled={variant === 'disabled'}
- highlighted={variant === 'highlighted'}
+ disabled={variant.endsWith('disabled')}
+ highlighted={variant.endsWith('highlighted')}
index={1}
label="Choice"
recommendedText="Suggested"
- selected={variant === 'selected'}
+ selected={variant.includes('selected')}
onToggle={() => {}}
/>
);
diff --git a/scripts/stylexMigration/verification/fixtures/PreviewToolbarFixture.tsx b/scripts/stylexMigration/verification/fixtures/PreviewToolbarFixture.tsx
new file mode 100644
index 00000000000..3afb8eb2e99
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/PreviewToolbarFixture.tsx
@@ -0,0 +1,22 @@
+import { EyeIcon } from 'lucide-react';
+import { PreviewToolbar } from 'verification:component';
+
+import { ToolbarActionButton } from '@/features/Portal/LocalFile/PreviewToolbar';
+
+export const Fixture = ({ variant }: { variant: string }) => (
+ <PreviewToolbar
+ path="/workspace/components/example.tsx"
+ rootPath="/workspace"
+ actions={
+ variant === 'no-actions' ? undefined : variant === 'hidden-actions' ? (
+ []
+ ) : (
+ <ToolbarActionButton
+ active={variant === 'dark-actions'}
+ icon={EyeIcon}
+ label="Preview file"
+ />
+ )
+ }
+ />
+);
diff --git a/scripts/stylexMigration/verification/fixtures/SidebarGroupItemFixture.tsx b/scripts/stylexMigration/verification/fixtures/SidebarGroupItemFixture.tsx
new file mode 100644
index 00000000000..e7e67d4f203
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/SidebarGroupItemFixture.tsx
@@ -0,0 +1,19 @@
+import { SidebarGroupItem } from 'verification:component';
+
+import { FixtureI18n } from './FixtureI18n';
+
+export const Fixture = ({ variant }: { variant: string }) => (
+ <FixtureI18n>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <SidebarGroupItem
+ disabled
+ id="fixture-group"
+ name={
+ variant === 'long'
+ ? 'A long sidebar folder title to exercise overflow at narrow widths'
+ : 'Folder'
+ }
+ />
+ </div>
+ </FixtureI18n>
+);
diff --git a/scripts/stylexMigration/verification/fixtures/ToolbarActionButtonFixture.tsx b/scripts/stylexMigration/verification/fixtures/ToolbarActionButtonFixture.tsx
new file mode 100644
index 00000000000..652e088fb31
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/ToolbarActionButtonFixture.tsx
@@ -0,0 +1,20 @@
+import { EyeIcon } from 'lucide-react';
+import { ToolbarActionButton } from 'verification:component';
+
+export const Fixture = ({ variant }: { variant: string }) => (
+ <div
+ dir={variant === 'rtl' ? 'rtl' : 'ltr'}
+ style={{
+ containerType: 'inline-size',
+ width: variant === 'narrow' ? 299 : variant === 'boundary' ? 300 : '100%',
+ }}
+ >
+ <ToolbarActionButton
+ active={variant === 'active'}
+ disabled={variant === 'disabled'}
+ icon={EyeIcon}
+ label="Preview file"
+ loading={variant === 'loading'}
+ />
+ </div>
+);
diff --git a/scripts/stylexMigration/verification/fixtures/UnmountedBreadcrumb.tsx b/scripts/stylexMigration/verification/fixtures/UnmountedBreadcrumb.tsx
new file mode 100644
index 00000000000..d081767ee96
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/UnmountedBreadcrumb.tsx
@@ -0,0 +1 @@
+export { UnmountedBreadcrumb as default } from './FixtureBusinessData';
diff --git a/scripts/stylexMigration/verification/fixtures/WorkPreviewData.test.ts b/scripts/stylexMigration/verification/fixtures/WorkPreviewData.test.ts
new file mode 100644
index 00000000000..3c588e922dd
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/WorkPreviewData.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWorkPreviewItem } from './WorkPreviewData';
+
+describe('WorkPreview style input data', () => {
+ it('uses statuses that actually select warning and info colors', () => {
+ expect(getWorkPreviewItem('warning').status).toBe('in_progress');
+ expect(getWorkPreviewItem('info').status).toBe('todo');
+ expect(getWorkPreviewItem('document').status).toBe('completed');
+ });
+
+ it('mounts the declared resource branches with complete task data', () => {
+ expect(['document', 'canvas', 'file', 'github', 'linear'].map((kind) => getWorkPreviewItem(kind).resourceType)).toEqual(['document', 'canvas', 'file', 'github_pull_request', 'linear_issue']);
+ const task = getWorkPreviewItem('task-completed');
+ expect(task.type).toBe('task');
+ if (task.type !== 'task') throw new Error('TASK_FIXTURE_NOT_NARROWED');
+ expect(task.task.status).toBe('completed');
+ });
+});
diff --git a/scripts/stylexMigration/verification/fixtures/WorkPreviewData.ts b/scripts/stylexMigration/verification/fixtures/WorkPreviewData.ts
new file mode 100644
index 00000000000..6d9e77c9312
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/WorkPreviewData.ts
@@ -0,0 +1,70 @@
+import type { WorkSummaryItem } from '@lobechat/types';
+
+const timestamp = new Date('2026-01-01T00:00:00Z');
+const common = {
+ createdAt: timestamp,
+ currentVersionId: null,
+ description: 'A preview with content that wraps at narrower widths.',
+ id: 'fixture-work',
+ identifier: 'WORK-1',
+ originAgentId: null,
+ originThreadId: null,
+ originTopicId: null,
+ resourceId: 'fixture-resource',
+ resourceDeleted: false,
+ status: null,
+ title: 'A detailed title',
+ toolIdentifier: 'fixture',
+ toolName: 'fixture',
+ updatedAt: timestamp,
+ url: null,
+ userId: 'fixture-user',
+ visibility: 'private' as const,
+ workspaceId: null,
+ version: null,
+ totalCost: null,
+ event: {
+ createdAt: timestamp,
+ cumulativeCost: null,
+ cumulativeUsage: null,
+ id: 'fixture-event',
+ metadata: null,
+ changeType: 'created' as const,
+ rootOperationId: null,
+ messageId: null,
+ toolCallId: null,
+ toolName: 'fixture',
+ version: 1,
+ },
+};
+
+export const getWorkPreviewItem = (kind: string): WorkSummaryItem => {
+ if (kind.startsWith('task-'))
+ return {
+ ...common,
+ type: 'task',
+ resourceType: 'task',
+ task: {
+ identifier: 'TASK-1',
+ instruction: common.description,
+ name: common.title,
+ priority: null,
+ status: kind === 'task-completed' ? 'completed' : 'todo',
+ },
+ };
+ if (kind === 'github' || kind === 'linear')
+ return {
+ ...common,
+ type: 'external',
+ resourceType: kind === 'github' ? 'github_pull_request' : 'linear_issue',
+ };
+ if (kind === 'canvas') return { ...common, type: 'canvas', resourceType: 'canvas' };
+ if (kind === 'file')
+ return { ...common, type: 'file', resourceType: 'file', description: 'report.pdf' };
+ return {
+ ...common,
+ type: 'document',
+ resourceType: 'document',
+ status: kind === 'warning' ? 'in_progress' : kind === 'info' ? 'todo' : 'completed',
+ };
+};
diff --git a/scripts/stylexMigration/verification/fixtures/WorkPreviewFixture.tsx b/scripts/stylexMigration/verification/fixtures/WorkPreviewFixture.tsx
new file mode 100644
index 00000000000..919a4544555
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/WorkPreviewFixture.tsx
@@ -0,0 +1,10 @@
+import { WorkPreview } from 'verification:component';
+
+import { getWorkPreviewItem } from './WorkPreviewData';
+
+export const Fixture = ({ variant }: { variant: string }) => (
+ <WorkPreview
+ item={getWorkPreviewItem(variant.replace(/-(light|dark)$/, ''))}
+ title="A detailed preview title"
+ />
+);
diff --git a/scripts/stylexMigration/verification/fixtures/WorkPreviewStatusFixture.tsx b/scripts/stylexMigration/verification/fixtures/WorkPreviewStatusFixture.tsx
new file mode 100644
index 00000000000..6efac397ca4
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/WorkPreviewStatusFixture.tsx
@@ -0,0 +1,10 @@
+import { WorkPreviewStatus } from 'verification:component';
+
+import { getWorkPreviewItem } from './WorkPreviewData';
+
+export const Fixture = ({ variant }: { variant: string }) => (
+ <WorkPreviewStatus
+ item={getWorkPreviewItem(variant.replace(/-(light|dark)$/, ''))}
+ title="A detailed preview title"
+ />
+);
diff --git a/scripts/stylexMigration/verification/fixtures/assets/LICENSE b/scripts/stylexMigration/verification/fixtures/assets/LICENSE
new file mode 100644
index 00000000000..1dd53d2a9d9
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/assets/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 LobeHub
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/scripts/stylexMigration/verification/fixtures/assets/folder-components.svg b/scripts/stylexMigration/verification/fixtures/assets/folder-components.svg
new file mode 100644
index 00000000000..ee0609eee2a
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/assets/folder-components.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
+ <path d="M13.84376,7.53645l-1.28749-1.0729A2,2,0,0,0,11.27591,6H4A2,2,0,0,0,2,8V24a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2H15.12412A2,2,0,0,1,13.84376,7.53645Z" style="fill: #c0ca33"/>
+ <g>
+ <rect x="12" y="20" width="8" height="8" style="fill: #f0f4c3"/>
+ <rect x="22" y="20" width="8" height="8" style="fill: #f0f4c3"/>
+ <rect x="12" y="10" width="8" height="8" style="fill: #f0f4c3"/>
+ <rect x="22" y="10" width="8" height="8" transform="translate(-2.28427 22.48528) rotate(-45)" style="fill: #f0f4c3"/>
+ </g>
+</svg>
diff --git a/scripts/stylexMigration/verification/fixtures/assets/manifest.json b/scripts/stylexMigration/verification/fixtures/assets/manifest.json
new file mode 100644
index 00000000000..9684195d3f6
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/assets/manifest.json
@@ -0,0 +1,14 @@
+[
+ {
+ "url": "https://registry.npmmirror.com/@lobehub/assets-fileicon/1.0.0/files/assets/react_ts.svg",
+ "file": "react_ts.svg",
+ "sha256": "0a8fb7beb18bf9e3f8e4302b5a6e129a7546301c97efb0a84c406629e2038d86",
+ "bytes": 1442
+ },
+ {
+ "url": "https://registry.npmmirror.com/@lobehub/assets-fileicon/1.0.0/files/assets/folder-components.svg",
+ "file": "folder-components.svg",
+ "sha256": "52db2ea34a51325fdcfd1ba94878d66e88d7edc84dd7e66967e1ddf6d2062fcd",
+ "bytes": 605
+ }
+]
diff --git a/scripts/stylexMigration/verification/fixtures/assets/react_ts.svg b/scripts/stylexMigration/verification/fixtures/assets/react_ts.svg
new file mode 100644
index 00000000000..50510021713
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/assets/react_ts.svg
@@ -0,0 +1,8 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
+ <g>
+ <path d="M16,12c7.44405,0,12,2.58981,12,4s-4.55595,4-12,4S4,17.41019,4,16,8.556,12,16,12m0-2C8.268,10,2,12.68629,2,16s6.268,6,14,6,14-2.68629,14-6-6.268-6-14-6Z" style="fill: #0288d1"/>
+ <path d="M16,14a2,2,0,1,0,2,2,2,2,0,0,0-2-2Z" style="fill: #0288d1"/>
+ <path d="M10.45764,5.50706C12.47472,5.50746,16.395,8.68416,19.4641,14,23.18613,20.44672,23.22125,25.68721,22,26.3923a.90009.90009,0,0,1-.45691.10064c-2.01725,0-5.93792-3.17678-9.00721-8.49294C8.81387,11.55328,8.77875,6.31279,10,5.6077a.90278.90278,0,0,1,.45766-.10064m-.00076-2A2.87113,2.87113,0,0,0,9,3.87564C6.13025,5.5325,6.93785,12.30391,10.80385,19c3.28459,5.68906,7.71948,9.49292,10.73927,9.49292A2.87033,2.87033,0,0,0,23,28.12436C25.86975,26.4675,25.06215,19.69609,21.19615,13c-3.28459-5.68906-7.71948-9.49342-10.73927-9.49292Z" style="fill: #0288d1"/>
+ <path d="M21.54311,5.50706A.9.9,0,0,1,22,5.6077c1.22125.70509,1.18613,5.94558-2.5359,12.3923-3.06929,5.31616-6.99,8.49294-9.00721,8.49294A.9.9,0,0,1,10,26.3923C8.77875,25.68721,8.81387,20.44672,12.5359,14c3.06929-5.31616,6.99-8.49294,9.00721-8.49294m0-2c-3.01979,0-7.45468,3.80386-10.73927,9.49292C6.93785,19.69609,6.13025,26.4675,9,28.12436a2.87033,2.87033,0,0,0,1.45688.36856c3.01979,0,7.45468-3.80386,10.73927-9.49292C25.06215,12.30391,25.86975,5.5325,23,3.87564a2.87033,2.87033,0,0,0-1.45688-.36856Z" style="fill: #0288d1"/>
+ </g>
+</svg>
diff --git a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts
index 1d43833266e..b8a3cebbf20 100644
--- a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts
+++ b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts
@@ -4,6 +4,26 @@ import { planFixtureProbes } from '../pipeline/probePlanner';
import { fixtureIds, getStyleFixture, styleFixtureSchema } from './fixtureRegistry';
describe('explicit fixture contract', () => {
+ it('splits WorkPreview resource/status cases inside the sixteen-shard budget', () => {
+ const resources = getStyleFixture('WorkPreview');
+ const statuses = getStyleFixture('WorkPreviewStatus');
+ expect(resources.styleVariants).toHaveLength(14);
+ expect(statuses.styleVariants).toHaveLength(4);
+ expect(planFixtureProbes(resources).length + planFixtureProbes(statuses).length).toBe(108);
+ expect(
+ getStyleFixture('PreviewToolbar').moduleBoundaries.every(
+ (edge) => edge.source !== './PathBreadcrumb',
+ ),
+ ).toBe(true);
+ expect(() =>
+ styleFixtureSchema.parse({
+ ...resources,
+ moduleBoundaries: [
+ { importer: 'src/fixture.tsx', source: 'store', replacement: 'fixtures/undeclared.ts' },
+ ],
+ }),
+ ).toThrow('UNDECLARED_BOUNDARY_ASSET');
+ });
it('declares real versioned entries and does not claim source-unit coverage', () => {
const fixture = getStyleFixture('LiteTable');
expect(fixture.component.base.source).toBe('src/components/LiteTable/index.tsx');
@@ -17,6 +37,28 @@ describe('explicit fixture contract', () => {
).toThrow();
expect(() => getStyleFixture('Unknown')).toThrow('FIXTURE_ADAPTER_UNAVAILABLE');
});
+
+ it('requires unique surfaces and explicitly scoped known portal variants', () => {
+ const fixture = getStyleFixture('GeneratingBorder');
+ const portal = {
+ id: 'popup',
+ kind: 'portal',
+ selector: '[data-popup]',
+ variants: ['generating'],
+ };
+ expect(
+ styleFixtureSchema
+ .parse({ ...fixture, surfaces: [...fixture.surfaces, portal] })
+ .surfaces.at(-1)?.variants,
+ ).toEqual(['generating']);
+ expect(() => styleFixtureSchema.parse({ ...fixture, surfaces: [portal, portal] })).toThrow(
+ 'DUPLICATE_SURFACE_ID',
+ );
+ for (const variants of [['unknown'], ['generating', 'generating'], []])
+ expect(() =>
+ styleFixtureSchema.parse({ ...fixture, surfaces: [{ ...portal, variants }] }),
+ ).toThrow();
+ });
it('plans explicit breakpoint boundaries, RTL, states and all variants within budget', () => {
const probes = planFixtureProbes(getStyleFixture('LiteTable'));
expect(probes).toHaveLength(176);
@@ -31,8 +73,8 @@ describe('explicit fixture contract', () => {
).toBe(false);
});
- it('connects all sixteen entries with explicit mounting and probe contracts', () => {
- expect(fixtureIds).toHaveLength(16);
+ it('connects all entries with explicit mounting and probe contracts', () => {
+ expect(fixtureIds).toHaveLength(21);
for (const id of fixtureIds) {
const fixture = getStyleFixture(id);
expect(fixture.component.id).toBe(id);
diff --git a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts
index be8ff1d512b..2278826d201 100644
--- a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts
+++ b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts
@@ -1,6 +1,7 @@
import { z } from 'zod';
import type { ScopeInventory } from '../types';
+import { migrationFixtures, migrationProfiles } from './migrationProfiles';
const relativePath = z
.string()
@@ -24,6 +25,15 @@ export const styleFixtureSchema = z
containerMode: z.enum(['component-root', 'fixture-wrapper']).default('fixture-wrapper'),
defaultInteractionSelector: z.string().min(1).optional(),
dependencyRoots: z.array(z.string().min(1)).default([]),
+ moduleBoundaries: z
+ .array(
+ z.strictObject({
+ importer: relativePath,
+ source: z.string().min(1),
+ replacement: relativePath,
+ }),
+ )
+ .default([]),
host: relativePath,
fontContract: z.strictObject({
family: z.literal('Arial, sans-serif'),
@@ -52,6 +62,7 @@ export const styleFixtureSchema = z
z.strictObject({
expectedUnits: z.array(z.string().min(1)),
id: z.string().min(1),
+ appearance: z.enum(['light', 'dark']).optional(),
states: z.array(pseudo).min(1).optional(),
}),
)
@@ -62,11 +73,15 @@ export const styleFixtureSchema = z
id: z.string().min(1),
kind: z.enum(['component', 'host', 'portal']),
selector: z.string().min(1),
+ variants: z.array(z.string().min(1)).min(1).optional(),
}),
)
.min(1),
})
.superRefine((fixture, context) => {
+ for (const boundary of fixture.moduleBoundaries)
+ if (!fixture.assets.includes(boundary.replacement))
+ context.addIssue({ code: 'custom', message: 'UNDECLARED_BOUNDARY_ASSET' });
if (
new Set(fixture.styleVariants.map((variant) => variant.id)).size !==
fixture.styleVariants.length
@@ -74,6 +89,17 @@ export const styleFixtureSchema = z
context.addIssue({ code: 'custom', message: 'DUPLICATE_FIXTURE_VARIANT' });
if (new Set(fixture.probeWidths).size !== fixture.probeWidths.length)
context.addIssue({ code: 'custom', message: 'DUPLICATE_PROBE_WIDTH' });
+ if (new Set(fixture.surfaces.map((surface) => surface.id)).size !== fixture.surfaces.length)
+ context.addIssue({ code: 'custom', message: 'DUPLICATE_SURFACE_ID' });
+ for (const surface of fixture.surfaces)
+ if (
+ surface.variants &&
+ (new Set(surface.variants).size !== surface.variants.length ||
+ surface.variants.some(
+ (id) => !fixture.styleVariants.some((variant) => variant.id === id),
+ ))
+ )
+ context.addIssue({ code: 'custom', message: 'INVALID_SURFACE_VARIANTS' });
if (
fixture.sizeContract &&
fixture.probeWidths.some(
@@ -113,21 +139,27 @@ export const experimentalFixtures = [
['TailMarquee', 'src/components/TailMarquee/index.tsx'],
['UnreadDot', 'src/components/UnreadDot/index.tsx'],
['VersionTag', 'src/components/ChangelogModal/VersionTag.tsx'],
+ ...migrationFixtures,
] as const;
export const fixtureIds = experimentalFixtures.map(([id]) => id);
const interactive = ['default', 'hover', 'focus-visible'] as const;
-const profiles: Record<
- string,
- {
- dependencies?: string[];
- i18n?: boolean;
- selector?: string;
- selectors?: { 'hover'?: string; 'focus-visible'?: string };
- settleFrames?: 2;
- variants: Array<{ id: string; states?: readonly (typeof interactive)[number][] }>;
- }
-> = {
+export type FixtureProfile = {
+ assets?: string[];
+ exportName?: string;
+ boundaries?: Array<{ importer: string; source: string; replacement: string }>;
+ dependencies?: string[];
+ i18n?: boolean;
+ selector?: string;
+ selectors?: { 'hover'?: string; 'focus-visible'?: string };
+ settleFrames?: 2;
+ variants: Array<{
+ id: string;
+ appearance?: 'light' | 'dark';
+ states?: readonly (typeof interactive)[number][];
+ }>;
+};
+const profiles: Record<string, FixtureProfile> = {
CollapsibleContent: {
dependencies: ['lucide-react', 'i18next', 'react-i18next'],
i18n: true,
@@ -178,6 +210,10 @@ const profiles: Record<
{ id: 'selected', states: interactive },
{ id: 'highlighted', states: interactive },
{ id: 'disabled', states: interactive },
+ { id: 'selected-highlighted', states: interactive },
+ { id: 'selected-disabled', states: interactive },
+ { id: 'dark-normal', appearance: 'dark', states: interactive },
+ { id: 'dark-selected', appearance: 'dark', states: interactive },
],
},
OptionRow: {
@@ -225,15 +261,25 @@ const profiles: Record<
},
UnreadDot: { variants: [{ id: 'normal' }] },
VersionTag: { variants: [{ id: 'normal' }] },
+ ...migrationProfiles,
};
export const getStyleFixture = (id: string): StyleFixture => {
const entry = experimentalFixtures.find(([name]) => name === id);
const profile = profiles[id];
if (!entry || !profile) throw new Error(`FIXTURE_ADAPTER_UNAVAILABLE:${id}`);
- const component = { exportName: id === 'FilePathDisplay' ? id : 'default', source: entry[1] };
+ const component = {
+ exportName: profile.exportName ?? (id === 'FilePathDisplay' ? id : 'default'),
+ source: entry[1],
+ };
return styleFixtureSchema.parse({
- assets: profile.i18n ? ['fixtures/FixtureI18n.tsx'] : [],
+ assets: [
+ ...(profile.assets ?? []),
+ ...(profile.i18n ? ['fixtures/FixtureI18n.tsx'] : []),
+ ...new Set(profile.boundaries?.map((boundary) => boundary.replacement) ?? []),
+ ...(id === 'ToolbarActionButton' ? ['fixtures/FixtureBusinessData.ts'] : []),
+ ],
+ moduleBoundaries: profile.boundaries,
component: { base: component, candidate: component, id },
containerMode: id === 'LiteTable' ? 'component-root' : 'fixture-wrapper',
defaultInteractionSelector: profile.selector,
@@ -246,14 +292,20 @@ export const getStyleFixture = (id: string): StyleFixture => {
host: 'fixtures/FixtureHost.tsx',
id,
interactionSelectors: profile.selectors,
- probeWidths: id === 'LiteTable' ? [320, 599, 600, 601, 799, 800, 801, 920] : [320, 600, 920],
+ probeWidths:
+ id === 'LiteTable'
+ ? [320, 599, 600, 601, 799, 800, 801, 920]
+ : id === 'PreviewToolbar'
+ ? [319, 320, 321, 459, 460, 461, 920]
+ : [320, 600, 920],
render: `fixtures/${id}Fixture.tsx`,
settleFrames: profile.settleFrames ?? 0,
- sizeContract: { host: [320, 920], viewport: [320, 1200] },
+ sizeContract: { host: [id === 'PreviewToolbar' ? 280 : 320, 920], viewport: [320, 1200] },
styleVariants: profile.variants.map((variant) => ({ ...variant, expectedUnits: [] })),
surfaces: [
{ id: 'host', kind: 'host', selector: '[data-verification-host]' },
{ id: 'component', kind: 'component', selector: '[data-component-mount] > *' },
+ { id: 'lobe-portals', kind: 'portal', selector: '[data-lobe-portal-host]' },
],
});
};
diff --git a/scripts/stylexMigration/verification/fixtures/host.ts b/scripts/stylexMigration/verification/fixtures/host.ts
index f5cbc09fe1a..bc2a2d51326 100644
--- a/scripts/stylexMigration/verification/fixtures/host.ts
+++ b/scripts/stylexMigration/verification/fixtures/host.ts
@@ -44,7 +44,7 @@ export const prepareFixtureHost = async (
);
await writeFile(
path.join(host, 'entry.tsx'),
- `import {startFixture} from ${JSON.stringify('./' + fixture.host)}; import {Fixture} from ${JSON.stringify('./' + fixture.render)}; import {__styleVerificationBindings,__styleVerificationCompositions} from "verification:component"; Object.defineProperty(globalThis,"__styleVerificationBindings",{value:__styleVerificationBindings}); Object.defineProperty(globalThis,"__styleVerificationCompositions",{value:__styleVerificationCompositions}); startFixture(Fixture,${JSON.stringify(fixture.styleVariants.map((variant) => variant.id))},${JSON.stringify(fixture.containerMode)});\n`,
+ `import {startFixture} from ${JSON.stringify('./' + fixture.host)}; import {Fixture} from ${JSON.stringify('./' + fixture.render)}; import {__styleVerificationBindings,__styleVerificationCompositions} from "verification:component"; Object.defineProperty(globalThis,"__styleVerificationBindings",{value:__styleVerificationBindings}); Object.defineProperty(globalThis,"__styleVerificationCompositions",{value:__styleVerificationCompositions}); startFixture(Fixture,${JSON.stringify(fixture.styleVariants.map((variant) => variant.id))},${JSON.stringify(fixture.containerMode)},${JSON.stringify(Object.fromEntries(fixture.styleVariants.map((variant) => [variant.id, variant.appearance])))});\n`,
{ flag: 'wx' },
);
return { componentSource: component.source, fixtureHashes, host, relativeTools, tools };
diff --git a/scripts/stylexMigration/verification/fixtures/migrationProfiles.ts b/scripts/stylexMigration/verification/fixtures/migrationProfiles.ts
new file mode 100644
index 00000000000..35b1f349d7e
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/migrationProfiles.ts
@@ -0,0 +1,102 @@
+import type { FixtureProfile } from './fixtureRegistry';
+
+export const migrationFixtures = [
+ ['SidebarGroupItem', 'src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx'],
+ ['ToolbarActionButton', 'src/features/Portal/LocalFile/PreviewToolbar.tsx'],
+ ['PreviewToolbar', 'src/features/Portal/LocalFile/PreviewToolbar.tsx'],
+ ['WorkPreview', 'src/features/WorkGallery/WorkPreview.tsx'],
+ ['WorkPreviewStatus', 'src/features/WorkGallery/WorkPreview.tsx'],
+] as const;
+
+export const migrationProfiles: Record<string, FixtureProfile> = {
+ SidebarGroupItem: {
+ dependencies: ['lucide-react', 'i18next', 'react-i18next'],
+ i18n: true,
+ variants: ['disabled', 'long', 'hidden'].map((id) => ({ id })),
+ boundaries: ['@/store/home', '../../useSidebarGroupVisibility'].map((source) => ({
+ importer: 'src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx',
+ source,
+ replacement: 'fixtures/FixtureBusinessData.ts',
+ })),
+ },
+ ToolbarActionButton: {
+ dependencies: ['lucide-react', 'i18next', 'react-i18next'],
+ exportName: 'ToolbarActionButton',
+ selector: '[data-component-mount] button',
+ variants: ['normal', 'active', 'disabled', 'loading', 'narrow', 'boundary'].map((id) => ({
+ id,
+ states:
+ id === 'disabled' || id === 'loading'
+ ? ['default', 'hover']
+ : ['default', 'hover', 'focus-visible'],
+ })),
+ boundaries: [
+ {
+ importer: 'src/features/Portal/LocalFile/PreviewToolbar.tsx',
+ source: './PathBreadcrumb',
+ replacement: 'fixtures/UnmountedBreadcrumb.tsx',
+ },
+ ],
+ },
+ PreviewToolbar: {
+ dependencies: ['lucide-react', 'i18next', 'react-i18next'],
+ variants: [
+ { id: 'actions' },
+ { id: 'no-actions' },
+ { id: 'hidden-actions' },
+ { id: 'dark-actions', appearance: 'dark' },
+ ],
+ boundaries: [
+ { source: '@/store/chat', replacement: 'fixtures/FixtureBusinessData.ts' },
+ {
+ source: '@/features/Conversation/WorkingSidebar/Files/useProjectFiles',
+ replacement: 'fixtures/FixtureBusinessData.ts',
+ },
+ ].map((boundary) => ({
+ ...boundary,
+ importer: 'src/features/Portal/LocalFile/PathBreadcrumb.tsx',
+ })),
+ },
+ WorkPreview: {
+ assets: ['fixtures/WorkPreviewData.ts'],
+ dependencies: [
+ 'lucide-react',
+ '@lobehub/icons',
+ 'i18next',
+ 'react-i18next',
+ 'zod',
+ 'path-browserify-esm',
+ ],
+ variants: [
+ 'document',
+ 'canvas',
+ 'file',
+ 'task-todo',
+ 'task-completed',
+ 'github',
+ 'linear',
+ ].flatMap((kind) =>
+ (['light', 'dark'] as const).map((appearance) => ({
+ id: `${kind}-${appearance}`,
+ appearance,
+ })),
+ ),
+ },
+ WorkPreviewStatus: {
+ assets: ['fixtures/WorkPreviewData.ts'],
+ dependencies: [
+ 'lucide-react',
+ '@lobehub/icons',
+ 'i18next',
+ 'react-i18next',
+ 'zod',
+ 'path-browserify-esm',
+ ],
+ variants: ['warning', 'info'].flatMap((kind) =>
+ (['light', 'dark'] as const).map((appearance) => ({
+ id: `${kind}-${appearance}`,
+ appearance,
+ })),
+ ),
+ },
+};
diff --git a/scripts/stylexMigration/verification/fixtures/modules.d.ts b/scripts/stylexMigration/verification/fixtures/modules.d.ts
index 9e2bf47c76f..50ec550862c 100644
--- a/scripts/stylexMigration/verification/fixtures/modules.d.ts
+++ b/scripts/stylexMigration/verification/fixtures/modules.d.ts
@@ -1,5 +1,7 @@
declare module 'verification:component' {
+ import type { WorkSummaryItem } from '@lobechat/types';
import type { ListProps } from '@lobehub/ui';
+ import type { LucideIcon } from 'lucide-react';
import type { ComponentType, CSSProperties, ReactNode } from 'react';
interface Row {
@@ -23,6 +25,24 @@ declare module 'verification:component' {
tableLayout: 'auto' | 'fixed';
}
export const LiteTable: ComponentType<Props>;
+ export const WorkPreview: ComponentType<{
+ item: WorkSummaryItem;
+ title: string;
+ }>;
+ export const WorkPreviewStatus: typeof WorkPreview;
+ export const PreviewToolbar: ComponentType<{
+ actions?: ReactNode;
+ path: string;
+ rootPath?: string;
+ }>;
+ export const ToolbarActionButton: ComponentType<{
+ active?: boolean;
+ disabled?: boolean;
+ icon: LucideIcon;
+ label?: ReactNode;
+ loading?: boolean;
+ }>;
+ export const SidebarGroupItem: ComponentType<{ disabled: boolean; id: string; name: string }>;
export const Menu: ComponentType<ListProps>;
export const SpendType: ComponentType<{
children: ReactNode;
diff --git a/scripts/stylexMigration/verification/fixtures/pinnedAssets.test.ts b/scripts/stylexMigration/verification/fixtures/pinnedAssets.test.ts
new file mode 100644
index 00000000000..dcd98be7d91
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/pinnedAssets.test.ts
@@ -0,0 +1,49 @@
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { loadPinnedAssets } from './pinnedAssets';
+
+const directories: string[] = [];
+afterEach(async () => {
+ await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true })));
+});
+
+const setup = async (overrides: Record<string, string> = {}) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'stylex-pinned-assets-'));
+ directories.push(root);
+ const directory = path.join(root, 'fixtures/assets');
+ await mkdir(directory, { recursive: true });
+ const body = '<svg xmlns="http://www.w3.org/2000/svg"/>';
+ const asset = {
+ file: 'react_ts.svg',
+ sha256: createHash('sha256').update(body).digest('hex'),
+ url: 'https://example.test/pinned.svg',
+ ...overrides,
+ };
+ await writeFile(path.join(directory, 'react_ts.svg'), body);
+ await writeFile(path.join(directory, 'manifest.json'), JSON.stringify([asset]));
+ return { root, asset, body };
+};
+
+describe('loadPinnedAssets', () => {
+ it('loads the exact asset and leaves unlisted URLs unavailable', async () => {
+ const { root, asset, body } = await setup();
+ const assets = await loadPinnedAssets(root);
+ expect(assets.get(asset.url)?.toString()).toBe(body);
+ expect(assets.has('https://example.test/other.svg')).toBe(false);
+ });
+
+ it('rejects changed upstream bytes', async () => {
+ const { root } = await setup({ sha256: '0'.repeat(64) });
+ await expect(loadPinnedAssets(root)).rejects.toThrow('PINNED_ASSET_HASH_MISMATCH');
+ });
+
+ it('rejects a manifest path outside its asset directory', async () => {
+ const { root } = await setup({ file: '../outside.svg' });
+ await expect(loadPinnedAssets(root)).rejects.toThrow('INVALID_PINNED_ASSET');
+ });
+});
diff --git a/scripts/stylexMigration/verification/fixtures/pinnedAssets.ts b/scripts/stylexMigration/verification/fixtures/pinnedAssets.ts
new file mode 100644
index 00000000000..a114272c728
--- /dev/null
+++ b/scripts/stylexMigration/verification/fixtures/pinnedAssets.ts
@@ -0,0 +1,34 @@
+import { createHash } from 'node:crypto';
+import { readFile, realpath } from 'node:fs/promises';
+import path from 'node:path';
+
+interface Asset {
+ file: string;
+ sha256: string;
+ url: string;
+}
+
+/** Exact, hashed upstream assets only; all other external requests stay blocked. */
+export const loadPinnedAssets = async (sourceDirectory: string) => {
+ const directory = await realpath(path.join(sourceDirectory, 'fixtures/assets'));
+ const manifest = JSON.parse(
+ await readFile(path.join(directory, 'manifest.json'), 'utf8'),
+ ) as Asset[];
+ const assets = new Map<string, Buffer>();
+ for (const asset of manifest) {
+ if (
+ !/^[a-z_-]+\.svg$/.test(asset.file) ||
+ !/^[a-f0-9]{64}$/.test(asset.sha256) ||
+ !asset.url.startsWith('https://') ||
+ assets.has(asset.url)
+ )
+ throw new Error('INVALID_PINNED_ASSET');
+ const file = await realpath(path.join(directory, asset.file));
+ if (!file.startsWith(directory + path.sep)) throw new Error('PINNED_ASSET_ESCAPE');
+ const body = await readFile(file);
+ if (createHash('sha256').update(body).digest('hex') !== asset.sha256)
+ throw new Error('PINNED_ASSET_HASH_MISMATCH');
+ assets.set(asset.url, body);
+ }
+ return assets;
+};
diff --git a/scripts/stylexMigration/verification/gate/coverage.ts b/scripts/stylexMigration/verification/gate/coverage.ts
deleted file mode 100644
index 6face619598..00000000000
--- a/scripts/stylexMigration/verification/gate/coverage.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { CoverageSummary, GateInput } from '../types';
-
-/** Keys are namespaced by unit: two distinct slots can never close one another. */
-export const calculateCoverage = (input: GateInput): CoverageSummary => {
- const fixtures = new Set(input.fixtures.map((fixture) => fixture.id));
- const missingKeys: string[] = [];
- const unresolvedUnitIds: string[] = [];
- let requiredKeys = 0;
- for (const unit of input.units) {
- const witnessed = new Set(
- input.witnesses
- .filter(
- (witness) =>
- witness.unitId === unit.id &&
- unit.fixtureIds.includes(witness.fixtureId) &&
- fixtures.has(witness.fixtureId) &&
- witness.evidenceRefs.length > 0,
- )
- .map((witness) => witness.key),
- );
- const missing = unit.requiredKeys.filter((key) => !witnessed.has(key));
- requiredKeys += unit.requiredKeys.length;
- missingKeys.push(...missing);
- if (!unit.fixtureIds.length || !unit.requiredKeys.length || missing.length)
- unresolvedUnitIds.push(unit.id);
- }
- return {
- machineResolvedUnits: input.units.length - unresolvedUnitIds.length,
- missingKeys,
- requiredKeys,
- reviewResolvedUnits: 0,
- totalUnits: input.units.length,
- unresolvedUnitIds,
- witnessedKeys: requiredKeys - missingKeys.length,
- };
-};
diff --git a/scripts/stylexMigration/verification/gate/gate.test.ts b/scripts/stylexMigration/verification/gate/gate.test.ts
deleted file mode 100644
index c626556bfea..00000000000
--- a/scripts/stylexMigration/verification/gate/gate.test.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-// @vitest-environment node
-import { describe, expect, it } from 'vitest';
-
-import type { GateInput } from '../types';
-import { evaluateGate, exitCode } from './gate';
-
-const input = (): GateInput => ({
- errors: [],
- fixtures: [{ aaStable: true, comparisons: 1, id: 'button', nodeCount: 2, propertyReads: 12 }],
- findings: [],
- fullScope: true,
- identityVerified: true,
- pureStyleMigration: true,
- units: [
- { componentId: 'button', fixtureIds: ['button'], id: 'root', requiredKeys: ['root:default'] },
- ],
- witnesses: [
- {
- evidenceRefs: ['snapshot.json'],
- fixtureId: 'button',
- key: 'root:default',
- probeId: 'default',
- unitId: 'root',
- },
- ],
-});
-
-describe('style migration gate', () => {
- it('passes only complete, stable, identity-verified comparisons', () => {
- const result = evaluateGate(input());
- expect(result).toMatchObject({ gateEligible: true, status: 'PASS' });
- expect(exitCode(result.status)).toBe(0);
- });
-
- it('keeps an unmounted style unit in the coverage denominator', () => {
- const value = input();
- value.units.push({
- componentId: 'button',
- fixtureIds: [],
- id: 'hidden',
- requiredKeys: ['hidden:hover'],
- });
- const result = evaluateGate(value);
- expect(result.status).toBe('NEEDS_REVIEW');
- expect(result.coverage).toMatchObject({
- totalUnits: 2,
- machineResolvedUnits: 1,
- missingKeys: ['hidden:hover'],
- unresolvedUnitIds: ['hidden'],
- });
- expect(exitCode(result.status)).toBe(2);
- });
-
- it.each(['fixtures', 'units', 'witnesses'] as const)(
- 'never passes an empty %s collection',
- (key) => {
- const value = input();
- value[key] = [];
- expect(evaluateGate(value).status).not.toBe('PASS');
- },
- );
-
- it.each(['nodeCount', 'comparisons', 'propertyReads'] as const)(
- 'rejects empty %s measurements',
- (key) => {
- const value = input();
- value.fixtures[0][key] = 0;
- expect(evaluateGate(value).status).toBe('ERROR');
- },
- );
-
- it('does not accept a witness from the wrong fixture or without evidence', () => {
- for (const witness of [
- { ...input().witnesses[0], fixtureId: 'unrelated' },
- { ...input().witnesses[0], evidenceRefs: [] },
- { ...input().witnesses[0], unitId: 'unrelated' },
- ]) {
- expect(evaluateGate({ ...input(), witnesses: [witness] }).status).not.toBe('PASS');
- }
- });
-
- it('requires every conditional key, not merely one hit per rule', () => {
- const value = input();
- value.units[0].requiredKeys.push('root:hover:media-small');
- expect(evaluateGate(value).coverage.missingKeys).toEqual(['root:hover:media-small']);
- });
-
- it('fails confirmed differences even when coverage is incomplete', () => {
- const value = input();
- value.witnesses = [];
- value.findings.push({
- confirmed: true,
- id: 'padding',
- reasonCode: 'STYLE_CHANGED',
- severity: 'difference',
- });
- expect(evaluateGate(value).status).toBe('FAIL');
- expect(exitCode(evaluateGate(value).status)).toBe(1);
- });
-
- it('does not call an unconfirmed difference stable', () => {
- const value = input();
- value.findings.push({
- confirmed: false,
- id: 'padding',
- reasonCode: 'UNSTABLE_DIFFERENCE',
- severity: 'difference',
- });
- expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');
- });
-
- it('retains failures and missing coverage when an execution error wins', () => {
- const value = input();
- value.errors.push('BROWSER_DISCONNECTED');
- value.witnesses = [];
- value.findings.push({
- confirmed: true,
- id: 'padding',
- reasonCode: 'STYLE_CHANGED',
- severity: 'difference',
- });
- const result = evaluateGate(value);
- expect(result.status).toBe('ERROR');
- expect(result.findings).toHaveLength(1);
- expect(result.coverage.missingKeys).toHaveLength(1);
- expect(exitCode(result.status)).toBe(3);
- });
-
- it.each(['fullScope', 'identityVerified', 'pureStyleMigration'] as const)(
- 'does not issue a gate PASS without %s',
- (key) => {
- expect(evaluateGate({ ...input(), [key]: false })).toMatchObject({
- gateEligible: false,
- status: 'NEEDS_REVIEW',
- });
- },
- );
-
- it('rejects unstable A/A and missing A/A controls', () => {
- const value = input();
- value.fixtures[0].aaStable = false;
- expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');
- });
-
- it('does not turn unsupported conditions or empty key sets green', () => {
- const value = input();
- value.units[0].requiredKeys = [];
- expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');
- expect(
- evaluateGate({
- ...input(),
- findings: [
- {
- confirmed: false,
- id: 'highlight',
- reasonCode: 'UNSUPPORTED_HIGHLIGHT',
- severity: 'review',
- },
- ],
- }).status,
- ).toBe('NEEDS_REVIEW');
- });
-
- it('rejects duplicate IDs and unknown schema fields', () => {
- const value = input();
- value.units.push(value.units[0]);
- expect(() => evaluateGate(value)).toThrow();
- expect(() => evaluateGate({ ...input(), approvedBy: 'author' })).toThrow();
- });
-});
diff --git a/scripts/stylexMigration/verification/gate/gate.ts b/scripts/stylexMigration/verification/gate/gate.ts
deleted file mode 100644
index 2f80e46d96d..00000000000
--- a/scripts/stylexMigration/verification/gate/gate.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { GateDecision, MachineStatus } from '../types';
-import { gateInputSchema } from '../types';
-import { calculateCoverage } from './coverage';
-
-export const exitCode = (status: MachineStatus | 'NOT_APPLICABLE') =>
- ({
- ERROR: 3,
- FAIL: 1,
- NEEDS_REVIEW: 2,
- NOT_APPLICABLE: 4,
- PASS: 0,
- })[status];
-
-/** All collection adapters must pass through this reducer. It never approves evidence. */
-export const evaluateGate = (value: unknown): GateDecision => {
- const input = gateInputSchema.parse(value);
- const coverage = calculateCoverage(input);
- const errors = [...input.errors];
- const reasons = new Set<string>();
- if (!input.identityVerified) reasons.add('IDENTITY_UNVERIFIED');
- if (!input.fullScope) reasons.add('PARTIAL_SCOPE');
- if (!input.pureStyleMigration) reasons.add('PURE_STYLE_MIGRATION_UNPROVEN');
- if (!input.units.length) reasons.add('EMPTY_SCOPE');
- if (!input.fixtures.length) reasons.add('MISSING_FIXTURE');
- if (coverage.unresolvedUnitIds.length || !coverage.requiredKeys)
- reasons.add('INCOMPLETE_COVERAGE');
- for (const fixture of input.fixtures) {
- if (!fixture.nodeCount || !fixture.comparisons || !fixture.propertyReads)
- errors.push(`EMPTY_CAPTURE:${fixture.id}`);
- if (!fixture.aaStable) reasons.add(`UNSTABLE_FIXTURE:${fixture.id}`);
- }
- for (const unit of input.units) {
- if (unit.fixtureIds.some((id) => !input.fixtures.some((fixture) => fixture.id === id)))
- reasons.add('MISSING_FIXTURE');
- }
- const difference = input.findings.some(
- (finding) => finding.severity === 'difference' && finding.confirmed,
- );
- input.findings.forEach((finding) => reasons.add(finding.reasonCode));
- const status: MachineStatus = errors.length
- ? 'ERROR'
- : difference
- ? 'FAIL'
- : reasons.size
- ? 'NEEDS_REVIEW'
- : 'PASS';
- return {
- coverage,
- errors,
- findings: input.findings,
- gateEligible: status === 'PASS',
- reasonCodes: [...reasons].sort(),
- status,
- };
-};
diff --git a/scripts/stylexMigration/verification/pipeline/componentRunner.ts b/scripts/stylexMigration/verification/pipeline/componentRunner.ts
index f379cba6ccd..ee79c939056 100644
--- a/scripts/stylexMigration/verification/pipeline/componentRunner.ts
+++ b/scripts/stylexMigration/verification/pipeline/componentRunner.ts
@@ -25,12 +25,16 @@ import { captureComponent } from '../browser/capture';
import { compareComponents } from '../browser/compareSnapshots';
import { collectRulesInPage } from '../browser/ruleInventory';
import { readRuntimeCompositions } from '../browser/runtimeCompositions';
+import { captureScreenshotEvidence } from '../browser/screenshotEvidence';
+import { screenshotCaptureLimit, shouldCaptureScreenshot } from '../browser/screenshotPlan';
+import { resolveCaptureSurfacesInPage } from '../browser/surfaces';
import { buildComponentFixture } from '../build/buildFixtures';
import { digestFile } from '../dependencies/dependencySnapshot';
import type { StyleFixture } from '../fixtures/fixtureRegistry';
import { serveFixtures } from '../fixtures/fixtureServer';
+import { loadPinnedAssets } from '../fixtures/pinnedAssets';
import { sha256, writeJson } from '../reporting/report';
-import type { GateInput } from '../types';
+import type { FixtureResult, VerificationFinding } from '../types';
import type { FixtureProbe } from './probePlanner';
import { planFixtureProbes } from './probePlanner';
import type { ProbeShardBudget } from './probeShards';
@@ -64,6 +68,9 @@ interface ProbeResult {
}
const openPage = async (browser: Browser, origin: string, failures: Set<string>) => {
+ const sourceDirectory = process.env.STYLEX_VERIFIER_SOURCE_DIRECTORY;
+ if (!sourceDirectory) throw new Error('VERIFIER_SOURCE_DIRECTORY_MISSING');
+ const assets = await loadPinnedAssets(sourceDirectory);
const context = await browser.newContext({
colorScheme: 'light',
deviceScaleFactor: 1,
@@ -74,7 +81,12 @@ const openPage = async (browser: Browser, origin: string, failures: Set<string>)
viewport: { height: 900, width: 1200 },
});
await context.route('**/*', async (route) => {
- if (new URL(route.request().url()).origin === origin) await route.continue();
+ if (assets.has(route.request().url()))
+ await route.fulfill({
+ body: assets.get(route.request().url())!,
+ contentType: 'image/svg+xml',
+ });
+ else if (new URL(route.request().url()).origin === origin) await route.continue();
else {
failures.add(`EXTERNAL_REQUEST_BLOCKED:${route.request().resourceType()}`);
await route.abort();
@@ -135,30 +147,40 @@ const applyProbe = async (
},
{ ...probe, settleFrames: fixture.settleFrames },
);
+ const scope = await page.evaluate(resolveCaptureSurfacesInPage, {
+ surfaces: fixture.surfaces,
+ variant: probe.variant,
+ });
if (probe.interaction || probe.pseudo !== 'default') {
const selector = probe.interaction
- ? await page.evaluate(({ key, tag }) => {
- if (!/^root(?:\.\d+)*$/.test(key)) throw new Error('INVALID_TRIGGER_KEY');
- let element = document.querySelector('[data-case-root]');
- for (const index of key.split('.').slice(1).map(Number))
- element = element
- ? [...element.children].filter(
- (child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName),
- )[index]
- : null;
- if (!element || element.tagName !== tag)
- throw new Error('PAIRED_TRIGGER_STRUCTURE_MISMATCH');
- const segments: string[] = [];
- for (
- let current: Element | null = element;
- current?.parentElement;
- current = current.parentElement
- )
- segments.unshift(
- `:nth-child(${[...current.parentElement.children].indexOf(current) + 1})`,
- );
- return [':root', ...segments].join(' > ');
- }, probe.interaction)
+ ? await page.evaluate(
+ ({ key, tag, roots }) => {
+ const surface = roots.find((root) => key.startsWith(`${root.keyPrefix}root`));
+ if (!surface) throw new Error('INVALID_TRIGGER_SURFACE');
+ const localKey = key.slice(surface.keyPrefix.length);
+ if (!/^root(?:\.\d+)*$/.test(localKey)) throw new Error('INVALID_TRIGGER_KEY');
+ let element = document.querySelector(surface.selector);
+ for (const index of localKey.split('.').slice(1).map(Number))
+ element = element
+ ? [...element.children].filter(
+ (child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName),
+ )[index]
+ : null;
+ if (!element || element.tagName !== tag)
+ throw new Error('PAIRED_TRIGGER_STRUCTURE_MISMATCH');
+ const segments: string[] = [];
+ for (
+ let current: Element | null = element;
+ current?.parentElement;
+ current = current.parentElement
+ )
+ segments.unshift(
+ `:nth-child(${[...current.parentElement.children].indexOf(current) + 1})`,
+ );
+ return [':root', ...segments].join(' > ');
+ },
+ { ...probe.interaction, roots: scope.roots },
+ )
: (fixture.interactionSelectors[probe.pseudo as 'hover' | 'focus-visible'] ??
fixture.defaultInteractionSelector);
if (!selector) throw new Error('PSEUDO_TRIGGER_CONTRACT_MISSING');
@@ -183,6 +205,7 @@ export const runComponentFixture = async (options: {
fixture: StyleFixture;
output: string;
sourceDirectory: string;
+ screenshots?: boolean;
}) => {
const { fixture, output } = options;
const builds = {
@@ -202,11 +225,11 @@ export const runComponentFixture = async (options: {
fixture,
output,
provenance: 'component-build',
+ screenshots: options.screenshots,
});
return { ...result, artifactFiles: ['fixture-builds.json', ...result.artifactFiles] };
};
-/** Lower-level browser integration; callers cannot turn this into a gate approval. */
export const runFixtureComparison = async (options: {
browser?: string;
bindingPlans?: { base: StyleBindingPlan; candidate: StyleBindingPlan };
@@ -217,6 +240,7 @@ export const runFixtureComparison = async (options: {
probeBudget?: Partial<ProbeShardBudget>;
planConditions?: boolean;
provenance: 'component-build' | 'infrastructure-corpus';
+ screenshots?: boolean;
}) => {
const { builds, fixture, output } = options;
const started = performance.now();
@@ -237,7 +261,7 @@ export const runFixtureComparison = async (options: {
});
let browser: Browser | undefined;
const failures = new Set<string>();
- const findings: GateInput['findings'] = [
+ const findings: VerificationFinding[] = [
{
confirmed: false,
id: 'font-contract',
@@ -245,9 +269,14 @@ export const runFixtureComparison = async (options: {
severity: 'review',
},
];
- const fixtureResults: GateInput['fixtures'] = [];
+ const fixtureResults: FixtureResult[] = [];
const artifactFiles = ['probe-plan.json'];
const results: ProbeResult[] = [];
+ const screenshots: Array<{
+ probeId: string;
+ variant: string;
+ result: Awaited<ReturnType<typeof captureScreenshotEvidence>>;
+ }> = [];
const rulePlans: Array<{ plan: RuleWitnessPlan; side: 'base' | 'candidate'; variant: string }> =
[];
const ruleEvidence: RuleProbeEvidence[] = [];
@@ -380,9 +409,12 @@ export const runFixtureComparison = async (options: {
const captureTiming: CaptureTiming[] = [{}, {}, {}];
const [base, aa, candidate] = await shardController.runOperation(() =>
Promise.all(
- pages
- .slice(0, 3)
- .map((entry, index) => captureComponent(entry.page, entry.cdp, captureTiming[index])),
+ pages.slice(0, 3).map((entry, index) =>
+ captureComponent(entry.page, entry.cdp, captureTiming[index], {
+ surfaces: fixture.surfaces,
+ variant: probe.variant,
+ }),
+ ),
),
);
timing.capture = performance.now() - phaseStarted;
@@ -404,7 +436,10 @@ export const runFixtureComparison = async (options: {
applyProbe(pages[3].page, pages[3].cdp, server.origin, 'candidate', probe, fixture),
);
const repeated = await shardController.runOperation(() =>
- captureComponent(pages[3].page, pages[3].cdp, (confirmationCaptureTiming = {})),
+ captureComponent(pages[3].page, pages[3].cdp, (confirmationCaptureTiming = {}), {
+ surfaces: fixture.surfaces,
+ variant: probe.variant,
+ }),
);
confirmation = compareComponents(aa, repeated);
evidenceRefs.push(await saveSnapshot(repeated));
@@ -412,6 +447,25 @@ export const runFixtureComparison = async (options: {
JSON.stringify(comparison.differences) === JSON.stringify(confirmation.differences);
}
timing.confirmation = performance.now() - phaseStarted;
+ if (
+ options.screenshots &&
+ shouldCaptureScreenshot(
+ fixture.styleVariants.map((entry) => entry.id),
+ screenshots.map((entry) => entry.variant),
+ variant.id,
+ comparison.differences.length > 0,
+ )
+ ) {
+ const image = await shardController.runOperation(() =>
+ captureScreenshotEvidence(
+ pages.slice(0, 3).map((entry) => entry.page),
+ output,
+ `pixels-${screenshots.length}`,
+ ),
+ );
+ screenshots.push({ probeId: probe.id, variant: variant.id, result: image });
+ artifactFiles.push(...image.artifactFiles);
+ }
phaseStarted = performance.now();
if (comparison.differences.length)
findings.push({
@@ -438,6 +492,7 @@ export const runFixtureComparison = async (options: {
pages[index].page.evaluate(collectRuleWitnessesInPage, {
nonce: randomBytes(8).toString('hex'),
rules: plan.rules,
+ roots: (index === 0 ? base : candidate).scope?.roots,
}),
);
ruleEvidence.push({
@@ -480,6 +535,7 @@ export const runFixtureComparison = async (options: {
)!.observation;
return {
...(await pages[index].page.evaluate(readConditionHostInPage, {
+ 'roots': (index === 0 ? base : candidate).scope?.roots,
'hover': fixture.interactionSelectors.hover ?? fixture.defaultInteractionSelector,
'focus-visible':
fixture.interactionSelectors['focus-visible'] ??
@@ -549,6 +605,19 @@ export const runFixtureComparison = async (options: {
);
}
const probeShards = shardController.report(probes.map((probe) => probe.id));
+ if (options.screenshots) {
+ await writeJson(output, 'screenshots.json', {
+ advisoryOnly: true,
+ captures: screenshots,
+ maxCaptures: screenshotCaptureLimit,
+ limitations: [
+ 'VIEWPORT_ONLY',
+ 'PIXEL_EQUALITY_DOES_NOT_OVERRIDE_STYLE_FAILURE',
+ 'UNSAMPLED_STATES_NOT_PROVEN',
+ ],
+ });
+ artifactFiles.push('screenshots.json');
+ }
await writeJson(output, 'probe-shards.json', probeShards);
artifactFiles.push('probe-shards.json');
for (const [index, reasonCode] of probeShards.gaps.entries())
@@ -657,7 +726,6 @@ export const runFixtureComparison = async (options: {
],
fixture,
fixtureResults,
- gateEligible: false,
results,
ruleCoverageRef: ruleCoverage ? 'rule-coverage.json' : undefined,
schemaVersion: 1,
diff --git a/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts b/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts
index ba6ecdcddd6..aa41204dd60 100644
--- a/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts
+++ b/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts
@@ -4,7 +4,6 @@ import path from 'node:path';
import { type StyleFixture, styleFixtureSchema } from '../fixtures/fixtureRegistry';
import { summarizeComponentRun } from '../reporting/componentSummary';
import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';
-import type { GateInput } from '../types';
import { runComponentFixture } from './componentRunner';
/** One frozen B/M pair and dependency capsule; isolated build namespace per
@@ -16,11 +15,9 @@ export const runFixtureBatch = async (options: {
fixtures: StyleFixture[];
output: string;
sourceDirectory: string;
+ screenshots?: boolean;
}) => {
const started = performance.now();
- const errors: string[] = [];
- const findings: GateInput['findings'] = [];
- const fixtureResults: GateInput['fixtures'] = [];
const artifactFiles: string[] = [];
const entries: Array<{
fixtureId: string;
@@ -41,12 +38,6 @@ export const runFixtureBatch = async (options: {
// Reserve the two 60s sandbox build deadlines before starting new work.
if (performance.now() - started >= 13 * 60_000) {
const reason = 'FIXTURE_BATCH_TIME_BUDGET_EXCEEDED';
- findings.push({
- confirmed: false,
- id: `${fixture.id}:batch-budget`,
- reasonCode: reason,
- severity: 'review',
- });
entries.push({
fixtureId: fixture.id,
outcome: 'NOT_RUN',
@@ -55,22 +46,13 @@ export const runFixtureBatch = async (options: {
});
await writeJson(directory, 'not-run.json', {
fixtureId: fixture.id,
- gateEligible: false,
reason,
});
- await writeHtmlReport(directory, { fixtureId: fixture.id, gateEligible: false, reason });
+ await writeHtmlReport(directory, { fixtureId: fixture.id, reason });
} else {
console.log(JSON.stringify({ phase: 'component-start', fixture: fixture.id }));
const run = await runComponentFixture({ ...options, fixture, output: directory });
const summary = summarizeComponentRun(run.result);
- errors.push(...run.result.errors.map((error) => `${fixture.id}:${error}`));
- findings.push(
- ...run.result.findings.map((finding) => ({
- ...finding,
- id: `${fixture.id}:${finding.id}`,
- })),
- );
- fixtureResults.push(...run.result.fixtureResults);
entries.push({
fixtureId: fixture.id,
outcome: 'COMPLETED',
@@ -80,12 +62,10 @@ export const runFixtureBatch = async (options: {
await writeJson(directory, 'component-summary.json', {
...summary,
fixtureId: fixture.id,
- gateEligible: false,
});
await writeHtmlReport(directory, {
...summary,
fixtureId: fixture.id,
- gateEligible: false,
componentRunRef: 'component-run.json',
});
console.log(
@@ -95,7 +75,6 @@ export const runFixtureBatch = async (options: {
} catch (error) {
console.error(error);
const reason = error instanceof Error ? error.message : String(error);
- errors.push(`${fixture.id}:${reason}`);
entries.push({
fixtureId: fixture.id,
outcome: 'ERROR',
@@ -104,10 +83,9 @@ export const runFixtureBatch = async (options: {
});
await writeJson(directory, 'fixture-error.json', {
fixtureId: fixture.id,
- gateEligible: false,
reason,
});
- await writeHtmlReport(directory, { fixtureId: fixture.id, gateEligible: false, reason });
+ await writeHtmlReport(directory, { fixtureId: fixture.id, reason });
}
const files = await readdir(directory, { withFileTypes: true });
if (files.some((file) => !file.isFile())) throw new Error('UNEXPECTED_FIXTURE_REPORT_ENTRY');
@@ -137,10 +115,9 @@ export const runFixtureBatch = async (options: {
await writeJson(options.output, 'fixture-batch.json', {
durationMs: performance.now() - started,
entries,
- gateEligible: false,
plannedFixtureIds: ids,
summary,
});
artifactFiles.push('fixture-batch.json');
- return { artifactFiles, errors, findings, fixtureResults, summary };
+ return { artifactFiles, entries, summary };
};
diff --git a/scripts/stylexMigration/verification/pipeline/preflight.ts b/scripts/stylexMigration/verification/pipeline/preflight.ts
index fd260b7b647..37ee9ca4225 100644
--- a/scripts/stylexMigration/verification/pipeline/preflight.ts
+++ b/scripts/stylexMigration/verification/pipeline/preflight.ts
@@ -8,7 +8,6 @@ import {
prepareFixtureDependencies,
} from '../dependencies/fixtureDependencies';
import { discoverFixtureCandidates, getStyleFixture } from '../fixtures/fixtureRegistry';
-import { evaluateGate } from '../gate/gate';
import { summarizeComponentRun } from '../reporting/componentSummary';
import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';
import { prepareSourceSnapshots } from '../source/buildSnapshots';
@@ -27,6 +26,7 @@ export interface PreflightOptions {
planOnly: boolean;
pullRequest?: { baseRef: string; headRepository: string; number: number; repository: string };
repository: string;
+ screenshots?: boolean;
verifierHash: string;
}
@@ -49,21 +49,6 @@ export const runPreflight = async (options: PreflightOptions) => {
});
await writeJson(options.output, 'fixtures.json', fixtures);
const routing = !options.planOnly && scope.changedFiles.length === 0;
- const gateInput = {
- errors: [],
- findings: [],
- fixtures: [],
- fullScope: false,
- identityVerified: false,
- pureStyleMigration: false,
- units: scope.units.map((unit) => ({
- componentId: unit.file,
- fixtureIds: [],
- id: unit.id,
- requiredKeys: [],
- })),
- witnesses: [],
- };
const snapshots =
!routing && !options.planOnly
? await prepareSourceSnapshots(session, options.output)
@@ -130,6 +115,7 @@ export const runPreflight = async (options: PreflightOptions) => {
fixture: getStyleFixture(options.fixture.id),
output: options.output,
sourceDirectory: options.fixture.sourceDirectory,
+ screenshots: options.screenshots,
});
}
if (options.fixtureBatch && snapshots) {
@@ -141,15 +127,9 @@ export const runPreflight = async (options: PreflightOptions) => {
fixtures: options.fixtureBatch.ids.map(getStyleFixture),
output: options.output,
sourceDirectory: options.fixtureBatch.sourceDirectory,
+ screenshots: options.screenshots,
});
}
- const gate = evaluateGate({
- ...gateInput,
- errors: component?.result.errors ?? batch?.errors ?? [],
- findings: component?.result.findings ?? batch?.findings ?? [],
- fixtures: component?.result.fixtureResults ?? batch?.fixtureResults ?? [],
- });
- await writeJson(options.output, 'coverage.json', gate.coverage);
const reasonCodes = routing
? ['NO_STYLE_IMPACT']
: [
@@ -160,7 +140,6 @@ export const runPreflight = async (options: PreflightOptions) => {
: []),
'SOURCE_UNIT_BINDING_UNPROVEN',
...(!component && !batch ? ['BROWSER_VERIFICATION_NOT_RUN'] : []),
- ...gate.reasonCodes,
...scope.limitations,
];
const result = {
@@ -172,7 +151,6 @@ export const runPreflight = async (options: PreflightOptions) => {
componentBatchRef: batch ? 'fixture-batch.json' : undefined,
componentRunRef: component ? 'component-run.json' : undefined,
fixtures,
- gateEligible: false as const,
identity: session.identity,
mode: 'preflight' as const,
migrationResidueRef: 'migration-residue.json',
@@ -181,7 +159,6 @@ export const runPreflight = async (options: PreflightOptions) => {
schemaVersion: 1 as const,
scopeHash: scope.hash,
snapshots,
- status: routing ? ('NOT_APPLICABLE' as const) : gate.status,
unresolvedUnitIds: scope.units.map((unit) => unit.id),
verifierHash: options.verifierHash,
};
@@ -192,7 +169,6 @@ export const runPreflight = async (options: PreflightOptions) => {
'scope.json',
'migration-residue.json',
'fixtures.json',
- 'coverage.json',
'preflight.json',
'report.html',
...(options.pullRequest ? ['pull-request.json'] : []),
diff --git a/scripts/stylexMigration/verification/pipeline/probeShards.test.ts b/scripts/stylexMigration/verification/pipeline/probeShards.test.ts
index ecc003c9689..6b394a74e01 100644
--- a/scripts/stylexMigration/verification/pipeline/probeShards.test.ts
+++ b/scripts/stylexMigration/verification/pipeline/probeShards.test.ts
@@ -17,7 +17,6 @@ describe('bounded probe shards', () => {
expect(report.shards.map((shard) => shard.completedProbeIds)).toEqual([['a', 'b'], ['c']]);
expect(report.unexecutedProbeIds).toEqual([]);
expect(report.gaps).toEqual([]);
- expect(report.gateEligible).toBe(false);
});
it('starts a fresh shard at a variant boundary', () => {
diff --git a/scripts/stylexMigration/verification/pipeline/probeShards.ts b/scripts/stylexMigration/verification/pipeline/probeShards.ts
index 96fcfb6e7e5..58647c14dc2 100644
--- a/scripts/stylexMigration/verification/pipeline/probeShards.ts
+++ b/scripts/stylexMigration/verification/pipeline/probeShards.ts
@@ -145,7 +145,6 @@ export const createProbeShardController = (
budget,
durationMs: clock() - started,
gaps: [...gaps],
- gateEligible: false as const,
mode: 'bounded-in-process-shards' as const,
plannedProbeIds,
shards,
diff --git a/scripts/stylexMigration/verification/pipeline/runWatchdog.test.ts b/scripts/stylexMigration/verification/pipeline/runWatchdog.test.ts
new file mode 100644
index 00000000000..422191221e1
--- /dev/null
+++ b/scripts/stylexMigration/verification/pipeline/runWatchdog.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { armRunWatchdog } from './runWatchdog';
+
+afterEach(() => vi.useRealTimers());
+
+it('waits for cleanup before fatal exit and reports cleanup failures', async () => {
+ vi.useFakeTimers();
+ const events: string[] = [];
+ armRunWatchdog({
+ cleanup: async () => {
+ events.push('cleanup');
+ throw new Error('cleanup failed');
+ },
+ durationMs: 10,
+ report: (message) => events.push(String(message)),
+ terminate: (code) => events.push(`exit:${code}`),
+ });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(events).toEqual([
+ 'ERROR: VERIFICATION_TIME_BUDGET_EXCEEDED',
+ 'cleanup',
+ 'Error: cleanup failed',
+ 'exit:3',
+ ]);
+});
+
+it('can be disposed and bounds a stuck cleanup attempt', async () => {
+ vi.useFakeTimers();
+ const cleanup = vi.fn(() => new Promise<void>(() => {}));
+ const terminate = vi.fn();
+ const report = vi.fn();
+ armRunWatchdog({ cleanup, durationMs: 10, report, terminate })();
+ await vi.advanceTimersByTimeAsync(20);
+ expect(cleanup).not.toHaveBeenCalled();
+ armRunWatchdog({ cleanup, durationMs: 10, report, terminate });
+ await vi.advanceTimersByTimeAsync(120_010);
+ expect(report).toHaveBeenCalledWith('ERROR: SOURCE_CLEANUP_TIME_BUDGET_EXCEEDED');
+ expect(terminate).toHaveBeenCalledWith(3);
+});
diff --git a/scripts/stylexMigration/verification/pipeline/runWatchdog.ts b/scripts/stylexMigration/verification/pipeline/runWatchdog.ts
new file mode 100644
index 00000000000..c0542eaef66
--- /dev/null
+++ b/scripts/stylexMigration/verification/pipeline/runWatchdog.ts
@@ -0,0 +1,26 @@
+/** Deadline exits must allow owned-source cleanup; SIGKILL remains unrecoverable. */
+export const armRunWatchdog = (options: {
+ cleanup: () => Promise<void>;
+ durationMs: number;
+ report?: (message: unknown) => void;
+ terminate?: (code: number) => void;
+}) => {
+ const report = options.report ?? console.error;
+ const terminate = options.terminate ?? ((code: number) => process.exit(code));
+ const timer = setTimeout(() => {
+ report('ERROR: VERIFICATION_TIME_BUDGET_EXCEEDED');
+ const grace = setTimeout(() => {
+ report('ERROR: SOURCE_CLEANUP_TIME_BUDGET_EXCEEDED');
+ terminate(3);
+ }, 120_000);
+ void options
+ .cleanup()
+ .catch(report)
+ .finally(() => {
+ clearTimeout(grace);
+ terminate(3);
+ });
+ }, options.durationMs);
+ timer.unref();
+ return () => clearTimeout(timer);
+};
diff --git a/scripts/stylexMigration/verification/reporting/componentSummary.ts b/scripts/stylexMigration/verification/reporting/componentSummary.ts
index 7b53cb7a69d..a7177c69db8 100644
--- a/scripts/stylexMigration/verification/reporting/componentSummary.ts
+++ b/scripts/stylexMigration/verification/reporting/componentSummary.ts
@@ -1,6 +1,5 @@
import type { runFixtureComparison } from '../pipeline/componentRunner';
-/** Equality is explicitly limited to executed samples, never a gate PASS. */
export const sampledStyleStatus = (
probes: Array<{
aaStable: boolean;
diff --git a/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.ts b/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.ts
deleted file mode 100644
index 747d2047cc5..00000000000
--- a/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import path from 'node:path';
-import { promisify } from 'node:util';
-import { gunzip } from 'node:zlib';
-
-import type { StyleBindingPlan } from '../analysis/styleBindings';
-import type { ComponentSnapshot } from '../browser/capture';
-import { getStyleFixture } from '../fixtures/fixtureRegistry';
-import { evaluateGate, exitCode } from '../gate/gate';
-import { runFixtureComparison } from '../pipeline/componentRunner';
-import { writeArtifactManifest } from '../reporting/report';
-
-const decompress = promisify(gunzip);
-
-/** Controlled HTML tests the infrastructure only; it is not a component adapter. */
-export const runBrowserPipelineSelfTest = async (output: string, browser?: string) => {
- const results = [];
- for (const mode of [
- 'equal',
- 'difference',
- 'supplemental',
- 'condition-intersection',
- 'condition-fraction',
- 'shards-complete',
- 'shards-truncated',
- 'shards-difference-truncated',
- ]) {
- const changed = mode === 'difference' || mode === 'shards-difference-truncated';
- const supplemental = mode === 'supplemental';
- const conditional = mode.startsWith('condition-');
- const sharded = mode.startsWith('shards-');
- const truncated = mode.endsWith('-truncated');
- const directory = path.join(output, `pipeline-${mode}`);
- const base = path.join(directory, 'base');
- const candidate = path.join(directory, 'candidate');
- await mkdir(base, { recursive: true });
- await mkdir(candidate);
- const html = (color: string, candidate = false) => {
- const conditionalCss =
- mode === 'condition-intersection'
- ? `@media (max-width:650px){@container card (max-width:550px){.row:hover>td{color:${candidate ? 'blue' : 'red'}}}}`
- : mode === 'condition-fraction'
- ? `@container card (599.2px < width < 599.4px){.row td{color:${candidate ? 'blue' : 'red'}}}`
- : '';
- const contextCheck = sharded
- ? `addEventListener('DOMContentLoaded',()=>{const count=Number(localStorage.getItem('visits')||0)+1;localStorage.setItem('visits',String(count));document.querySelector('[data-case-root]').setAttribute('data-context-visits',String(count));});`
- : '';
- return `<!doctype html><html><head><style>body{margin:0;font:14px Arial}td{color:${color}}tr:hover{background:yellow}${supplemental ? `.row:hover>td{background:red}${candidate ? '.row:nth-child(2):hover>td{background:blue}' : ''}` : ''}${conditionalCss}</style><script>Object.defineProperty(globalThis,'__styleVerificationBindings',{value:{styles:{row:'row'}}});Object.defineProperty(globalThis,'__styleVerificationCompositions',{value:{records:[],gaps:[]}});${contextCheck}</script></head><body><div id="app" data-verification-ready><main data-case-root data-verification-host><div data-component-mount><div style="container:card / inline-size"><table><tbody><tr class="row" tabindex="0"><td>Controlled infrastructure corpus</td></tr>${supplemental ? '<tr class="row" tabindex="0"><td>Second target</td></tr>' : ''}</tbody></table></div></div></main></div></body></html>`;
- };
- await writeFile(path.join(base, 'index.html'), html('red'), { flag: 'wx' });
- await writeFile(path.join(candidate, 'index.html'), html(changed ? 'blue' : 'red', true), {
- flag: 'wx',
- });
- const fixture = {
- ...getStyleFixture('LiteTable'),
- component: {
- id: 'infrastructure-corpus-no-react',
- base: { exportName: 'none', source: 'base/index.html' },
- candidate: { exportName: 'none', source: 'candidate/index.html' },
- },
- host: 'base/index.html',
- id: 'infrastructure-corpus',
- render: 'base/index.html',
- styleVariants: [{ expectedUnits: [], id: 'normal' }],
- };
- const comparison = await runFixtureComparison({
- bindingPlans:
- supplemental || conditional
- ? { base: controlledBindingPlan, candidate: controlledBindingPlan }
- : undefined,
- browser,
- builds: { base: { output: base }, candidate: { output: candidate } },
- fixture,
- output: directory,
- provenance: 'infrastructure-corpus',
- probeBudget: sharded ? { maxProbesPerShard: 1, maxShards: truncated ? 1 : 2 } : undefined,
- planConditions: conditional,
- probes: [
- {
- direction: 'ltr',
- id: 'normal:default',
- pseudo: 'default',
- variant: 'normal',
- width: 320,
- },
- { direction: 'rtl', id: 'normal:hover', pseudo: 'hover', variant: 'normal', width: 600 },
- ],
- });
- const gate = evaluateGate({
- errors: comparison.result.errors,
- findings: comparison.result.findings,
- fixtures: comparison.result.fixtureResults,
- fullScope: false,
- identityVerified: false,
- pureStyleMigration: false,
- units: [
- {
- componentId: 'infrastructure-corpus',
- fixtureIds: [],
- id: 'unresolved-source',
- requiredKeys: [],
- },
- ],
- witnesses: [],
- });
- await writeArtifactManifest(directory, [
- ...comparison.artifactFiles,
- 'base/index.html',
- 'candidate/index.html',
- ]);
- const expected = changed || supplemental || conditional ? 'FAIL' : 'NEEDS_REVIEW';
- const supplementPassed =
- !supplemental ||
- (comparison.result.supplemental.scheduled === 1 &&
- comparison.result.ruleCoverage?.missingActivationTargets === 0 &&
- comparison.result.results
- .slice(0, 2)
- .every((entry) => !entry.comparison.differences.length) &&
- comparison.result.results[2]?.confirmed === true);
- const conditionPassed =
- !conditional ||
- (comparison.result.results
- .slice(0, 2)
- .every((entry) => entry.comparison.differences.length === 0) &&
- comparison.result.results.slice(2).some((entry) => entry.confirmed) &&
- (mode === 'condition-fraction'
- ? comparison.result.conditionCoverage!.missing > 0
- : comparison.result.conditionCoverage!.missing === 0));
- let freshContexts = true;
- if (sharded)
- for (const file of comparison.result.results.flatMap((entry) => entry.evidenceRefs)) {
- const snapshot: ComponentSnapshot = JSON.parse(
- (await decompress(await readFile(path.join(directory, file)))).toString(),
- );
- freshContexts &&=
- snapshot.attributes
- .find((entry) => entry.key === 'root')
- ?.attributes.find(([name]) => name === 'data-context-visits')?.[1] === '1';
- }
- const shardsPassed =
- !sharded ||
- (freshContexts &&
- comparison.result.probeShards.shards === (truncated ? 1 : 2) &&
- comparison.result.probeShards.completedShards === (truncated ? 1 : 2) &&
- comparison.result.probeShards.failedShards === 0 &&
- comparison.result.unexecutedProbeIds.length === (truncated ? 1 : 0) &&
- comparison.result.findings.some(
- (entry) => entry.reasonCode === 'PROBE_SHARD_COUNT_BUDGET_EXCEEDED',
- ) === truncated);
- results.push({
- actual: gate.status,
- aaStable: comparison.result.fixtureResults.every((entry) => entry.aaStable),
- browserIdentity: comparison.result.browser,
- confirmed: comparison.result.results.filter((entry) => entry.confirmed).length,
- exitCode: exitCode(gate.status),
- expected,
- gateEligible: gate.gateEligible,
- supplemental: comparison.result.supplemental,
- conditionCoverage: comparison.result.conditionCoverage,
- probeShards: comparison.result.probeShards,
- freshContexts,
- passed:
- gate.status === expected &&
- !gate.gateEligible &&
- (conditional ||
- comparison.result.results.length === (supplemental ? 3 : truncated ? 1 : 2)) &&
- comparison.result.fixtureResults.every((entry) => entry.aaStable) &&
- !comparison.result.errors.length &&
- (truncated || !comparison.result.unexecutedProbeIds.length) &&
- supplementPassed &&
- conditionPassed &&
- shardsPassed,
- report: path.relative(output, path.join(directory, 'component-run.json')),
- });
- }
- return {
- results,
- summary: { cases: results.length, failed: results.filter((result) => !result.passed).length },
- };
-};
-
-const controlledBindingPlan: StyleBindingPlan = {
- bindings: [
- {
- kind: 'css-module',
- symbol: 'styles',
- slots: [{ name: 'row', start: 0, end: 1, unitId: 'controlled-row' }],
- },
- ],
- gaps: [],
- source: 'controlled.html',
- sourceHash: 'controlled',
- stylesheets: [],
-};
diff --git a/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts b/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts
index 470c2e50fc3..1d79adf1132 100644
--- a/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts
+++ b/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts
@@ -1,8 +1,11 @@
import type { Browser } from '@playwright/test';
+import {
+ captureInPage,
+ compareSnapshots,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
import { captureComponent } from '../browser/capture';
import { createFastCapture } from '../browser/fastCapture';
-import { captureInPage, compareSnapshots } from '../browser/snapshot';
/** Independent legacy enumeration. Never share the optimized name list with the
* reference collector: doing so could hide an omitted property in both trees. */
diff --git a/scripts/stylexMigration/verification/selfTest/index.ts b/scripts/stylexMigration/verification/selfTest/index.ts
index 50bec34c088..36012f605e3 100644
--- a/scripts/stylexMigration/verification/selfTest/index.ts
+++ b/scripts/stylexMigration/verification/selfTest/index.ts
@@ -2,16 +2,19 @@ import path from 'node:path';
import { chromium } from '@playwright/test';
+import {
+ captureInPage,
+ compareSnapshots,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
import { createFastCapture } from '../browser/fastCapture';
import { createProbeDriver } from '../browser/probes';
-import { captureInPage, compareSnapshots } from '../browser/snapshot';
import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';
import { boundaries, boundaryHtml } from './boundaries';
-import { runBrowserPipelineSelfTest } from './browserPipelineSelfTest';
import { runCapturePreparationSelfTest } from './capturePreparationSelfTest';
import { runCollectorSelfTest } from './collectorSelfTest';
import { runBoundaryMatrix } from './matrix';
import { runRuleWitnessSelfTest } from './ruleWitnessSelfTest';
+import { runSurfaceSelfTest } from './surfaceSelfTest';
/** The prototype corpus remains regression evidence, never a whole-PR PASS. */
export const runSelfTest = async (
@@ -55,10 +58,10 @@ export const runSelfTest = async (
if (!entry.passed) regressions.push(`COLLECTOR_REGRESSION:${entry.id}`);
const capturePreparation = await runCapturePreparationSelfTest(browser);
if (capturePreparation.summary.failed) regressions.push('CAPTURE_PREPARATION_REGRESSION');
- const pipeline = await runBrowserPipelineSelfTest(output, executablePath);
- if (pipeline.summary.failed) regressions.push('BROWSER_PIPELINE_REGRESSION');
const ruleWitness = await runRuleWitnessSelfTest(browser);
if (ruleWitness.summary.failed) regressions.push('RULE_WITNESS_REGRESSION');
+ const surfaces = await runSurfaceSelfTest(browser);
+ if (surfaces.summary.failed) regressions.push('CAPTURE_SURFACE_REGRESSION');
const parity: Array<{ caseId: string; differences: number; nodes: number; side: string }> = [];
const page = await browser.newPage();
@@ -101,9 +104,8 @@ export const runSelfTest = async (
collector: collector.summary,
capturePreparation: capturePreparation.summary,
ruleWitness: ruleWitness.summary,
- pipeline: pipeline.summary,
+ surfaces: surfaces.summary,
durationMs: performance.now() - started,
- gateEligible: false,
mode: 'self-test',
parity: {
comparisons: parity.length,
@@ -120,8 +122,8 @@ export const runSelfTest = async (
await writeJson(output, 'parity.json', parity);
await writeJson(output, 'collector.json', collector);
await writeJson(output, 'capture-preparation.json', capturePreparation);
- await writeJson(output, 'pipeline.json', pipeline);
await writeJson(output, 'rule-witness.json', ruleWitness);
+ await writeJson(output, 'surfaces.json', surfaces);
await writeJson(output, 'self-test.json', result);
await writeHtmlReport(output, result);
await writeArtifactManifest(output, [
@@ -130,16 +132,8 @@ export const runSelfTest = async (
'parity.json',
'collector.json',
'capture-preparation.json',
- 'pipeline.json',
'rule-witness.json',
- 'pipeline-equal/artifacts.json',
- 'pipeline-difference/artifacts.json',
- 'pipeline-supplemental/artifacts.json',
- 'pipeline-condition-intersection/artifacts.json',
- 'pipeline-condition-fraction/artifacts.json',
- 'pipeline-shards-complete/artifacts.json',
- 'pipeline-shards-truncated/artifacts.json',
- 'pipeline-shards-difference-truncated/artifacts.json',
+ 'surfaces.json',
'self-test.json',
'report.html',
]);
diff --git a/scripts/stylexMigration/verification/selfTest/matrix.ts b/scripts/stylexMigration/verification/selfTest/matrix.ts
index e08be8633cb..d6994766795 100644
--- a/scripts/stylexMigration/verification/selfTest/matrix.ts
+++ b/scripts/stylexMigration/verification/selfTest/matrix.ts
@@ -1,7 +1,10 @@
import type { Browser } from '@playwright/test';
+import {
+ captureInPage,
+ compareSnapshots,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
import { compareWithProbes, discoverProbes } from '../browser/probes';
-import { captureInPage, compareSnapshots } from '../browser/snapshot';
import { boundaries, boundaryHtml } from './boundaries';
export const runBoundaryMatrix = async (
diff --git a/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts b/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts
index 5603d7104dd..6d3bc4d85be 100644
--- a/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts
+++ b/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts
@@ -1,5 +1,9 @@
import type { Browser } from '@playwright/test';
+import {
+ captureInPage,
+ compareSnapshots,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
import {
collectRuleWitnessesInPage,
planRuleWitnesses,
@@ -7,7 +11,6 @@ import {
} from '../analysis/ruleWitnesses';
import type { StyleBindingPlan } from '../analysis/styleBindings';
import { collectRulesInPage } from '../browser/ruleInventory';
-import { captureInPage, compareSnapshots } from '../browser/snapshot';
import { sha256 } from '../reporting/report';
/** Real browser tests of marker isolation and branch activation, not React substitutes. */
diff --git a/scripts/stylexMigration/verification/selfTest/surfaceSelfTest.ts b/scripts/stylexMigration/verification/selfTest/surfaceSelfTest.ts
new file mode 100644
index 00000000000..e6c77463ddf
--- /dev/null
+++ b/scripts/stylexMigration/verification/selfTest/surfaceSelfTest.ts
@@ -0,0 +1,172 @@
+import type { Browser } from '@playwright/test';
+
+import {
+ captureInPage,
+ compareSnapshots,
+} from '../../../../packages/style-equivalence/src/capture/snapshot';
+import { readConditionHostInPage } from '../analysis/conditionProbePlanner';
+import { collectRuleWitnessesInPage, planRuleWitnesses } from '../analysis/ruleWitnesses';
+import { captureComponent } from '../browser/capture';
+import { collectRulesInPage } from '../browser/ruleInventory';
+import type { CaptureSurface } from '../browser/surfaces';
+import { resolveCaptureSurfacesInPage } from '../browser/surfaces';
+
+/** Executed by the local browser self-test, never by the application test suite. */
+export const runSurfaceSelfTest = async (browser: Browser) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await page.route('**/*', (route) => route.abort());
+ const cdp = await context.newCDPSession(page);
+ await cdp.send('DOM.enable');
+ await cdp.send('CSS.enable');
+ const results: Array<{ id: string; passed: boolean; detail?: unknown }> = [];
+ const surfaces: CaptureSurface[] = [{ id: 'popup', kind: 'portal', selector: '.popup' }];
+ try {
+ await page.setContent(`<!doctype html><style>
+ body{margin:0}.popup{position:absolute;left:20px;top:50px;color:blue;--local:blue}
+ .popup::before{content:'Before';color:purple}.other{color:red}
+ </style><main data-case-root><div data-component-mount><button>Trigger</button></div></main>
+ <section class="popup"><span>Blue</span><span hidden>Hidden</span><svg><path d="M0 0L5 5"/></svg></section>
+ <aside class="popup other">Red leaf</aside><footer>Unrelated fixture content</footer>`);
+ const snapshot = await captureComponent(page, cdp, undefined, { surfaces, variant: 'open' });
+ results.push({
+ id: 'multiple-roots-pseudos-leaf-svg-hidden',
+ passed:
+ snapshot.scope?.roots.length === 3 &&
+ new Set(snapshot.tree.nodes.map((node) => node.key)).size === snapshot.tree.nodes.length &&
+ snapshot.tree.nodes.some((node) => node.key === 'surface:popup:0/root::before') &&
+ snapshot.tree.nodes.some((node) => node.tag === 'path') &&
+ !snapshot.tree.nodes.some((node) => node.tag === 'FOOTER') &&
+ snapshot.tree.styles[
+ snapshot.tree.nodes.find((node) => node.key === 'surface:popup:0/root')!.style
+ ].color === 'rgb(0, 0, 255)' &&
+ snapshot.tree.styles[
+ snapshot.tree.nodes.find((node) => node.key === 'surface:popup:1/root')!.style
+ ].color === 'rgb(255, 0, 0)',
+ });
+ for (const root of snapshot.scope!.roots) {
+ const properties = ['color', 'display', 'height', 'background-color', 'animation-name'];
+ const reference = await page.evaluate(captureInPage, {
+ ...root,
+ originSelector: '[data-case-root]',
+ properties,
+ });
+ const measured = {
+ ...snapshot.tree,
+ nodes: snapshot.tree.nodes.filter((node) => node.key.startsWith(`${root.keyPrefix}root`)),
+ styles: snapshot.tree.styles.map((style) =>
+ Object.fromEntries(properties.map((property) => [property, style[property]])),
+ ),
+ };
+ results.push({
+ id: `strict-hybrid-parity:${root.keyPrefix || 'main'}`,
+ passed: compareSnapshots(reference, measured).length === 0,
+ });
+ }
+ const first = await page.evaluate(resolveCaptureSurfacesInPage, { surfaces });
+ const second = await page.evaluate(resolveCaptureSurfacesInPage, { surfaces });
+ results.push({
+ id: 'repeat-resolution-stable',
+ passed: JSON.stringify(first) === JSON.stringify(second),
+ });
+ for (const [id, definition, error] of [
+ ['missing', { id: 'missing', kind: 'portal', selector: '.absent' }, 'SURFACE_NOT_MOUNTED'],
+ [
+ 'invalid-selector',
+ { id: 'invalid', kind: 'portal', selector: '[' },
+ 'SURFACE_SELECTOR_INVALID',
+ ],
+ ['broad-body', { id: 'body', kind: 'portal', selector: 'body' }, 'SURFACE_CONTAINS_ROOT'],
+ [
+ 'misclassified',
+ { id: 'wrong', kind: 'component', selector: '.popup' },
+ 'SURFACE_OUTSIDE_ROOT',
+ ],
+ ] as const) {
+ let message = '';
+ try {
+ await page.evaluate(resolveCaptureSurfacesInPage, { surfaces: [definition] });
+ } catch (caught) {
+ message = String(caught);
+ }
+ results.push({ id, passed: message.includes(error) });
+ }
+ const closed = await page.evaluate(resolveCaptureSurfacesInPage, {
+ surfaces: [
+ { id: 'conditional', kind: 'portal', selector: '.absent', variants: ['open'] },
+ ] satisfies CaptureSurface[],
+ variant: 'closed',
+ });
+ results.push({
+ id: 'closed-variant-explicitly-excludes-popup',
+ passed: closed.roots.length === 1 && closed.surfaces.length === 0,
+ });
+ await page.setContent(
+ '<main data-case-root><div data-component-mount><div class="inside">Inside</div></div></main><section class="outer"><span class="inner">Nested</span></section>',
+ );
+ const overlap = await page.evaluate(resolveCaptureSurfacesInPage, {
+ surfaces: [
+ { id: 'inner', kind: 'portal', selector: '.inner' },
+ { id: 'outer', kind: 'portal', selector: '.outer' },
+ { id: 'duplicate', kind: 'portal', selector: '.outer' },
+ { id: 'inside', kind: 'portal', selector: '.inside' },
+ ] satisfies CaptureSurface[],
+ });
+ results.push({
+ id: 'nested-overlapping-and-in-root-deduplicated',
+ passed: overlap.roots.length === 2 && overlap.surfaces.length === 4,
+ });
+ await page.setContent(
+ '<style>.popup:hover{color:red}</style><main data-case-root><div data-component-mount><button>Trigger</button></div></main><section class="popup"><span>Content</span></section>',
+ );
+ const scope = await page.evaluate(resolveCaptureSurfacesInPage, { surfaces });
+ const plan = planRuleWitnesses(
+ await page.evaluate(collectRulesInPage),
+ {
+ bindings: [
+ {
+ kind: 'css-module',
+ symbol: 'styles',
+ slots: [{ name: 'popup', start: 0, end: 1, unitId: 'popup' }],
+ },
+ ],
+ gaps: [],
+ source: 'corpus.css',
+ sourceHash: 'controlled',
+ stylesheets: [],
+ },
+ { styles: { popup: 'popup' } },
+ );
+ const document = await cdp.send('DOM.getDocument');
+ const target = await cdp.send('DOM.querySelector', {
+ nodeId: document.root.nodeId,
+ selector: '.popup',
+ });
+ await cdp.send('CSS.forcePseudoState', {
+ nodeId: target.nodeId,
+ forcedPseudoClasses: ['hover'],
+ });
+ const observation = await page.evaluate(collectRuleWitnessesInPage, {
+ nonce: '0123456789abcdef',
+ rules: plan.rules,
+ roots: scope.roots,
+ });
+ const host = await page.evaluate(readConditionHostInPage, {
+ hover: '.popup',
+ roots: scope.roots,
+ });
+ results.push({
+ id: 'portal-rule-witness-and-trigger-use-capture-keys',
+ passed:
+ observation.observations[0]?.targets[0]?.active === true &&
+ observation.observations[0]?.targets[0]?.key === 'surface:popup:0/root' &&
+ observation.observations[0]?.targets[0]?.triggers[0]?.key === host.legacyTriggerKeys.hover,
+ });
+ } finally {
+ await context.close();
+ }
+ return {
+ results,
+ summary: { cases: results.length, failed: results.filter((result) => !result.passed).length },
+ };
+};
diff --git a/scripts/stylexMigration/verification/source/cleanupSnapshots.test.ts b/scripts/stylexMigration/verification/source/cleanupSnapshots.test.ts
new file mode 100644
index 00000000000..2664607fb36
--- /dev/null
+++ b/scripts/stylexMigration/verification/source/cleanupSnapshots.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { cleanupSourceSnapshots } from './cleanupSnapshots';
+
+const owned: string[] = [];
+const setup = async () => {
+ const output = await mkdtemp(path.join(tmpdir(), 'stylex-cleanup-test-'));
+ owned.push(output);
+ await mkdir(path.join(output, 'base-source/.stylex-dependencies'), { recursive: true });
+ await writeFile(path.join(output, 'base-source/package.json'), '{"name":"source"}');
+ await writeFile(path.join(output, 'base-source/component.ts'), 'export const x = 1;');
+ await writeFile(path.join(output, 'base-source/.stylex-dependencies/pnpm-lock.yaml'), 'lock');
+ await writeFile(path.join(output, 'snapshot.json.gz'), 'raw-evidence');
+ await mkdir(path.join(output, 'base-source/.stylex-dependencies/.stylex-tools'), {
+ recursive: true,
+ });
+ await writeFile(
+ path.join(output, 'base-source/.stylex-dependencies/.stylex-tools/restore.log'),
+ 'pnpm failure details',
+ );
+ await mkdir(
+ path.join(output, 'base-source/.stylex-dependencies/.stylex-tools/cache/a/b/c/d/e/f'),
+ { recursive: true },
+ );
+ await mkdir(path.join(output, 'base-source/.stylex-tools/fixtures/Example'), { recursive: true });
+ await writeFile(
+ path.join(output, 'base-source/.stylex-tools/fixtures/Example/build.log'),
+ 'build details',
+ );
+ return output;
+};
+
+afterEach(async () => {
+ for (const output of owned.splice(0)) await rm(output, { force: true, recursive: true });
+});
+
+describe('owned verification source lifecycle', () => {
+ it('removes partial exports, preserving lock inputs and browser evidence', async () => {
+ const output = await setup();
+ const result = await cleanupSourceSnapshots(output);
+ expect(result.removed).toEqual(['base-source']);
+ expect(await readFile(path.join(output, 'snapshot.json.gz'), 'utf8')).toBe('raw-evidence');
+ expect(
+ await readFile(path.join(output, 'source-metadata/base-source/package.json'), 'utf8'),
+ ).toContain('source');
+ expect(
+ await readFile(
+ path.join(output, 'source-metadata/base-source/.stylex-dependencies/pnpm-lock.yaml'),
+ 'utf8',
+ ),
+ ).toBe('lock');
+ await expect(readFile(path.join(output, 'base-source/component.ts'))).rejects.toThrow();
+ expect((await cleanupSourceSnapshots(output)).removed).toEqual([]);
+ expect(
+ await readFile(
+ path.join(output, 'source-metadata/base-source/.stylex-tools/fixtures/Example/build.log'),
+ 'utf8',
+ ),
+ ).toBe('build details');
+ expect(
+ await readFile(
+ path.join(
+ output,
+ 'source-metadata/base-source/.stylex-dependencies/.stylex-tools/restore.log',
+ ),
+ 'utf8',
+ ),
+ ).toBe('pnpm failure details');
+ });
+
+ it('refuses symlinked source directories without touching their targets', async () => {
+ const output = await setup();
+ await symlink(path.join(output, 'base-source'), path.join(output, 'candidate-source'));
+ await expect(cleanupSourceSnapshots(output)).rejects.toThrow('REFUSE_SOURCE_CLEANUP_SYMLINK');
+ expect(await readFile(path.join(output, 'base-source/component.ts'), 'utf8')).toContain(
+ 'export',
+ );
+ });
+});
diff --git a/scripts/stylexMigration/verification/source/cleanupSnapshots.ts b/scripts/stylexMigration/verification/source/cleanupSnapshots.ts
new file mode 100644
index 00000000000..c44e687600f
--- /dev/null
+++ b/scripts/stylexMigration/verification/source/cleanupSnapshots.ts
@@ -0,0 +1,99 @@
+import { constants } from 'node:fs';
+import { copyFile, lstat, mkdir, readdir, realpath, rm } from 'node:fs/promises';
+import path from 'node:path';
+
+import { digestFile } from '../dependencies/dependencySnapshot';
+import { sha256, writeJson } from '../reporting/report';
+
+const names = ['base-source', 'candidate-source'] as const;
+const inputs = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', 'capsule.json'];
+const statIfPresent = async (file: string) => {
+ try {
+ return await lstat(file);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+};
+
+/** Only the two owned exports under a unique run directory are removable. */
+export const cleanupSourceSnapshots = async (output: string) => {
+ const root = await realpath(output);
+ const present: string[] = [];
+ // Validate every target before deleting any: refuse links, including partial runs.
+ for (const name of names) {
+ const file = path.join(root, name);
+ const stat = await statIfPresent(file);
+ if (!stat) continue;
+ if (stat.isSymbolicLink()) throw new Error('REFUSE_SOURCE_CLEANUP_SYMLINK');
+ if (!stat.isDirectory() || (await realpath(file)) !== file)
+ throw new Error('REFUSE_UNOWNED_SOURCE_CLEANUP');
+ present.push(name);
+ }
+ const metadata: Array<{ path: string; sha256: string }> = [];
+ for (const name of present) {
+ const preserve = async (relative: string) => {
+ const source = path.join(root, name, relative);
+ const stat = await statIfPresent(source);
+ if (!stat) return;
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 32 * 1024 ** 2)
+ throw new Error('UNSAFE_SOURCE_METADATA');
+ if (!(await realpath(source)).startsWith(path.join(root, name) + path.sep))
+ throw new Error('SOURCE_METADATA_ESCAPE');
+ const destination = path.join(root, 'source-metadata', name, relative);
+ await mkdir(path.dirname(destination), { recursive: true });
+ try {
+ await copyFile(source, destination, constants.COPYFILE_EXCL);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ if ((await digestFile(source)) !== (await digestFile(destination)))
+ throw new Error('SOURCE_METADATA_ALREADY_DIFFERENT', { cause: error });
+ }
+ metadata.push({
+ path: path.relative(root, destination),
+ sha256: await digestFile(destination),
+ });
+ };
+ for (const prefix of ['', '.stylex-dependencies/']) {
+ for (const input of inputs) {
+ await preserve(`${prefix}${input}`);
+ }
+ }
+ const preserveLogs = async (relative: string): Promise<void> => {
+ const directory = path.join(root, name, relative);
+ const stat = await statIfPresent(directory);
+ if (!stat) return;
+ if (stat.isSymbolicLink() || !stat.isDirectory())
+ throw new Error('UNSAFE_SOURCE_LOG_DIRECTORY');
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ if (entry.isSymbolicLink()) throw new Error('UNSAFE_SOURCE_LOG_SYMLINK');
+ if (entry.isFile() && entry.name.endsWith('.log'))
+ await preserve(path.join(relative, entry.name));
+ }
+ };
+ await preserveLogs('.stylex-tools');
+ await preserveLogs('.stylex-dependencies/.stylex-tools');
+ // Build workers write one log per fixture. Do not traverse pnpm caches.
+ const fixtures = path.join(root, name, '.stylex-tools/fixtures');
+ const fixtureStat = await statIfPresent(fixtures);
+ if (fixtureStat) {
+ if (!fixtureStat.isDirectory() || fixtureStat.isSymbolicLink())
+ throw new Error('UNSAFE_FIXTURE_LOG_DIRECTORY');
+ for (const fixture of await readdir(fixtures, { withFileTypes: true })) {
+ if (!fixture.isDirectory() || fixture.isSymbolicLink())
+ throw new Error('UNSAFE_FIXTURE_LOG_DIRECTORY');
+ await preserveLogs(path.join('.stylex-tools/fixtures', fixture.name));
+ }
+ }
+ await rm(path.join(root, name), { recursive: true });
+ }
+ return { metadata, metadataHash: sha256(JSON.stringify(metadata)), removed: present };
+};
+
+export const recordSourceCleanup = async (output: string) => {
+ const result = await cleanupSourceSnapshots(output);
+ await writeJson(output, 'source-cleanup.json', {
+ ...result,
+ retainedDiagnostics: 'source-metadata/<side>/.stylex-tools (including dependency capsule logs)',
+ policy: 'remove-owned-sources-after-run',
+ });
+};
diff --git a/scripts/stylexMigration/verification/types.ts b/scripts/stylexMigration/verification/types.ts
index 6ff12898e66..e23a9ac039e 100644
--- a/scripts/stylexMigration/verification/types.ts
+++ b/scripts/stylexMigration/verification/types.ts
@@ -1,78 +1,16 @@
-import { z } from 'zod';
-
-const nonempty = z.string().min(1).max(8192);
-const unique = <T>(values: T[]) => new Set(values).size === values.length;
-
-export const machineStatusSchema = z.enum(['PASS', 'FAIL', 'NEEDS_REVIEW', 'ERROR']);
-export type MachineStatus = z.infer<typeof machineStatusSchema>;
-
-export const coverageUnitSchema = z.strictObject({
- componentId: nonempty,
- fixtureIds: z.array(nonempty).refine(unique, 'Duplicate fixture ID'),
- id: nonempty,
- requiredKeys: z.array(nonempty).refine(unique, 'Duplicate coverage key'),
-});
-
-export const witnessSchema = z.strictObject({
- evidenceRefs: z.array(nonempty),
- fixtureId: nonempty,
- key: nonempty,
- probeId: nonempty,
- unitId: nonempty,
-});
-
-export const gateInputSchema = z.strictObject({
- errors: z.array(nonempty),
- findings: z
- .array(
- z.strictObject({
- confirmed: z.boolean(),
- id: nonempty,
- reasonCode: nonempty,
- severity: z.enum(['difference', 'review']),
- }),
- )
- .refine((values) => unique(values.map((value) => value.id)), 'Duplicate finding ID'),
- fixtures: z
- .array(
- z.strictObject({
- aaStable: z.boolean(),
- comparisons: z.number().int().nonnegative(),
- id: nonempty,
- nodeCount: z.number().int().nonnegative(),
- propertyReads: z.number().int().nonnegative(),
- }),
- )
- .refine((values) => unique(values.map((value) => value.id)), 'Duplicate fixture ID'),
- fullScope: z.boolean(),
- identityVerified: z.boolean(),
- pureStyleMigration: z.boolean(),
- units: z
- .array(coverageUnitSchema)
- .refine((values) => unique(values.map((value) => value.id)), 'Duplicate unit ID'),
- witnesses: z.array(witnessSchema),
-});
-
-export type GateInput = z.infer<typeof gateInputSchema>;
-export type CoverageUnit = z.infer<typeof coverageUnitSchema>;
-
-export interface CoverageSummary {
- machineResolvedUnits: number;
- missingKeys: string[];
- requiredKeys: number;
- reviewResolvedUnits: number;
- totalUnits: number;
- unresolvedUnitIds: string[];
- witnessedKeys: number;
+export interface VerificationFinding {
+ confirmed: boolean;
+ id: string;
+ reasonCode: string;
+ severity: 'difference' | 'review';
}
-export interface GateDecision {
- coverage: CoverageSummary;
- errors: string[];
- findings: GateInput['findings'];
- gateEligible: boolean;
- reasonCodes: string[];
- status: MachineStatus;
+export interface FixtureResult {
+ aaStable: boolean;
+ comparisons: number;
+ id: string;
+ nodeCount: number;
+ propertyReads: number;
}
export interface RevisionIdentity {
diff --git a/scripts/stylexMigration/verification/vitest.config.test.ts b/scripts/stylexMigration/verification/vitest.config.test.ts
index 3ea57e748f4..8f1778c01da 100644
--- a/scripts/stylexMigration/verification/vitest.config.test.ts
+++ b/scripts/stylexMigration/verification/vitest.config.test.ts
@@ -68,9 +68,8 @@ describe('local StyleX verification test discovery', () => {
expect(files).toEqual(
expect.arrayContaining([
'scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts',
- 'scripts/stylexMigration/verification/gate/gate.test.ts',
'scripts/stylexMigration/verification/vitest.config.test.ts',
- 'scripts/stylexMigration/verification/browser/snapshot.test.ts',
+ 'scripts/stylexMigration/verification/browser/screenshotEvidence.test.ts',
'scripts/stylexMigration/verification/__tests__/sxArguments.test.ts',
]),
);
diff --git a/src/components/ChatGroupWizard/ChatGroupWizard.tsx b/src/components/ChatGroupWizard/ChatGroupWizard.tsx
index ade26d33706..fe6c57576e9 100644
--- a/src/components/ChatGroupWizard/ChatGroupWizard.tsx
+++ b/src/components/ChatGroupWizard/ChatGroupWizard.tsx
@@ -671,7 +671,7 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(
</Flexbox>
<Flexbox horizontal align="center" gap={12}>
<div
- {...sx([isHostRemoved && styles.modelSelectDisabled], undefined, {
+ {...sx(isHostRemoved && styles.modelSelectDisabled, {
opacity: isHostRemoved ? 0.6 : 1,
})}
>
diff --git a/src/components/CodeEditorPane/index.tsx b/src/components/CodeEditorPane/index.tsx
index 25a60238d90..6a9c2ac5125 100644
--- a/src/components/CodeEditorPane/index.tsx
+++ b/src/components/CodeEditorPane/index.tsx
@@ -1,5 +1,7 @@
'use client';
+import './style.css';
+
import {
type CodeMirrorOptions,
type ICodeMirrorInstance,
@@ -13,7 +15,6 @@ import { useIsDark } from '@/hooks/useIsDark';
import { detectIndentStyle } from './indent';
import { getEditorLanguage } from './language';
import StatusBar, { type CursorPosition } from './StatusBar';
-import styles from './style.module.css';
/**
* The parts of the underlying CodeMirror 6 view that the compat wrapper does
@@ -214,8 +215,11 @@ const CodeEditorPane = memo<CodeEditorPaneProps>(
}, [isDark]);
return (
- <div className={`${styles.container} ${className ?? ''}`.trim()} style={style}>
- <div className={styles.editorArea}>
+ <div
+ className={`${'lobe-code-editor-pane-d8fecd5f-container'} ${className ?? ''}`.trim()}
+ style={style}
+ >
+ <div className={'lobe-code-editor-pane-d8fecd5f-editor-area'}>
<textarea className={'cm-textarea'} ref={textareaRef} />
</div>
{showStatusBar && (
diff --git a/src/components/CodeEditorPane/style.module.css b/src/components/CodeEditorPane/style.css
similarity index 63%
rename from src/components/CodeEditorPane/style.module.css
rename to src/components/CodeEditorPane/style.css
index bf4360ff24f..bdabb6d54c8 100644
--- a/src/components/CodeEditorPane/style.module.css
+++ b/src/components/CodeEditorPane/style.css
@@ -3,7 +3,7 @@
* emits (`.cm-editor.cm-editor`) so these rules win regardless of which style
* sheet the browser inserted last.
*/
-.container {
+.lobe-code-editor-pane-d8fecd5f-container {
overflow: hidden;
display: flex;
flex-direction: column;
@@ -14,32 +14,32 @@
background: var(--lobe-color-bg-container);
}
-.container :global(.cm-textarea) {
+.lobe-code-editor-pane-d8fecd5f-container .cm-textarea {
height: 0;
opacity: 0;
}
-.editorArea {
+.lobe-code-editor-pane-d8fecd5f-editor-area {
overflow: hidden;
flex: 1;
min-height: 0;
}
-.editorArea :global(.cm-editor) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor {
height: 100%;
padding-block: 0;
}
/* Own the vertical scroll here rather than in an outer wrapper, so the
gutter and the fold markers stay pinned while the text scrolls. */
-.editorArea :global(.cm-scroller) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-scroller {
overflow: auto;
font-variant-ligatures: none;
line-height: 20px;
}
-.editorArea :global(.cm-editor.cm-editor) span,
-.editorArea :global(.cm-editor.cm-editor) :global(.cm-line) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor span,
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor .cm-line {
font-family: var(--lobe-font-family-code);
font-size: 12px;
line-height: 20px;
@@ -47,12 +47,12 @@
/* Clicking below the last line should still land in the document, the way
every desktop editor behaves. */
-.editorArea :global(.cm-content) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-content {
min-height: 100%;
padding-block: 8px;
}
-.editorArea :global(.cm-gutters) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-gutters {
user-select: none;
border-inline-end: 1px solid var(--lobe-color-border-secondary);
background: var(--lobe-color-bg-container);
@@ -60,13 +60,13 @@
/* The bundled theme pads every line by 12px, which lands on top of the
gutter's own trailing space and pushes the code away from its number. */
-.editorArea :global(.cm-editor.cm-editor) :global(.cm-line) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor .cm-line {
padding-inline: 6px 12px;
}
/* The number sits closer to the code than to the pane edge: it labels the
line, so the eye should travel from it rightwards, not across a gap. */
-.editorArea :global(.cm-lineNumbers) :global(.cm-gutterElement) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-lineNumbers .cm-gutterElement {
min-width: 22px;
padding-inline: 16px 2px;
@@ -81,36 +81,36 @@
hard-coded near-white, in dark mode too, and qualifies both of them with
the editor class. Naming that class twice is what outranks it: otherwise
the focused line reads as a white band with its punctuation washed out. */
-.editorArea :global(.cm-editor.cm-editor) :global(.cm-activeLineGutter) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor .cm-activeLineGutter {
color: var(--lobe-color-text) !important;
background: transparent;
}
-.editorArea :global(.cm-editor.cm-editor) :global(.cm-activeLine) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor .cm-activeLine {
background: var(--lobe-color-fill-quaternary);
}
/* A focused editor gets the stronger cue; an unfocused one keeps a faint
marker so the caret position is still findable after a click elsewhere. */
-.editorArea :global(.cm-editor.cm-editor:not(.cm-focused)) :global(.cm-activeLine) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor:not(.cm-focused) .cm-activeLine {
background: transparent;
}
-.editorArea :global(.cm-matchingBracket),
-.editorArea :global(.cm-editor.cm-focused) :global(.cm-matchingBracket) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-matchingBracket,
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-focused .cm-matchingBracket {
border-radius: 2px;
background: var(--lobe-color-fill-secondary);
outline: 1px solid var(--lobe-color-border);
}
-.editorArea :global(.cm-nonmatchingBracket) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-nonmatchingBracket {
border-radius: 2px;
background: var(--lobe-color-error-bg);
}
/* Fold markers render as empty divs; the chevron is entirely ours. */
-.editorArea :global(.gutter-fold-open),
-.editorArea :global(.gutter-fold-close) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-open,
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-close {
cursor: pointer;
display: flex;
@@ -125,8 +125,8 @@
transition: opacity 0.15s;
}
-.editorArea :global(.gutter-fold-open)::before,
-.editorArea :global(.gutter-fold-close)::before {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-open::before,
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-close::before {
content: '';
width: 5px;
@@ -137,29 +137,29 @@
/* Pointing down: this range is expanded. Only offered on gutter hover, so
the gutter is not a column of permanent arrows. */
-.editorArea :global(.gutter-fold-open) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-open {
opacity: 0;
}
-.editorArea :global(.gutter-fold-open)::before {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-open::before {
transform: translateY(-1px) rotate(45deg);
}
/* Pointing right: content is hidden here, so this one always shows. */
-.editorArea :global(.gutter-fold-close)::before {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-close::before {
transform: translateX(-2px) rotate(-45deg);
}
-.editorArea :global(.gutter-fold-open):hover,
-.editorArea :global(.gutter-fold-close):hover {
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-open:hover,
+.lobe-code-editor-pane-d8fecd5f-editor-area .gutter-fold-close:hover {
color: var(--lobe-color-text);
}
-.editorArea :global(.cm-gutters):hover :global(.gutter-fold-open) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-gutters:hover .gutter-fold-open {
opacity: 1;
}
-.editorArea :global(.cm-editor.cm-editor) :global(.cm-foldPlaceholder) {
+.lobe-code-editor-pane-d8fecd5f-editor-area .cm-editor.cm-editor .cm-foldPlaceholder {
width: auto;
height: auto;
padding-inline: 6px;
diff --git a/src/components/CommentList/CommentItem.module.css b/src/components/CommentList/CommentItem.css
similarity index 53%
rename from src/components/CommentList/CommentItem.module.css
rename to src/components/CommentList/CommentItem.css
index 82adfce8dae..ad91198019d 100644
--- a/src/components/CommentList/CommentItem.module.css
+++ b/src/components/CommentList/CommentItem.css
@@ -1,28 +1,28 @@
-.content {
+.lobe-comment-item-3223608e-content {
font-size: 16px;
line-height: 1.56;
color: var(--lobe-color-text-secondary);
}
-.content p {
+.lobe-comment-item-3223608e-content p {
margin-block: 0;
}
-.content p + p {
+.lobe-comment-item-3223608e-content p + p {
margin-block-start: 0.72em;
}
-.content a {
+.lobe-comment-item-3223608e-content a {
color: var(--lobe-color-link);
}
-.content strong {
+.lobe-comment-item-3223608e-content strong {
font-weight: 600;
color: var(--lobe-color-text);
}
@media (width <= 575.98px) {
- .content {
+ .lobe-comment-item-3223608e-content {
font-size: 15px;
}
}
diff --git a/src/components/CommentList/CommentItem.tsx b/src/components/CommentList/CommentItem.tsx
index 83535fdcf84..3420b18f275 100644
--- a/src/components/CommentList/CommentItem.tsx
+++ b/src/components/CommentList/CommentItem.tsx
@@ -1,5 +1,7 @@
'use client';
+import './CommentItem.css';
+
import { AgentIcon } from '@lobehub/icons';
import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
@@ -11,8 +13,6 @@ import { useTranslation } from 'react-i18next';
import Rate from '@/components/RatingOverview/Rate';
import { type SkillCommentItem } from '@/types/discover';
-import moduleStyles from './CommentItem.module.css';
-
const styles = stylex.create({
author: {
fontSize: { default: '16px', [media.sm]: '15px' },
@@ -105,7 +105,7 @@ const CommentItem = memo<{ item: SkillCommentItem }>(({ item }) => {
</Flexbox>
<Text className={stylex.props(styles.date).className}>{createdAt}</Text>
</Flexbox>
- <Markdown className={moduleStyles.content} variant={'chat'}>
+ <Markdown className={'lobe-comment-item-3223608e-content'} variant={'chat'}>
{item.content}
</Markdown>
</Flexbox>
diff --git a/src/components/Descriptions/index.tsx b/src/components/Descriptions/index.tsx
index 513a79af561..bd5334d353b 100644
--- a/src/components/Descriptions/index.tsx
+++ b/src/components/Descriptions/index.tsx
@@ -84,19 +84,14 @@ const Descriptions = memo<DescriptionsProps>(
return (
<>
{title && <h3 style={{ marginTop: 12 }}>{title}</h3>}
- <Grid
- gap={0}
- maxItemWidth={450}
- {...sx([bordered && styles.bordered], className)}
- {...rest}
- >
+ <Grid gap={0} maxItemWidth={450} {...sx(bordered && styles.bordered, className)} {...rest}>
{items.map((item) => (
<Flexbox
horizontal
align={wrap ? 'flex-start' : 'center'}
flex={1}
key={item.key}
- {...sx([bordered && styles.cell], cx(item.className, classNames?.item))}
+ {...sx(bordered && styles.cell, cx(item.className, classNames?.item))}
style={{
overflow: wrap ? undefined : 'hidden',
position: 'relative',
@@ -109,7 +104,7 @@ const Descriptions = memo<DescriptionsProps>(
align={'center'}
flex={'none'}
gap={6}
- {...sx([bordered && styles.label])}
+ {...sx(bordered && styles.label)}
paddingBlock={bordered ? 12 : 4}
paddingInline={bordered ? 16 : 0}
style={{ height: '100%', position: 'relative' }}
diff --git a/src/components/DiscreteSlider/index.tsx b/src/components/DiscreteSlider/index.tsx
index c00cab8dcc0..87a4c54e1b2 100644
--- a/src/components/DiscreteSlider/index.tsx
+++ b/src/components/DiscreteSlider/index.tsx
@@ -103,13 +103,13 @@ const DiscreteSlider = memo<DiscreteSliderProps>(
);
return (
- <Flexbox gap={6} {...sx([styles.root], className, style)}>
+ <Flexbox gap={6} {...sx(styles.root, className, style)}>
{formatTooltip && currentOption ? (
<Tooltip title={formatTooltip(currentOption.value)}>{slider}</Tooltip>
) : (
slider
)}
- <div {...sx([styles.labels], undefined, { gridTemplateColumns })}>
+ <div {...sx(styles.labels, { gridTemplateColumns })}>
{options.map((option, index) => {
const isFirst = index === 0;
const isLast = index === options.length - 1;
@@ -121,7 +121,7 @@ const DiscreteSlider = memo<DiscreteSliderProps>(
aria-label={option.ariaLabel}
disabled={disabled}
key={option.value}
- {...sx([styles.label, index === currentIndex && styles.selectedLabel], undefined, {
+ {...sx(styles.label, index === currentIndex && styles.selectedLabel, {
textAlign,
...option.style,
})}
diff --git a/src/components/DotsLoading/index.tsx b/src/components/DotsLoading/index.tsx
index 8f5db7d10a6..d7afbab0d10 100644
--- a/src/components/DotsLoading/index.tsx
+++ b/src/components/DotsLoading/index.tsx
@@ -47,10 +47,10 @@ const DotsLoading = memo<DotsLoadingProps>(({ size = 4, gap = 3, color, classNam
} as CSSProperties;
return (
- <div {...sx([styles.container], className, { ...cssVars, ...style })}>
- <div {...sx([styles.dot], undefined, { animationDelay: '0s' })} />
- <div {...sx([styles.dot], undefined, { animationDelay: '0.15s' })} />
- <div {...sx([styles.dot], undefined, { animationDelay: '0.3s' })} />
+ <div {...sx(styles.container, className, { ...cssVars, ...style })}>
+ <div {...sx(styles.dot, { animationDelay: '0s' })} />
+ <div {...sx(styles.dot, { animationDelay: '0.15s' })} />
+ <div {...sx(styles.dot, { animationDelay: '0.3s' })} />
</div>
);
});
diff --git a/src/components/DragUploadZone/index.tsx b/src/components/DragUploadZone/index.tsx
index 2530c84877f..c78ea708ffb 100644
--- a/src/components/DragUploadZone/index.tsx
+++ b/src/components/DragUploadZone/index.tsx
@@ -197,17 +197,14 @@ const DragUploadZone = memo<DragUploadZoneProps>(
const tone = isLocalPathReferenceOverlay ? LOCAL_PATH_TONE : DEFAULT_TONE;
return (
- <div {...sx([styles.container], className, style)} {...getContainerProps()}>
+ <div {...sx(styles.container, className, style)} {...getContainerProps()}>
{children}
{showOverlay && (
<div {...stylex.props(styles.overlay)}>
<div
{...sx(
- [
- styles.overlayContent,
- isLocalPathReferenceOverlay && styles.overlayContentLocalPath,
- ],
- undefined,
+ styles.overlayContent,
+ isLocalPathReferenceOverlay && styles.overlayContentLocalPath,
{ minHeight: overlayMinHeight },
)}
>
diff --git a/src/components/Editor/AutoSaveHint.tsx b/src/components/Editor/AutoSaveHint.tsx
index f45764b75b2..52cf4e6b3d9 100644
--- a/src/components/Editor/AutoSaveHint.tsx
+++ b/src/components/Editor/AutoSaveHint.tsx
@@ -64,7 +64,7 @@ const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTi
if (saveStatus === 'saving')
return (
- <span {...sx(styles.hint, undefined, style)}>
+ <span {...sx(styles.hint, style)}>
<Spin size="small" />
{t('autoSave.saving')}
</span>
@@ -72,7 +72,7 @@ const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTi
if (saveStatus === 'failed')
return (
- <span {...sx([styles.hint, styles.failed], undefined, style)} role="alert">
+ <span {...sx(styles.hint, styles.failed, style)} role="alert">
<Icon icon={TriangleAlertIcon} size={14} />
{t('autoSave.failed')}
{onRetry && (
@@ -87,7 +87,7 @@ const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTi
);
return (
- <span {...sx(styles.hint, undefined, style)}>
+ <span {...sx(styles.hint, style)}>
<Icon icon={CloudIcon} size={14} />
{saveStatus === 'saved' && lastUpdatedTime
? `${t('autoSave.saved')} ${dayjs(lastUpdatedTime).fromNow()}`
diff --git a/src/components/FormAction/index.tsx b/src/components/FormAction/index.tsx
index 5f82b26d839..cdf359a7e7d 100644
--- a/src/components/FormAction/index.tsx
+++ b/src/components/FormAction/index.tsx
@@ -39,7 +39,7 @@ const FormAction = memo<
...rest
}) => {
return (
- <Center gap={gap} {...sx([styles.form], className)} {...rest}>
+ <Center gap={gap} {...sx(styles.form, className)} {...rest}>
<Avatar
animation={animation}
avatar={avatar}
diff --git a/src/components/GalleyGrid/Grid.tsx b/src/components/GalleyGrid/Grid.tsx
index ebab441ed6a..c50480c07e8 100644
--- a/src/components/GalleyGrid/Grid.tsx
+++ b/src/components/GalleyGrid/Grid.tsx
@@ -1,9 +1,10 @@
+import './style.css';
+
import { cx, Flexbox } from '@lobehub/ui';
import { type CSSProperties, type ReactNode } from 'react';
import { memo, useMemo } from 'react';
import { MAX_SIZE_DESKTOP, MIN_IMAGE_SIZE } from './style';
-import styles from './style.module.css';
interface GridProps {
children: ReactNode;
@@ -38,7 +39,7 @@ const Grid = memo<GridProps>(
return (
<Flexbox
horizontal
- className={cx(styles.container, className)}
+ className={cx('lobe-galley-grid-17c2ab70-container', className)}
gap={gap}
style={{
...cssVariables,
diff --git a/src/components/GalleyGrid/style.module.css b/src/components/GalleyGrid/style.css
similarity index 84%
rename from src/components/GalleyGrid/style.module.css
rename to src/components/GalleyGrid/style.css
index 01824cd9313..693466dc629 100644
--- a/src/components/GalleyGrid/style.module.css
+++ b/src/components/GalleyGrid/style.css
@@ -1,4 +1,4 @@
-.container {
+.lobe-galley-grid-17c2ab70-container {
display: grid;
grid-gap: var(--galley-grid-gap, 6px);
grid-template-columns: repeat(var(--galley-grid-col, 3), 1fr);
@@ -7,7 +7,7 @@
max-width: var(--galley-grid-max, 200px);
}
-.container > div {
+.lobe-galley-grid-17c2ab70-container > div {
width: 100%;
min-width: var(--galley-grid-min, 64px);
min-height: var(--galley-grid-min, 64px);
diff --git a/src/components/GeneratingBorder/index.tsx b/src/components/GeneratingBorder/index.tsx
index eb963a8b31f..5afc46e9a83 100644
--- a/src/components/GeneratingBorder/index.tsx
+++ b/src/components/GeneratingBorder/index.tsx
@@ -81,7 +81,7 @@ export interface GeneratingBorderProps {
*/
const GeneratingBorder = memo<GeneratingBorderProps>(
({ children, className, generating, style }) => (
- <Flexbox {...sx([styles.shell, generating && styles.shellGenerating], className, style)}>
+ <Flexbox {...sx(styles.shell, generating && styles.shellGenerating, className, style)}>
{children}
</Flexbox>
),
diff --git a/src/components/GuideModal/GuideModal.css b/src/components/GuideModal/GuideModal.css
new file mode 100644
index 00000000000..3b88f1274af
--- /dev/null
+++ b/src/components/GuideModal/GuideModal.css
@@ -0,0 +1,8 @@
+.lobe-guide-modal-92efaf88-body h3 {
+ margin: 0;
+ font-weight: bold;
+}
+
+.lobe-guide-modal-92efaf88-body p {
+ margin: 0;
+}
diff --git a/src/components/GuideModal/GuideModal.module.css b/src/components/GuideModal/GuideModal.module.css
deleted file mode 100644
index 4ccf180758a..00000000000
--- a/src/components/GuideModal/GuideModal.module.css
+++ /dev/null
@@ -1,8 +0,0 @@
-.body h3 {
- margin: 0;
- font-weight: bold;
-}
-
-.body p {
- margin: 0;
-}
diff --git a/src/components/GuideModal/index.tsx b/src/components/GuideModal/index.tsx
index 8fe7e09cfc9..b4de7ae0381 100644
--- a/src/components/GuideModal/index.tsx
+++ b/src/components/GuideModal/index.tsx
@@ -1,11 +1,11 @@
'use client';
+import './GuideModal.css';
+
import { Button, createModal, Flexbox, type ModalInstance, useModalContext } from '@lobehub/ui';
import { type ReactNode } from 'react';
import { memo } from 'react';
-import styles from './GuideModal.module.css';
-
interface GuideModalContentProps {
cancelText?: ReactNode;
cover: ReactNode;
@@ -31,7 +31,7 @@ const GuideModalContent = memo<GuideModalContentProps>(
};
return (
- <Flexbox className={styles.body}>
+ <Flexbox className={'lobe-guide-modal-92efaf88-body'}>
{cover}
<Flexbox gap={4} padding={16}>
<h3>{title}</h3>
diff --git a/src/components/ImageItem/index.tsx b/src/components/ImageItem/index.tsx
index e08c6957b70..c9b51358d59 100644
--- a/src/components/ImageItem/index.tsx
+++ b/src/components/ImageItem/index.tsx
@@ -89,7 +89,7 @@ const ImageItem = memo<ImageItemProps>(
)
}
classNames={{
- wrapper: sx([styles.image, editable && styles.editableImage], className).className,
+ wrapper: sx(styles.image, editable && styles.editableImage, className).className,
}}
style={{
aspectRatio,
diff --git a/src/components/InlineTable/InlineTable.css b/src/components/InlineTable/InlineTable.css
new file mode 100644
index 00000000000..5b3cfa268f8
--- /dev/null
+++ b/src/components/InlineTable/InlineTable.css
@@ -0,0 +1,27 @@
+.lobe-inline-table-b75cf865-table table {
+ font-size: 13px;
+}
+
+.lobe-inline-table-b75cf865-table th {
+ background: transparent;
+ box-shadow: inset 0 999px 0 var(--lobe-color-fill-quaternary);
+}
+
+.lobe-inline-table-b75cf865-table td {
+ border: none;
+ background: transparent;
+}
+
+.lobe-inline-table-b75cf865-table tr:hover > td {
+ background: var(--lobe-color-fill-quaternary);
+}
+
+.lobe-inline-table-b75cf865-table tr td:first-child,
+.lobe-inline-table-b75cf865-table tr th:first-child {
+ padding-inline-start: 24px;
+}
+
+.lobe-inline-table-b75cf865-table tr td:last-child,
+.lobe-inline-table-b75cf865-table tr th:last-child {
+ padding-inline-end: 24px;
+}
diff --git a/src/components/InlineTable/InlineTable.module.css b/src/components/InlineTable/InlineTable.module.css
deleted file mode 100644
index 876ffdff1f7..00000000000
--- a/src/components/InlineTable/InlineTable.module.css
+++ /dev/null
@@ -1,27 +0,0 @@
-.table table {
- font-size: 13px;
-}
-
-.table th {
- background: transparent;
- box-shadow: inset 0 999px 0 var(--lobe-color-fill-quaternary);
-}
-
-.table td {
- border: none;
- background: transparent;
-}
-
-.table tr:hover > td {
- background: var(--lobe-color-fill-quaternary);
-}
-
-.table tr td:first-child,
-.table tr th:first-child {
- padding-inline-start: 24px;
-}
-
-.table tr td:last-child,
-.table tr th:last-child {
- padding-inline-end: 24px;
-}
diff --git a/src/components/InlineTable/index.tsx b/src/components/InlineTable/index.tsx
index 58857e531ec..45ef59a3d93 100644
--- a/src/components/InlineTable/index.tsx
+++ b/src/components/InlineTable/index.tsx
@@ -1,10 +1,10 @@
+import './InlineTable.css';
+
import { cx, Table, type TableProps } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import { sx } from '@/styles/sx';
-import styles from './InlineTable.module.css';
-
const hoverStyles = stylex.create({
hoverToActive: {
opacity: { 'default': 0.6, ':hover': 1 },
@@ -22,7 +22,10 @@ const InlineTable = <T extends object>({
pagination={false}
size={'small'}
className={
- sx([hoverToActive && hoverStyles.hoverToActive], cx(styles.table, className)).className
+ sx(
+ hoverToActive && hoverStyles.hoverToActive,
+ cx('lobe-inline-table-b75cf865-table', className),
+ ).className
}
{...rest}
/>
diff --git a/src/components/LiteTable/index.tsx b/src/components/LiteTable/index.tsx
index f44445040b3..79efd8e6c6b 100644
--- a/src/components/LiteTable/index.tsx
+++ b/src/components/LiteTable/index.tsx
@@ -411,7 +411,7 @@ const LiteTableInner = <RecordType,>({
<tr>
{columns.map((column) => (
<th
- {...sx(wide ? styles.wideHeading : styles.heading, undefined, {
+ {...sx(wide ? styles.wideHeading : styles.heading, {
width: column.width,
})}
key={column.key}
diff --git a/src/components/Loading/BrandTextLoading/index.module.css b/src/components/Loading/BrandTextLoading/index.css
similarity index 74%
rename from src/components/Loading/BrandTextLoading/index.module.css
rename to src/components/Loading/BrandTextLoading/index.css
index 6b4d4c2620e..17eb28264ae 100644
--- a/src/components/Loading/BrandTextLoading/index.module.css
+++ b/src/components/Loading/BrandTextLoading/index.css
@@ -1,4 +1,4 @@
-.container {
+.lobe-brand-text-loading-15b392f3-container {
--brand-text-color: var(--colorText, #1f1f1f);
--brand-muted-color: var(--colorTextSecondary, #8c8c8c);
--brand-border-color: var(--colorBorder, #d9d9d9);
@@ -15,14 +15,14 @@
height: 100dvh;
}
-[data-theme='dark'] .container {
+[data-theme='dark'] .lobe-brand-text-loading-15b392f3-container {
--brand-text-color: var(--colorText, #f0f0f0);
--brand-muted-color: var(--colorTextSecondary, #a6a6a6);
--brand-border-color: var(--colorBorder, #424242);
--brand-tag-bg: var(--colorFillTertiary, rgb(255 255 255 / 8%));
}
-.brand {
+.lobe-brand-text-loading-15b392f3-brand {
display: flex;
gap: 12px;
align-items: center;
@@ -32,21 +32,12 @@
opacity: 0.6;
}
-.brand :global(.lobe-brand-loading) {
+.lobe-brand-text-loading-15b392f3-brand .lobe-brand-loading {
display: block;
color: inherit;
}
-.debug {
- display: flex;
- flex-direction: column;
- gap: 4px;
- align-items: center;
-
- padding: 16px;
-}
-
-.debugRow {
+.lobe-brand-text-loading-15b392f3-debug-row {
display: flex;
gap: 8px;
align-items: center;
@@ -55,13 +46,13 @@
color: var(--brand-muted-color);
}
-.debugRow code {
+.lobe-brand-text-loading-15b392f3-debug-row code {
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
monospace;
}
-.debugTag {
+.lobe-brand-text-loading-15b392f3-debug-tag {
display: inline-flex;
align-items: center;
@@ -72,11 +63,6 @@
background: var(--brand-tag-bg);
}
-.debugTag code {
+.lobe-brand-text-loading-15b392f3-debug-tag code {
color: var(--brand-text-color);
}
-
-.debugHint {
- font-size: 12px;
- color: var(--brand-muted-color);
-}
diff --git a/src/components/Loading/BrandTextLoading/index.tsx b/src/components/Loading/BrandTextLoading/index.tsx
index 53e9bc4e04d..ca14991ca0b 100644
--- a/src/components/Loading/BrandTextLoading/index.tsx
+++ b/src/components/Loading/BrandTextLoading/index.tsx
@@ -1,9 +1,22 @@
+import './index.css';
+
import { BrandLoading, LobeHubText } from '@lobehub/ui/brand';
+import * as stylex from '@stylexjs/stylex';
import { isCustomBranding } from '@/const/version';
import CircleLoading from '../CircleLoading';
-import styles from './index.module.css';
+
+const stylesAtomic = stylex.create({
+ debug: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '16px',
+ },
+ debugHint: { fontSize: '12px', color: 'var(--brand-muted-color)' },
+});
interface BrandTextLoadingProps {
debugId: string;
@@ -12,7 +25,7 @@ interface BrandTextLoadingProps {
const BrandTextLoading = ({ debugId }: BrandTextLoadingProps) => {
if (isCustomBranding)
return (
- <div className={styles.container}>
+ <div className={'lobe-brand-text-loading-15b392f3-container'}>
<CircleLoading />
</div>
);
@@ -20,19 +33,19 @@ const BrandTextLoading = ({ debugId }: BrandTextLoadingProps) => {
const showDebug = process.env.NODE_ENV === 'development' && debugId;
return (
- <div className={styles.container}>
- <div aria-label="Loading" className={styles.brand} role="status">
+ <div className={'lobe-brand-text-loading-15b392f3-container'}>
+ <div aria-label="Loading" className={'lobe-brand-text-loading-15b392f3-brand'} role="status">
<BrandLoading size={40} text={LobeHubText} />
</div>
{showDebug && (
- <div className={styles.debug}>
- <div className={styles.debugRow}>
+ <div {...stylex.props(stylesAtomic['debug'])}>
+ <div className={'lobe-brand-text-loading-15b392f3-debug-row'}>
<code>Debug ID:</code>
- <span className={styles.debugTag}>
+ <span className={'lobe-brand-text-loading-15b392f3-debug-tag'}>
<code>{debugId}</code>
</span>
</div>
- <div className={styles.debugHint}>only visible in development</div>
+ <div {...stylex.props(stylesAtomic['debugHint'])}>only visible in development</div>
</div>
)}
</div>
diff --git a/src/components/Loading/SkeletonLoading/index.tsx b/src/components/Loading/SkeletonLoading/index.tsx
index c827ed7085e..1f6485a331f 100644
--- a/src/components/Loading/SkeletonLoading/index.tsx
+++ b/src/components/Loading/SkeletonLoading/index.tsx
@@ -12,7 +12,7 @@ const styles = stylex.create({
});
const SkeletonLoading = memo<{ className?: string }>(({ className }) => (
- <ArticleSkeleton className={sx([styles.root], className).className} rows={8} />
+ <ArticleSkeleton className={sx(styles.root, className).className} rows={8} />
));
export default SkeletonLoading;
diff --git a/src/components/MemberSelectionModal/MemberSelectionModal.tsx b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
index 8e1a9f58a8e..955877a5074 100644
--- a/src/components/MemberSelectionModal/MemberSelectionModal.tsx
+++ b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
@@ -463,11 +463,9 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
</Flexbox>
<Flexbox horizontal align="center" gap={12}>
<div
- {...sx(
- [styles.hostModelSelect, isHostRemoved && styles.modelSelectDisabled],
- undefined,
- { opacity: isHostRemoved ? 0.6 : 1 },
- )}
+ {...sx(styles.hostModelSelect, isHostRemoved && styles.modelSelectDisabled, {
+ opacity: isHostRemoved ? 0.6 : 1,
+ })}
>
<ModelSelect
requiredAbilities={['functionCall']}
diff --git a/src/components/Menu/Menu.css b/src/components/Menu/Menu.css
new file mode 100644
index 00000000000..1dc0cfd2665
--- /dev/null
+++ b/src/components/Menu/Menu.css
@@ -0,0 +1,3 @@
+.lobe-menu-8b666d35-inset > li:not([role='separator']) {
+ margin-inline: 4px;
+}
diff --git a/src/components/Menu/Menu.module.css b/src/components/Menu/Menu.module.css
deleted file mode 100644
index f83d1f32004..00000000000
--- a/src/components/Menu/Menu.module.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.inset > li:not([role='separator']) {
- margin-inline: 4px;
-}
diff --git a/src/components/Menu/index.tsx b/src/components/Menu/index.tsx
index 5d1dbc8dc26..566d816e897 100644
--- a/src/components/Menu/index.tsx
+++ b/src/components/Menu/index.tsx
@@ -1,15 +1,15 @@
+import './Menu.css';
+
import { cx, List, type ListProps } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import { memo } from 'react';
-import styles from './Menu.module.css';
-
export type MenuProps = ListProps;
const Menu = memo<MenuProps>(
({ className, compact, selectable = false, styles: customStyles, ...rest }) => (
<List
- className={cx(!compact && styles.inset, className)}
+ className={cx(!compact && 'lobe-menu-8b666d35-inset', className)}
compact={compact}
selectable={selectable}
styles={
diff --git a/src/components/Notification/index.tsx b/src/components/Notification/index.tsx
index 4883929cec8..f2433e0ee07 100644
--- a/src/components/Notification/index.tsx
+++ b/src/components/Notification/index.tsx
@@ -77,7 +77,7 @@ const Notification = memo<NotificationProps>(
<Flexbox
height={height}
width={mobile ? 'calc(100% - 16px)' : width}
- {...sx([styles.container, mobile && styles.mobileContainer], className)}
+ {...sx(styles.container, mobile && styles.mobileContainer, className)}
{...rest}
>
{showCloseIcon && (
@@ -92,7 +92,8 @@ const Notification = memo<NotificationProps>(
gap={16}
padding={'20px 20px 16px'}
{...sx(
- [styles.wrapper, isDarkMode ? styles.wrapperDark : styles.wrapperLight],
+ styles.wrapper,
+ isDarkMode ? styles.wrapperDark : styles.wrapperLight,
wrapperClassName,
)}
{...restWrapper}
diff --git a/src/components/PublishedTime.tsx b/src/components/PublishedTime.tsx
index 07bdc667715..022c59a5ac0 100644
--- a/src/components/PublishedTime.tsx
+++ b/src/components/PublishedTime.tsx
@@ -43,8 +43,9 @@ interface PublishedTimeProps {
date: string;
style?: CSSProperties;
template?: string;
+ xstyle?: stylex.StyleXStyles;
}
-const PublishedTime: FC<PublishedTimeProps> = ({ date, style, className, template }) => {
+const PublishedTime: FC<PublishedTimeProps> = ({ date, style, className, template, xstyle }) => {
const { t } = useTranslation('common');
const time = formatDate(date, t as (key: string) => string, template);
@@ -52,7 +53,7 @@ const PublishedTime: FC<PublishedTimeProps> = ({ date, style, className, templat
<time
aria-label={'published-date'}
dateTime={formatTime(date)}
- {...sx([styles.time], className, style)}
+ {...sx(styles.time, xstyle, className, style)}
>
{time}
</time>
diff --git a/src/components/RatingOverview/Rate.tsx b/src/components/RatingOverview/Rate.tsx
index d32d8b32499..cf13690a97a 100644
--- a/src/components/RatingOverview/Rate.tsx
+++ b/src/components/RatingOverview/Rate.tsx
@@ -9,7 +9,7 @@ const styles = stylex.create({
});
const Rate = memo<RateProps>(({ className, size = 16, ...props }) => (
- <BaseRate allowHalf readOnly size={size} {...sx([styles.rate], className)} {...props} />
+ <BaseRate allowHalf readOnly size={size} {...sx(styles.rate, className)} {...props} />
));
export default Rate;
diff --git a/src/components/Skeleton/Conversation/Container.tsx b/src/components/Skeleton/Conversation/Container.tsx
index e4b22bc25a4..7f77dcbe9c8 100644
--- a/src/components/Skeleton/Conversation/Container.tsx
+++ b/src/components/Skeleton/Conversation/Container.tsx
@@ -25,7 +25,7 @@ const ConversationSkeletonContainer = ({
return (
<Flexbox aria-busy flex={flex} height={height} style={{ minHeight: 0 }} width={'100%'}>
<Flexbox
- {...sx([styles.container], className)}
+ {...sx(styles.container, className)}
flex={flex}
height={height}
paddingInline={16}
diff --git a/src/components/Skeleton/Settings/Section.module.css b/src/components/Skeleton/Settings/Section.css
similarity index 80%
rename from src/components/Skeleton/Settings/Section.module.css
rename to src/components/Skeleton/Settings/Section.css
index 1f3402aaf03..215aee23ef1 100644
--- a/src/components/Skeleton/Settings/Section.module.css
+++ b/src/components/Skeleton/Settings/Section.css
@@ -1,5 +1,5 @@
/* A loaded settings form renders its fields flush in the group body (each field
pads itself), while a bare `Form.Group` pads the body by 16px on both ends. */
-.group > :last-child {
+.lobe-section-96565f37-group > :last-child {
padding-block: 0;
}
diff --git a/src/components/Skeleton/Settings/Section.tsx b/src/components/Skeleton/Settings/Section.tsx
index 6698a4aead6..4a910be7d81 100644
--- a/src/components/Skeleton/Settings/Section.tsx
+++ b/src/components/Skeleton/Settings/Section.tsx
@@ -1,12 +1,13 @@
'use client';
+import './Section.css';
+
import { Flexbox } from '@lobehub/ui';
import { Form } from '@lobehub/ui/form';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import SkeletonBar from '../Bar';
-import moduleStyles from './Section.module.css';
const styles = stylex.create({
divider: {
@@ -88,7 +89,7 @@ const Group = ({
withDesc = true,
}: SettingsSectionSkeletonGroup) => (
<Form.Group
- className={moduleStyles.group}
+ className={'lobe-section-96565f37-group'}
collapsible={false}
variant={'filled'}
title={
diff --git a/src/components/Skeleton/Settings/Sections.css b/src/components/Skeleton/Settings/Sections.css
new file mode 100644
index 00000000000..4d09657736e
--- /dev/null
+++ b/src/components/Skeleton/Settings/Sections.css
@@ -0,0 +1,7 @@
+.lobe-sections-05ee388b-flush {
+ overflow: hidden;
+}
+
+.lobe-sections-05ee388b-flush [data-form-group-body] {
+ padding: 0;
+}
diff --git a/src/components/Skeleton/Settings/Sections.module.css b/src/components/Skeleton/Settings/Sections.module.css
deleted file mode 100644
index a708d7d7cd6..00000000000
--- a/src/components/Skeleton/Settings/Sections.module.css
+++ /dev/null
@@ -1,7 +0,0 @@
-.flush {
- overflow: hidden;
-}
-
-.flush [data-form-group-body] {
- padding: 0;
-}
diff --git a/src/components/Skeleton/Settings/Sections.tsx b/src/components/Skeleton/Settings/Sections.tsx
index 38f0ac4997d..07b12f17475 100644
--- a/src/components/Skeleton/Settings/Sections.tsx
+++ b/src/components/Skeleton/Settings/Sections.tsx
@@ -1,5 +1,7 @@
'use client';
+import './Sections.css';
+
import { Flexbox } from '@lobehub/ui';
import { Form } from '@lobehub/ui/form';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
@@ -12,7 +14,6 @@ import type { RouteSkeletonProps } from '@/spa/router/routeMeta';
import { sx } from '@/styles/sx';
import SkeletonBar from '../Bar';
-import moduleStyles from './Sections.module.css';
/** Shared head options of every section rendered as a filled `Form.Group`. */
interface GroupHeadOptions {
@@ -159,7 +160,7 @@ const Group = ({
titleWidth,
}: GroupHeadOptions & { children: ReactNode; flush?: boolean }) => (
<Form.Group
- className={flush ? moduleStyles.flush : undefined}
+ className={flush ? 'lobe-sections-05ee388b-flush' : undefined}
collapsible={false}
desc={desc ? <GroupDesc /> : undefined}
extra={extra ? <SkeletonBar height={32} width={120} /> : undefined}
@@ -266,9 +267,7 @@ const Tiles = ({
tileHeight: number;
tiles: number;
}) => (
- <div
- {...sx([styles.grid], undefined, { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` })}
- >
+ <div {...sx(styles.grid, { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` })}>
{Array.from({ length: tiles }).map((_, index) => (
<Flexbox
horizontal
@@ -407,7 +406,7 @@ const CardGrid = ({
size: 'large' | 'small';
}) => (
<div
- {...sx([styles.grid], undefined, {
+ {...sx(styles.grid, {
gap,
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
})}
diff --git a/src/components/TablePagination/index.tsx b/src/components/TablePagination/index.tsx
index 1632e700211..b7e680cc7bb 100644
--- a/src/components/TablePagination/index.tsx
+++ b/src/components/TablePagination/index.tsx
@@ -101,7 +101,7 @@ const TablePagination = memo<TablePaginationProps>(
align={'center'}
gap={12}
justify={'space-between'}
- {...sx([styles.root], className)}
+ {...sx(styles.root, className)}
>
<span {...stylex.props(styles.total)}>
{t('table.pagination.range', {
diff --git a/src/components/TailMarquee/index.tsx b/src/components/TailMarquee/index.tsx
index b505cbdb06c..6354a9ef943 100644
--- a/src/components/TailMarquee/index.tsx
+++ b/src/components/TailMarquee/index.tsx
@@ -180,7 +180,7 @@ const TailMarquee = ({ children, className, style }: TailMarqueeProps) => {
data-revealing={revealing || undefined}
ref={containerRef}
title={overflow > 0 ? fullText : undefined}
- {...sx([styles.container, overflow > 0 && styles.overflowing], className, {
+ {...sx(styles.container, overflow > 0 && styles.overflowing, className, {
...style,
'--tail-marquee-duration': `${duration}s`,
'--tail-marquee-offset': `${overflow}px`,
diff --git a/src/features/Acceptance/Report/TerminalEvidence/player.css b/src/features/Acceptance/Report/TerminalEvidence/player.css
new file mode 100644
index 00000000000..2f0852e98ca
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/player.css
@@ -0,0 +1,3 @@
+.lobe-player-15569863-screen .xterm {
+ width: max-content;
+}
diff --git a/src/features/Acceptance/Report/TerminalEvidence/player.module.css b/src/features/Acceptance/Report/TerminalEvidence/player.module.css
deleted file mode 100644
index 35fe9588c58..00000000000
--- a/src/features/Acceptance/Report/TerminalEvidence/player.module.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.screen :global(.xterm) {
- width: max-content;
- }
diff --git a/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts b/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts
index 6a0736839a4..a4cdedb175d 100644
--- a/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts
+++ b/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts
@@ -1,9 +1,9 @@
+import './player.css';
+
import { cx } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import relational from './player.module.css';
-
const definitions = stylex.create({
screen: {
overflow: 'auto',
@@ -63,7 +63,7 @@ const definitions = stylex.create({
});
export const styles = {
- screen: cx(stylex.props(definitions.screen).className ?? '', relational.screen),
+ screen: cx(stylex.props(definitions.screen).className ?? '', 'lobe-player-15569863-screen'),
clock: stylex.props(definitions.clock).className ?? '',
rate: stylex.props(definitions.rate).className ?? '',
rateActive: stylex.props(definitions.rateActive).className ?? '',
diff --git a/src/features/Acceptance/Report/TerminalEvidence/relational.css b/src/features/Acceptance/Report/TerminalEvidence/relational.css
new file mode 100644
index 00000000000..fe14fa36edf
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/relational.css
@@ -0,0 +1,20 @@
+.lobe-relational-0c7e78c1-fold-header:hover [data-fold-title] {
+ color: var(--lobe-color-text);
+}
+
+.lobe-relational-0c7e78c1-facts dt {
+ color: var(--lobe-color-text-tertiary);
+}
+
+.lobe-relational-0c7e78c1-facts dd {
+ min-width: 0;
+ margin: 0;
+ color: var(--lobe-color-text-secondary);
+ overflow-wrap: anywhere;
+}
+
+@media (width <= 767px) {
+ .lobe-relational-0c7e78c1-facts dd + dt {
+ margin-block-start: 6px;
+ }
+}
diff --git a/src/features/Acceptance/Report/TerminalEvidence/relational.module.css b/src/features/Acceptance/Report/TerminalEvidence/relational.module.css
deleted file mode 100644
index 82f13db7a3d..00000000000
--- a/src/features/Acceptance/Report/TerminalEvidence/relational.module.css
+++ /dev/null
@@ -1,18 +0,0 @@
-.foldHeader:hover [data-fold-title] {
- color: var(--lobe-color-text);
- }
-
-.facts dt {
- color: var(--lobe-color-text-tertiary);
- }
-
-.facts dd {
- min-width: 0;
- margin: 0;
- color: var(--lobe-color-text-secondary);
- overflow-wrap: anywhere;
- }
-
-@media (width <= 767px) { .facts dd + dt {
- margin-block-start: 6px;
- } }
diff --git a/src/features/Acceptance/Report/TerminalEvidence/styles.ts b/src/features/Acceptance/Report/TerminalEvidence/styles.ts
index 80bf0c4cef5..c3026fa4bfb 100644
--- a/src/features/Acceptance/Report/TerminalEvidence/styles.ts
+++ b/src/features/Acceptance/Report/TerminalEvidence/styles.ts
@@ -1,9 +1,9 @@
+import './relational.css';
+
import { cx } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import relational from './relational.module.css';
-
const definitions = stylex.create({
foldHeader: {
cursor: 'pointer',
@@ -236,7 +236,10 @@ const definitions = stylex.create({
});
export const styles = {
- foldHeader: cx(stylex.props(definitions.foldHeader).className ?? '', relational.foldHeader),
+ foldHeader: cx(
+ stylex.props(definitions.foldHeader).className ?? '',
+ 'lobe-relational-0c7e78c1-fold-header',
+ ),
foldChevron: stylex.props(definitions.foldChevron).className ?? '',
foldChevronOpen: stylex.props(definitions.foldChevronOpen).className ?? '',
foldIcon: stylex.props(definitions.foldIcon).className ?? '',
@@ -248,7 +251,7 @@ export const styles = {
command: stylex.props(definitions.command).className ?? '',
commandText: stylex.props(definitions.commandText).className ?? '',
commandPrompt: stylex.props(definitions.commandPrompt).className ?? '',
- facts: cx(stylex.props(definitions.facts).className ?? '', relational.facts),
+ facts: cx(stylex.props(definitions.facts).className ?? '', 'lobe-relational-0c7e78c1-facts'),
mono: stylex.props(definitions.mono).className ?? '',
inlineList: stylex.props(definitions.inlineList).className ?? '',
linkButton: stylex.props(definitions.linkButton).className ?? '',
diff --git a/src/features/AddAgentMemberModal/AgentItem.tsx b/src/features/AddAgentMemberModal/AgentItem.tsx
index 2c3248ba309..8f39657213d 100644
--- a/src/features/AddAgentMemberModal/AgentItem.tsx
+++ b/src/features/AddAgentMemberModal/AgentItem.tsx
@@ -1,7 +1,9 @@
'use client';
import { agentDisplayName } from '@lobechat/types';
-import { Checkbox, createStaticStyles, Flexbox, Text } from '@lobehub/ui';
+import { Checkbox, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { useHover } from 'ahooks';
import { X } from 'lucide-react';
import { memo, useRef } from 'react';
@@ -10,48 +12,32 @@ import AgentAvatar from '@/components/AgentAvatar';
import { useAgentSelectionStore } from './store';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- item: css`
- cursor: pointer;
-
- margin-block: 1px;
- padding-block: 6px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
-
- transition: background 0.2s ease;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- removeButton: css`
- cursor: pointer;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: 20px;
- height: 20px;
- border-radius: 4px;
-
- color: ${cssVar.colorTextTertiary};
-
- transition: all 0.2s ease;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- }
- `,
- title: css`
- overflow: hidden;
- flex: 1;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ item: {
+ cursor: 'pointer',
+ marginBlock: '1px',
+ paddingBlock: '6px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.2s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ removeButton: {
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '20px',
+ height: '20px',
+ borderRadius: '4px',
+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },
+ transition: 'all 0.2s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ title: { overflow: 'hidden', flex: '1', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+});
export interface AgentItemData {
avatar: string | null;
@@ -89,7 +75,7 @@ const AgentItem = memo<AgentItemProps>(({ agent, defaultTitle, showCheckbox, sho
return (
<div
- className={styles.item}
+ className={stylex.props(styles.item).className}
ref={ref}
style={{ cursor: showCheckbox ? 'pointer' : 'default' }}
onClick={showCheckbox ? handleClick : undefined}
@@ -114,11 +100,11 @@ const AgentItem = memo<AgentItemProps>(({ agent, defaultTitle, showCheckbox, sho
shape="circle"
size={28}
/>
- <Text ellipsis className={styles.title}>
+ <Text ellipsis className={stylex.props(styles.title).className}>
{title}
</Text>
{showRemove && (
- <div className={styles.removeButton} onClick={handleRemove}>
+ <div {...stylex.props(styles.removeButton)} onClick={handleRemove}>
<X size={14} />
</div>
)}
diff --git a/src/features/AddAgentMemberModal/AvailableAgentList.tsx b/src/features/AddAgentMemberModal/AvailableAgentList.tsx
index 32e3159b0bd..43e421868c3 100644
--- a/src/features/AddAgentMemberModal/AvailableAgentList.tsx
+++ b/src/features/AddAgentMemberModal/AvailableAgentList.tsx
@@ -1,7 +1,9 @@
'use client';
import { agentDisplayName } from '@lobechat/types';
-import { createStaticStyles, Flexbox, SearchBar, Skeleton, Text } from '@lobehub/ui';
+import { Flexbox, SearchBar, Skeleton, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { type ChangeEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -17,24 +19,24 @@ import { type AgentItemData } from './AgentItem';
type Row = { agent: AgentItemData; type: 'agent' } | { label: string; type: 'header' };
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- user-select: none;
-
- overflow: hidden;
- display: flex;
- flex: 1;
- flex-direction: column;
-
- padding-block: ${cssVar.paddingSM}px 0;
- padding-inline: ${cssVar.paddingSM}px;
- `,
- sectionHeader: css`
- padding-block: 6px 4px;
- padding-inline: 8px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: {
+ userSelect: 'none',
+ overflow: 'hidden',
+ display: 'flex',
+ flex: '1',
+ flexDirection: 'column',
+ paddingBlockStart: `${cssVar.paddingSM}px`,
+ paddingBlockEnd: '0',
+ paddingInline: `${cssVar.paddingSM}px`,
+ },
+ sectionHeader: {
+ paddingBlockStart: '6px',
+ paddingBlockEnd: '4px',
+ paddingInline: '8px',
+ color: cssVar.colorTextSecondary,
+ },
+});
interface AvailableAgentListProps {
agents: AgentItemData[];
@@ -99,7 +101,7 @@ const AvailableAgentList = memo<AvailableAgentListProps>(({ agents, isLoading })
}, [filteredAgents, privateAgentIds, t]);
return (
- <Flexbox className={styles.container} gap={12}>
+ <Flexbox className={stylex.props(styles.container).className} gap={12}>
<SearchBar
allowClear
placeholder={t('memberSelection.searchAgents')}
@@ -128,7 +130,11 @@ const AvailableAgentList = memo<AvailableAgentListProps>(({ agents, isLoading })
const row = rows[index];
if (row.type === 'header') {
return (
- <Text className={styles.sectionHeader} fontSize={12} type="secondary">
+ <Text
+ className={stylex.props(styles.sectionHeader).className}
+ fontSize={12}
+ type="secondary"
+ >
{row.label}
</Text>
);
diff --git a/src/features/AddAgentMemberModal/SelectedAgentList.tsx b/src/features/AddAgentMemberModal/SelectedAgentList.tsx
index 536912a3e1a..4eed2c6fdf9 100644
--- a/src/features/AddAgentMemberModal/SelectedAgentList.tsx
+++ b/src/features/AddAgentMemberModal/SelectedAgentList.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, Flexbox } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,18 +12,10 @@ import AgentItem from './AgentItem';
import { type AgentItemData } from './AgentItem';
import { useAgentSelectionStore } from './store';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow-y: auto;
- flex: 1;
- padding: ${cssVar.paddingSM}px;
- `,
- title: css`
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ container: { overflowY: 'auto', flex: '1', padding: `${cssVar.paddingSM}px` },
+ title: { fontSize: '12px', fontWeight: 500, color: cssVar.colorTextSecondary },
+});
interface SelectedAgentListProps {
agents: AgentItemData[];
@@ -43,15 +37,15 @@ const SelectedAgentList = memo<SelectedAgentListProps>(({ agents }) => {
if (selectedAgents.length === 0) {
return (
- <Flexbox className={styles.container} flex={1}>
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
<AgentSelectionEmpty variant="noSelected" />
</Flexbox>
);
}
return (
- <Flexbox className={styles.container} gap={4}>
- <div className={styles.title}>
+ <Flexbox className={stylex.props(styles.container).className} gap={4}>
+ <div {...stylex.props(styles.title)}>
{t('memberSelection.selectedAgents', { count: selectedAgents.length })}
</div>
<Flexbox>
diff --git a/src/features/AddAgentMemberModal/index.tsx b/src/features/AddAgentMemberModal/index.tsx
index 84b4c43c740..0848c096457 100644
--- a/src/features/AddAgentMemberModal/index.tsx
+++ b/src/features/AddAgentMemberModal/index.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, Divider, Flexbox } from '@lobehub/ui';
+import { Divider, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,22 +13,18 @@ import SelectedAgentList from './SelectedAgentList';
import { useAgentSelectionStore } from './store';
import { useAddableGroupMembers } from './useAddableGroupMembers';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- display: flex;
- flex-direction: row;
-
- height: 500px;
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius}px;
- `,
- rightColumn: css`
- display: flex;
- flex: 1;
- flex-direction: column;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ flexDirection: 'row',
+ height: '500px',
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: `${cssVar.borderRadius}px`,
+ },
+});
/** Multi-select agent picker shared by chat groups and projects. */
export interface AddGroupMemberModalProps {
@@ -91,7 +89,7 @@ const AddGroupMemberModal = memo<AddGroupMemberModalProps>(
onCancel={handleCancel}
onOk={handleConfirm}
>
- <Flexbox horizontal className={styles.container} gap={8}>
+ <Flexbox horizontal className={stylex.props(styles.container).className} gap={8}>
{/* Left Column - Available Agents */}
<AvailableAgentList agents={availableAgents} isLoading={isLoadingAgents} />
diff --git a/src/features/AgentChannel/PlatformDetail/Body.module.css b/src/features/AgentChannel/PlatformDetail/Body.css
similarity index 67%
rename from src/features/AgentChannel/PlatformDetail/Body.module.css
rename to src/features/AgentChannel/PlatformDetail/Body.css
index c0635bfff60..fe9afc049ca 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.module.css
+++ b/src/features/AgentChannel/PlatformDetail/Body.css
@@ -3,11 +3,11 @@
* text and never wraps it, so a long description pushed the Save out of the card; let the title give
* way instead. Scoped plain CSS because the header is the form library's own DOM.
*/
-.moduleGroup :global(.lobe-form-form__group-header) {
+.lobe-body-2aeb75a4-module-group .lobe-form-form__group-header {
gap: 12px;
}
-.moduleGroup :global(.lobe-form-form__group-header) > :global(.lobe-form-form__group-title) {
+.lobe-body-2aeb75a4-module-group .lobe-form-form__group-header > .lobe-form-form__group-title {
flex: 1 1 0;
min-width: 0;
}
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 2e7d82c49e5..e3ff2ae1f2c 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -1,5 +1,7 @@
'use client';
+import './Body.css';
+
import { Button, confirmModal, Flexbox, Text } from '@lobehub/ui';
import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
import { RotateCcw } from 'lucide-react';
@@ -22,7 +24,6 @@ import { getInlineFieldKeys } from '../quickSetup/guides';
import QuickSetupSection from '../quickSetup/QuickSetupSection';
import { WakeRecords } from '../WakeRecords';
import { AccessSection } from './AccessSection';
-import styles from './Body.module.css';
import type { ChannelTab } from './channelTabs';
import { extractSettingsDefaults, WAKE_MASTER_KEY } from './formState';
import type { ChannelFormValues } from './index';
@@ -295,7 +296,7 @@ const Body = memo<BodyProps>(
fold away; a new bot has nothing else to do but fill them in. */}
{(groupCredentialFields.length > 0 || showApplicationId || showExtras) && (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={!!hasConfig || inlineKeys.size > 0}
defaultActive={!hasConfig && inlineKeys.size === 0}
desc={t('channel.group.credentialsDesc')}
@@ -358,7 +359,7 @@ const Body = memo<BodyProps>(
)}
{connectGroup && (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={false}
extra={moduleExtra('connection')}
keyValue={`settings-connect-${platformDef.id}`}
@@ -394,7 +395,7 @@ const Body = memo<BodyProps>(
// three separate decisions, so each gets a block (and a Save) of its own.
groupAccessFields(group.fields).map((section) => (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={false}
extra={moduleExtra(`access-${section.key}`)}
key={section.key}
@@ -422,7 +423,7 @@ const Body = memo<BodyProps>(
// it is a block of its own with a Save.
groupReplyFields(group.fields).map((section) => (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={false}
extra={section.key === 'style' ? moduleExtra('reply-style') : undefined}
key={section.key}
@@ -446,7 +447,7 @@ const Body = memo<BodyProps>(
.filter(wakeSectionShown)
.map((section) => (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={false}
key={section.key}
keyValue={`settings-wake-${section.key}-${platformDef.id}`}
@@ -466,7 +467,7 @@ const Body = memo<BodyProps>(
))
) : (
<Form.Group
- className={styles.moduleGroup}
+ className={'lobe-body-2aeb75a4-module-group'}
collapsible={false}
extra={moduleExtra(group.key as SaveModuleId)}
keyValue={`settings-${group.key}-${platformDef.id}`}
diff --git a/src/features/AgentSetting/AgentGraphRuntime/index.tsx b/src/features/AgentSetting/AgentGraphRuntime/index.tsx
index 167981205fa..1324a222d2a 100644
--- a/src/features/AgentSetting/AgentGraphRuntime/index.tsx
+++ b/src/features/AgentSetting/AgentGraphRuntime/index.tsx
@@ -2,7 +2,9 @@
import type { AgentGraph, LobeAgentChatConfig } from '@lobechat/types';
import { AgentGraphSchema } from '@lobechat/types/agent/graph';
-import { Alert, Button, createStaticStyles, cssVar, Flexbox, Switch, TextArea } from '@lobehub/ui';
+import { Alert, Button, Flexbox, Switch, TextArea } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,32 +12,21 @@ import { useTranslation } from 'react-i18next';
import { useStore } from '../store';
import { selectors } from '../store/selectors';
-const styles = createStaticStyles(({ css }) => ({
- actions: css`
- justify-content: flex-end;
- `,
- editor: css`
- font-family: ${cssVar.fontFamilyCode};
- `,
- item: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
- itemDesc: css`
- margin: 0;
- font-size: 13px;
- line-height: 1.5;
- color: ${cssVar.colorTextSecondary};
- `,
- itemTitle: css`
- margin: 0;
- font-size: 14px;
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ actions: { justifyContent: 'flex-end' },
+ editor: { fontFamily: cssVar.fontFamilyCode },
+ item: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ itemDesc: { margin: '0', fontSize: '13px', lineHeight: 1.5, color: cssVar.colorTextSecondary },
+ itemTitle: { margin: '0', fontSize: '14px', fontWeight: 600, color: cssVar.colorText },
+});
const formatGraph = (graph?: AgentGraph | null) => (graph ? JSON.stringify(graph, null, 2) : '');
@@ -119,10 +110,10 @@ const AgentGraphRuntime = memo(() => {
return (
<Flexbox gap={16} width={'100%'}>
- <Flexbox horizontal align={'center'} className={styles.item} gap={16}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.item).className} gap={16}>
<Flexbox flex={1} gap={4}>
- <h3 className={styles.itemTitle}>{t('settingGraphRuntime.enabled.title')}</h3>
- <p className={styles.itemDesc}>{t('settingGraphRuntime.enabled.desc')}</p>
+ <h3 {...stylex.props(styles.itemTitle)}>{t('settingGraphRuntime.enabled.title')}</h3>
+ <p {...stylex.props(styles.itemDesc)}>{t('settingGraphRuntime.enabled.desc')}</p>
</Flexbox>
<Switch
checked={enabled}
@@ -134,13 +125,13 @@ const AgentGraphRuntime = memo(() => {
/>
</Flexbox>
- <Flexbox className={styles.item} gap={12}>
+ <Flexbox className={stylex.props(styles.item).className} gap={12}>
<Flexbox gap={4}>
- <h3 className={styles.itemTitle}>{t('settingGraphRuntime.snapshot.title')}</h3>
- <p className={styles.itemDesc}>{t('settingGraphRuntime.snapshot.desc')}</p>
+ <h3 {...stylex.props(styles.itemTitle)}>{t('settingGraphRuntime.snapshot.title')}</h3>
+ <p {...stylex.props(styles.itemDesc)}>{t('settingGraphRuntime.snapshot.desc')}</p>
</Flexbox>
<TextArea
- className={styles.editor}
+ className={stylex.props(styles.editor).className}
disabled={disabled}
placeholder={t('settingGraphRuntime.snapshot.placeholder')}
rows={16}
@@ -154,7 +145,7 @@ const AgentGraphRuntime = memo(() => {
{error && <Alert showIcon title={error} type="error" />}
- <Flexbox horizontal className={styles.actions}>
+ <Flexbox horizontal className={stylex.props(styles.actions).className}>
<Button
disabled={disabled || !isDirty}
loading={saving}
diff --git a/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx b/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
index 7d914b976bd..06ef80804f4 100644
--- a/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
+++ b/src/features/AgentSetting/AgentOpening/OpeningMessage.tsx
@@ -1,7 +1,9 @@
'use client';
-import { Button, createStaticStyles, Flexbox } from '@lobehub/ui';
+import { Button, Flexbox } from '@lobehub/ui';
import { EditableMessage } from '@lobehub/ui/chat';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { PencilLine } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,19 +11,23 @@ import { useTranslation } from 'react-i18next';
import { useStore } from '../store';
import { selectors } from '../store/selectors';
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- markdown: css`
- border: unset;
- `,
- wrapper: css`
- width: 100%;
- padding: 8px;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: calc(${cssVar.borderRadiusLG} - 1px);
-
- background: ${cssVar.colorBgContainer};
- `,
-}));
+const styles = stylex.create({
+ markdown: {
+ borderWidth: 'unset',
+ borderStyle: 'unset',
+ borderColor: 'unset',
+ },
+ wrapper: {
+ width: '100%',
+ padding: '8px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: `calc(${cssVar.borderRadiusLG} - 1px)`,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
const OpeningMessage = memo(() => {
const { t } = useTranslation('setting');
@@ -52,7 +58,7 @@ const OpeningMessage = memo(() => {
);
return (
- <div className={styles.wrapper}>
+ <div {...stylex.props(styles.wrapper)}>
<Flexbox direction={'horizontal'}>
<EditableMessage
editButtonSize={'small'}
@@ -63,7 +69,7 @@ const OpeningMessage = memo(() => {
value={openingMessage ?? ''}
variant={'borderless'}
classNames={{
- markdown: styles.markdown,
+ markdown: stylex.props(styles.markdown).className,
}}
text={{
cancel: t('cancel', { ns: 'common' }),
diff --git a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
index 423bc46e46c..0a46aef373e 100644
--- a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
+++ b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
@@ -1,14 +1,8 @@
'use client';
-import {
- ActionIcon,
- Button,
- createStaticStyles,
- Empty,
- Flexbox,
- Input,
- SortableList,
-} from '@lobehub/ui';
+import { ActionIcon, Button, Empty, Flexbox, Input, SortableList } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { MessageCircle, PlusIcon, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,27 +11,13 @@ import useMergeState from 'use-merge-value';
import { useStore } from '../store';
import { selectors } from '../store/selectors';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- empty: css`
- margin-block: 24px;
- margin-inline: auto;
- `,
- questionItemContainer: css`
- padding-block: 8px;
- padding-inline-end: 8px;
- `,
- questionItemContent: css`
- flex: 1;
- `,
- questionsList: css`
- width: 100%;
- margin-block-start: 16px;
- `,
- repeatError: css`
- margin: 0;
- color: ${cssVar.colorErrorText};
- `,
-}));
+const styles = stylex.create({
+ empty: { marginBlock: '24px', marginInline: 'auto' },
+ questionItemContainer: { paddingBlock: '8px', paddingInlineEnd: '8px' },
+ questionItemContent: { flex: '1' },
+ questionsList: { width: '100%', marginBlockStart: '16px' },
+ repeatError: { margin: '0', color: cssVar.colorErrorText },
+});
interface QuestionItem {
content: string;
@@ -121,22 +101,22 @@ const OpeningQuestions = memo(() => {
</Flexbox>
{isRepeat && (
- <p className={styles.repeatError}>{t('settingOpening.openingQuestions.repeat')}</p>
+ <p {...stylex.props(styles.repeatError)}>{t('settingOpening.openingQuestions.repeat')}</p>
)}
</Flexbox>
- <div className={styles.questionsList}>
+ <div {...stylex.props(styles.questionsList)}>
{openingQuestions.length > 0 ? (
<SortableList
items={items}
renderItem={(item: QuestionItem) => (
<SortableList.Item
- className={styles.questionItemContainer}
+ className={stylex.props(styles.questionItemContainer).className}
id={item.id}
variant={'filled'}
>
{!disabled && <SortableList.DragHandle />}
- <div className={styles.questionItemContent}>{item.content}</div>
+ <div {...stylex.props(styles.questionItemContent)}>{item.content}</div>
<ActionIcon
disabled={disabled}
icon={Trash}
@@ -149,7 +129,7 @@ const OpeningQuestions = memo(() => {
/>
) : (
<Empty
- className={styles.empty}
+ className={stylex.props(styles.empty).className}
description={t('settingOpening.openingQuestions.empty')}
descriptionProps={{ fontSize: 14 }}
icon={MessageCircle}
diff --git a/src/features/AgentSetting/SettingsModalLayout.tsx b/src/features/AgentSetting/SettingsModalLayout.tsx
index b049b69aa26..ee344776fe9 100644
--- a/src/features/AgentSetting/SettingsModalLayout.tsx
+++ b/src/features/AgentSetting/SettingsModalLayout.tsx
@@ -1,15 +1,8 @@
'use client';
-import {
- ActionIcon,
- Avatar,
- createStaticStyles,
- Flexbox,
- Icon,
- Tabs,
- Text,
- useModalContext,
-} from '@lobehub/ui';
+import { ActionIcon, Avatar, Flexbox, Icon, Tabs, Text, useModalContext } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type LucideIcon, XIcon } from 'lucide-react';
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -34,19 +27,23 @@ export interface SettingsModalLayoutProps {
title: ReactNode;
}
-const styles = createStaticStyles(({ css, cssVar }) => ({
- header: css`
- flex-shrink: 0;
- padding-block: 10px;
- padding-inline: 16px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- tabsBar: css`
- flex-shrink: 0;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
-}));
+const styles = stylex.create({
+ header: {
+ flexShrink: 0,
+ paddingBlock: '10px',
+ paddingInline: '16px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ tabsBar: {
+ flexShrink: 0,
+ paddingInline: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+});
const SettingsModalLayout = memo<SettingsModalLayoutProps>(
({ agentId, avatar, background, title, tabs, activeTab, onTabChange, children }) => {
@@ -61,7 +58,12 @@ const SettingsModalLayout = memo<SettingsModalLayoutProps>(
return (
<Flexbox height={'100%'} style={{ overflow: 'hidden' }}>
- <Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.header).className}
+ justify={'space-between'}
+ >
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
{agentId ? (
<AgentAvatar
@@ -82,7 +84,7 @@ const SettingsModalLayout = memo<SettingsModalLayoutProps>(
</Flexbox>
{tabItems && tabItems.length >= 2 && (
- <Flexbox className={styles.tabsBar}>
+ <Flexbox className={stylex.props(styles.tabsBar).className}>
<Tabs activeKey={activeTab} items={tabItems} onChange={onTabChange} />
</Flexbox>
)}
diff --git a/src/features/Auth/OAuthCallback/Success.tsx b/src/features/Auth/OAuthCallback/Success.tsx
index a389d9a3ff7..e49cc741368 100644
--- a/src/features/Auth/OAuthCallback/Success.tsx
+++ b/src/features/Auth/OAuthCallback/Success.tsx
@@ -1,12 +1,12 @@
'use client';
+import '../resultStyles.css';
+
import { FluentEmoji, Result, Text } from '@lobehub/ui';
import React, { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router';
-import resultStyles from '../resultStyles.module.css';
-
const SuccessPage = memo(() => {
const { t } = useTranslation('oauth');
const [searchParams] = useSearchParams();
@@ -48,7 +48,7 @@ const SuccessPage = memo(() => {
return (
<Result
- className={resultStyles.fullWidthSubTitle}
+ className={'lobe-result-styles-cb01c08e-full-width-sub-title'}
icon={<FluentEmoji emoji={'✅'} size={96} type={'anim'} />}
status="success"
subTitle={
diff --git a/src/features/Auth/OAuthDevice/DeviceSuccess.tsx b/src/features/Auth/OAuthDevice/DeviceSuccess.tsx
index 980adb4b496..e3fe7f08009 100644
--- a/src/features/Auth/OAuthDevice/DeviceSuccess.tsx
+++ b/src/features/Auth/OAuthDevice/DeviceSuccess.tsx
@@ -1,17 +1,17 @@
'use client';
+import '../resultStyles.css';
+
import { FluentEmoji, Result, Text } from '@lobehub/ui';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import resultStyles from '../resultStyles.module.css';
-
const DeviceSuccess = memo(() => {
const { t } = useTranslation('oauth');
return (
<Result
- className={resultStyles.fullWidthSubTitle}
+ className={'lobe-result-styles-cb01c08e-full-width-sub-title'}
icon={<FluentEmoji emoji={'✅'} size={96} type={'anim'} />}
status="success"
subTitle={
diff --git a/src/features/Auth/resultStyles.module.css b/src/features/Auth/resultStyles.css
similarity index 75%
rename from src/features/Auth/resultStyles.module.css
rename to src/features/Auth/resultStyles.css
index 7374c80b11b..0a4bfcf5c36 100644
--- a/src/features/Auth/resultStyles.module.css
+++ b/src/features/Auth/resultStyles.css
@@ -1,5 +1,5 @@
/* Result caps the subtitle at 36ch, which makes it narrower than the title.
Keep the subtitle paragraph at full width inside the Result root. */
-.fullWidthSubTitle p {
+.lobe-result-styles-cb01c08e-full-width-sub-title p {
max-width: 100%;
}
diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
index bf27db1521d..fb432d01463 100644
--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
@@ -1,3 +1,5 @@
+import './gitMenuTrigger.css';
+
import type { DeviceGitWorktreeListItem } from '@lobechat/types';
import {
confirmModal,
@@ -46,7 +48,6 @@ import { gitService } from '@/services/git';
import { useFetchGitWorkingTreeStatus } from '@/store/device';
import { openCreateBranchModal } from './CreateBranchModal';
-import gitMenuTriggerStyles from './gitMenuTrigger.module.css';
import { openRenameBranchModal } from './RenameBranchModal';
import { useBranchList } from './useBranchList';
import { useSwitchWorktree } from './useSwitchWorktree';
@@ -436,7 +437,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
return (
<DropdownMenuRoot open={open} onOpenChange={onOpenChange}>
<DropdownMenuTrigger>
- <div className={gitMenuTriggerStyles.trigger}>{children}</div>
+ <div className={'lobe-git-menu-trigger-7cf96368-trigger'}>{children}</div>
</DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement={placement} sideOffset={8}>
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.css b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.css
new file mode 100644
index 00000000000..53e0e9a3dae
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.css
@@ -0,0 +1,13 @@
+.lobe-quota-account-manager-modal-2f1ccb6d-radio-group {
+ width: 100%;
+}
+
+/* Targets the RadioGroup's own label / text DOM, which has no className hook. */
+.lobe-quota-account-manager-modal-2f1ccb6d-radio-group > label {
+ width: 100%;
+}
+
+.lobe-quota-account-manager-modal-2f1ccb6d-radio-group > label > span:last-child {
+ flex: 1;
+ min-width: 0;
+}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.css b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.css
deleted file mode 100644
index a5e5d9a6de4..00000000000
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.css
+++ /dev/null
@@ -1,13 +0,0 @@
-.radioGroup {
- width: 100%;
-}
-
-/* Targets the RadioGroup's own label / text DOM, which has no className hook. */
-.radioGroup > label {
- width: 100%;
-}
-
-.radioGroup > label > span:last-child {
- flex: 1;
- min-width: 0;
-}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
index 7560c1bd7a9..d9b43fa0a5a 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
@@ -1,5 +1,7 @@
'use client';
+import './QuotaAccountManagerModal.css';
+
import { isDesktop } from '@lobechat/const';
import {
currentUtilization,
@@ -46,8 +48,6 @@ import {
import { useElectronStore } from '@/store/electron';
import { electronGatewaySelectors } from '@/store/electron/selectors';
-import radioGroupStyles from './QuotaAccountManagerModal.module.css';
-
const styles = stylex.create({
footer: {
marginBlockStart: '4px',
@@ -417,7 +417,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId
<AccountReadingsSync accountId={a.id} key={a.id} />
))}
<RadioGroup
- className={radioGroupStyles.radioGroup}
+ className={'lobe-quota-account-manager-modal-2f1ccb6d-radio-group'}
gap={2}
horizontal={false}
// Which mode is active is unknown until the bindings are on screen. The
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index ddfb9f8341c..a23bd6eac92 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -1,3 +1,5 @@
+import './gitMenuTrigger.css';
+
import { deriveWorktreePath, type DeviceGitWorktreeListItem } from '@lobechat/types';
import {
confirmModal,
@@ -39,7 +41,6 @@ import { useTranslation } from 'react-i18next';
import { gitService } from '@/services/git';
import { openCreateWorktreeModal } from './CreateWorktreeModal';
-import gitMenuTriggerStyles from './gitMenuTrigger.module.css';
import { useSwitchWorktree } from './useSwitchWorktree';
import { useWorktreeHomeDir } from './useWorktreeHomeDir';
import { getPathName, isDisabled, normalizeDisplayPath } from './worktreeHelpers';
@@ -598,7 +599,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
<DropdownMenuTrigger>
<div
aria-disabled={disabled}
- className={gitMenuTriggerStyles.trigger}
+ className={'lobe-git-menu-trigger-7cf96368-trigger'}
data-disabled={disabled || undefined}
>
{open ? trigger : <Tooltip title={triggerTitle}>{trigger}</Tooltip>}
diff --git a/src/features/ChatInput/ControlBar/gitMenuTrigger.module.css b/src/features/ChatInput/ControlBar/gitMenuTrigger.css
similarity index 68%
rename from src/features/ChatInput/ControlBar/gitMenuTrigger.module.css
rename to src/features/ChatInput/ControlBar/gitMenuTrigger.css
index 254a75539b6..c30e9af464c 100644
--- a/src/features/ChatInput/ControlBar/gitMenuTrigger.module.css
+++ b/src/features/ChatInput/ControlBar/gitMenuTrigger.css
@@ -1,4 +1,4 @@
-.trigger {
+.lobe-git-menu-trigger-7cf96368-trigger {
display: inline-flex;
flex: none;
min-width: 0;
@@ -6,7 +6,7 @@
/* The stable menu anchor must not paint behind the child's rounded chip or
overview row. Keep hover and popup-open feedback on that same surface. */
-.trigger.trigger.trigger[data-popup-open] {
+.lobe-git-menu-trigger-7cf96368-trigger.lobe-git-menu-trigger-7cf96368-trigger.lobe-git-menu-trigger-7cf96368-trigger[data-popup-open] {
background: transparent;
}
@@ -15,18 +15,18 @@
/* A column host stretches the anchor for overview rows; compact composer
chips use their intrinsic width instead of 100% of the whole git group. */
-.trigger.trigger > * {
+.lobe-git-menu-trigger-7cf96368-trigger.lobe-git-menu-trigger-7cf96368-trigger > * {
flex: 1 !important;
min-width: 0 !important;
}
-.trigger[data-popup-open] > * {
+.lobe-git-menu-trigger-7cf96368-trigger[data-popup-open] > * {
background: var(--lobe-color-fill-tertiary) !important;
}
/* Stale-first: the trigger stays in place (no layout jump) but cannot
checkout until the current probe confirms the branch. */
-.trigger[aria-disabled='true'] > * {
+.lobe-git-menu-trigger-7cf96368-trigger[aria-disabled='true'] > * {
cursor: not-allowed !important;
opacity: 0.6 !important;
}
diff --git a/src/features/CommunitySkillDetail/Details/Install/Platform.css b/src/features/CommunitySkillDetail/Details/Install/Platform.css
new file mode 100644
index 00000000000..69864efa995
--- /dev/null
+++ b/src/features/CommunitySkillDetail/Details/Install/Platform.css
@@ -0,0 +1,3 @@
+.lobe-platform-535c8dc5-lite pre {
+ padding: 12px !important;
+}
diff --git a/src/features/CommunitySkillDetail/Details/Install/Platform.module.css b/src/features/CommunitySkillDetail/Details/Install/Platform.module.css
deleted file mode 100644
index 1b9659a4aba..00000000000
--- a/src/features/CommunitySkillDetail/Details/Install/Platform.module.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.lite pre {
- padding: 12px !important;
-}
diff --git a/src/features/CommunitySkillDetail/Details/Install/Platform.tsx b/src/features/CommunitySkillDetail/Details/Install/Platform.tsx
index b8bb107aacc..9d552bfa765 100644
--- a/src/features/CommunitySkillDetail/Details/Install/Platform.tsx
+++ b/src/features/CommunitySkillDetail/Details/Install/Platform.tsx
@@ -1,5 +1,7 @@
'use client';
+import './Platform.css';
+
import { AGENT_CHAT_URL, DEFAULT_INBOX_AVATAR } from '@lobechat/const';
import { Claude, Cline, Cursor, OpenAI } from '@lobehub/icons';
import {
@@ -26,7 +28,6 @@ import { useChatStore } from '@/store/chat';
import { useDetailActionContext } from '../../DetailProvider';
import { getSkillInstructionsUrl } from './getSkillInstructionsUrl';
-import styles from './Platform.module.css';
import VsCodeIcon from './VsCodeIcon';
const Title = ({ children }: { children?: React.ReactNode }) => (
@@ -246,7 +247,7 @@ const Platform = memo<PlatformProps>(
<Highlighter
fullFeatured
wrap
- className={lite ? styles.lite : undefined}
+ className={lite ? 'lobe-platform-535c8dc5-lite' : undefined}
defaultExpand={expandCodeByDefault ?? false}
fileName={'Agent prompt'}
language={'bash'}
@@ -305,7 +306,7 @@ const Platform = memo<PlatformProps>(
{lite && <Divider dashed />}
<Highlighter
fullFeatured
- className={lite ? styles.lite : undefined}
+ className={lite ? 'lobe-platform-535c8dc5-lite' : undefined}
defaultExpand={expandCodeByDefault ?? false}
fileName={t('skills.details.sidebar.installCommand')}
language={'bash'}
@@ -317,7 +318,7 @@ const Platform = memo<PlatformProps>(
{lite && <Divider dashed />}
<Highlighter
fullFeatured
- className={lite ? styles.lite : undefined}
+ className={lite ? 'lobe-platform-535c8dc5-lite' : undefined}
defaultExpand={false}
fileName={t('skills.details.sidebar.directoryLayout')}
language={'text'}
diff --git a/src/features/CommunitySkillDetail/Details/Overview/Overview.css b/src/features/CommunitySkillDetail/Details/Overview/Overview.css
new file mode 100644
index 00000000000..c0c87d79707
--- /dev/null
+++ b/src/features/CommunitySkillDetail/Details/Overview/Overview.css
@@ -0,0 +1,3 @@
+.lobe-overview-22f20c33-summary p {
+ margin-block: 0 0.8em;
+}
diff --git a/src/features/CommunitySkillDetail/Details/Overview/Overview.module.css b/src/features/CommunitySkillDetail/Details/Overview/Overview.module.css
deleted file mode 100644
index 9edbb735b76..00000000000
--- a/src/features/CommunitySkillDetail/Details/Overview/Overview.module.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.summary p {
- margin-block: 0 0.8em;
-}
diff --git a/src/features/CommunitySkillDetail/Details/Overview/index.tsx b/src/features/CommunitySkillDetail/Details/Overview/index.tsx
index 39acf7bf4ad..f1ce525fe1f 100644
--- a/src/features/CommunitySkillDetail/Details/Overview/index.tsx
+++ b/src/features/CommunitySkillDetail/Details/Overview/index.tsx
@@ -1,5 +1,7 @@
'use client';
+import './Overview.css';
+
import {
Accordion,
Block,
@@ -26,7 +28,6 @@ import { skillSelectors } from '@/store/discover/selectors';
import { sx } from '@/styles/sx';
import { useDetailActionContext, useDetailContext } from '../../DetailProvider';
-import moduleStyles from './Overview.module.css';
import RelatedSkillCard from './RelatedSkillCard';
const styles = stylex.create({
@@ -95,7 +96,7 @@ const Overview = memo(() => {
{/* ABOUT */}
<Flexbox gap={12}>
<SectionLabel>{t('skills.details.overview.about')}</SectionLabel>
- <div {...sx(styles.summary, moduleStyles.summary)}>
+ <div {...sx(styles.summary, 'lobe-overview-22f20c33-summary')}>
<Markdown variant={'chat'}>{overview?.summary || description || ''}</Markdown>
</div>
</Flexbox>
diff --git a/src/features/CommunitySkillDetail/Header.tsx b/src/features/CommunitySkillDetail/Header.tsx
index 3984e935b51..94b5bc640e4 100644
--- a/src/features/CommunitySkillDetail/Header.tsx
+++ b/src/features/CommunitySkillDetail/Header.tsx
@@ -358,9 +358,9 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
<>
<MetaDivider />
<PublishedTime
- className={stylex.props(styles.time).className}
date={(updatedAt || createdAt) as string}
template={'MMM DD, YYYY'}
+ xstyle={styles.time}
/>
</>
)}
diff --git a/src/features/CommunityWorkspaceSettings/index.tsx b/src/features/CommunityWorkspaceSettings/index.tsx
index 565574a5274..21d10160057 100644
--- a/src/features/CommunityWorkspaceSettings/index.tsx
+++ b/src/features/CommunityWorkspaceSettings/index.tsx
@@ -4,7 +4,6 @@ import { OFFICIAL_URL } from '@lobechat/const';
import {
Button,
Center,
- createStaticStyles,
cssVar,
Flexbox,
Icon,
@@ -19,6 +18,8 @@ import {
Tooltip,
Upload,
} from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import {
ArrowLeft,
CircleHelp,
@@ -57,15 +58,9 @@ const DISPLAY_NAME_MAX = 50;
const ORGANIZATION_URL_PREFIX = `${OFFICIAL_URL.replace(/^https?:\/\//, '')}/community/org/`;
const NAMESPACE_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- memberNameLink: css`
- color: inherit;
-
- &:hover {
- color: ${cssVar.colorPrimary};
- }
- `,
-}));
+const styles = stylex.create({
+ memberNameLink: { color: { 'default': 'inherit', ':hover': sxVar.colorPrimary } },
+});
/**
* The default Market namespace equals the raw cloud userId (e.g.
@@ -152,7 +147,7 @@ const MembersCard = memo<{ canManage: boolean }>(({ canManage }) => {
<Flexbox gap={2}>
{profileUrl ? (
<a
- className={styles.memberNameLink}
+ {...stylex.props(styles.memberNameLink)}
href={profileUrl}
rel="noopener noreferrer"
target="_blank"
@@ -164,7 +159,7 @@ const MembersCard = memo<{ canManage: boolean }>(({ canManage }) => {
)}
{publicHandle && profileUrl && (
<a
- className={styles.memberNameLink}
+ {...stylex.props(styles.memberNameLink)}
href={profileUrl}
rel="noopener noreferrer"
target="_blank"
diff --git a/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx b/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx
index bdd44a285a5..c6bbdf99b36 100644
--- a/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx
+++ b/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx
@@ -5,6 +5,8 @@ import * as stylex from '@stylexjs/stylex';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { scrollShadowButtonMarker } from './markers.stylex';
+
const styles = stylex.create({
button: {
position: 'absolute',
@@ -12,7 +14,7 @@ const styles = stylex.create({
insetBlockStart: '50%',
transform: 'translateY(-50%)',
color: cssVar.colorTextSecondary,
- opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },
+ opacity: { default: 0, [stylex.when.ancestor(':hover', scrollShadowButtonMarker)]: 1 },
transition: `opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut}`,
borderColor: { 'default': null, ':hover': cssVar.colorBorder },
boxShadow: { 'default': null, ':hover': cssVar.boxShadowTertiary },
@@ -70,7 +72,7 @@ const ScrollShadowWithButton = memo<FlexboxProps>(({ children, ...rest }) => {
return (
<Flexbox
horizontal
- className={stylex.props(styles.container, stylex.defaultMarker()).className}
+ className={stylex.props(styles.container, scrollShadowButtonMarker).className}
width={'100%'}
{...rest}
>
diff --git a/src/features/Conversation/Messages/AgentCouncil/components/markers.stylex.ts b/src/features/Conversation/Messages/AgentCouncil/components/markers.stylex.ts
new file mode 100644
index 00000000000..110fdf26749
--- /dev/null
+++ b/src/features/Conversation/Messages/AgentCouncil/components/markers.stylex.ts
@@ -0,0 +1,3 @@
+import * as stylex from '@stylexjs/stylex';
+
+export const scrollShadowButtonMarker = stylex.defineMarker();
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
index 52ecd55688d..8de0a06f503 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
@@ -114,7 +114,7 @@ const ToolTitle = memo<ToolTitleProps>(
const status = isLoading ? 'loading' : failed ? 'failed' : 'completed';
return (
<div {...stylex.props(styles.root, isAborted && styles.aborted)}>
- <span {...sx([styles.label], isLoading ? shinyTextStyles.shinyText : undefined)}>
+ <span {...sx(styles.label, isLoading ? shinyTextStyles.shinyText : undefined)}>
{t(`builtins.goalCommand.${goalCommand.kind}.${status}`)}
</span>
{goalTitle && <span {...stylex.props(styles.standalone)}>{goalTitle}</span>}
@@ -125,12 +125,12 @@ const ToolTitle = memo<ToolTitleProps>(
return (
<div {...stylex.props(styles.root, isAborted && styles.aborted)}>
{isStandaloneDescription ? (
- <span {...sx([styles.standalone], isLoading ? shinyTextStyles.shinyText : undefined)}>
+ <span {...sx(styles.standalone, isLoading ? shinyTextStyles.shinyText : undefined)}>
{keyword}
</span>
) : (
<>
- <span {...sx([styles.label], isLoading ? shinyTextStyles.shinyText : undefined)}>
+ <span {...sx(styles.label, isLoading ? shinyTextStyles.shinyText : undefined)}>
{actionLabel || (
<>
{pluginTitle && (
diff --git a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
index a7647e149c2..ba1697d9a4c 100644
--- a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
+++ b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
@@ -215,7 +215,7 @@ const ProcessingState = memo<ProcessingStateProps>(
{/* Progress Bar */}
<div {...stylex.props(styles.progress)}>
- <div {...sx([styles.progressBar], undefined, { width: `${progress}%` })} />
+ <div {...sx(styles.progressBar, { width: `${progress}%` })} />
<div {...stylex.props(styles.progressShimmer)} />
</div>
@@ -292,7 +292,7 @@ const ProcessingState = memo<ProcessingStateProps>(
{/* Progress Bar */}
<div {...stylex.props(styles.progressCompact)}>
- <div {...sx([styles.progressBar], undefined, { width: `${progress}%` })} />
+ <div {...sx(styles.progressBar, { width: `${progress}%` })} />
<div {...stylex.props(styles.progressShimmer)} />
</div>
diff --git a/src/features/Conversation/Messages/index.module.css b/src/features/Conversation/Messages/index.css
similarity index 63%
rename from src/features/Conversation/Messages/index.module.css
rename to src/features/Conversation/Messages/index.css
index ee9ce539fd0..56e8b5a91c0 100644
--- a/src/features/Conversation/Messages/index.module.css
+++ b/src/features/Conversation/Messages/index.css
@@ -1,4 +1,4 @@
/* Prevent the antd textarea from growing too long. */
-.message :global(.ant-input) {
+.lobe-messages-0fc10b22-message .ant-input {
max-height: 900px;
}
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index 38782dd0019..a026235d798 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -1,5 +1,7 @@
'use client';
+import './index.css';
+
import { isDesktop } from '@lobechat/const';
import { Flexbox } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
@@ -26,7 +28,6 @@ import PendingRetryTurn from './components/PendingRetryTurn';
import TextSelectionActionLayer from './components/TextSelectionActionLayer';
import CompressedGroupMessage from './CompressedGroup';
import GroupTasksMessage from './GroupTasks';
-import cssModule from './index.module.css';
import { getMessageInteractionState } from './messageInteraction';
import TaskMessage from './Task';
import TaskCallbackMessage from './TaskCallback';
@@ -278,8 +279,9 @@ const MessageItem = memo<MessageItemProps>(
{enableHistoryDivider && <History />}
<Flexbox
{...sx(
- [styles.message, shouldDimCreatingMessage && styles.loading],
- [cssModule.message, className].filter(Boolean).join(' '),
+ styles.message,
+ shouldDimCreatingMessage && styles.loading,
+ ['lobe-messages-0fc10b22-message', className].filter(Boolean).join(' '),
)}
data-index={index}
onContextMenu={onContextMenu}
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index 4ad5ccb3285..efba609e10d 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -1,6 +1,8 @@
import type { SidebarAgentItem } from '@lobechat/types';
import { agentDisplayName, agentSecondaryDisplayName } from '@lobechat/types';
-import { ActionIcon, createStaticStyles, cssVar, Spin } from '@lobehub/ui';
+import { ActionIcon, Spin } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { PinIcon } from 'lucide-react';
import { type CSSProperties, type DragEvent } from 'react';
import { memo, useCallback, useMemo } from 'react';
@@ -20,56 +22,49 @@ import Actions from '../Item/Actions';
import { usePreservedAgentUrl } from '../usePreservedAgentUrl';
import { useAgentDropdownMenu } from './useDropdownMenu';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- badge: css`
- pointer-events: none;
-
- position: absolute;
- inset-block-end: -3px;
- inset-inline-end: -3px;
-
- display: inline-flex;
- align-items: center;
- justify-content: center;
-
- min-width: 14px;
- height: 14px;
- padding-inline: 3px;
- border: 1.5px solid ${cssVar.colorBgContainer};
- border-radius: 999px;
-
- font-size: 9px;
- font-weight: 600;
- line-height: 1;
- color: #fff;
-
- background: ${cssVar.colorError};
- `,
- runningBadge: css`
- pointer-events: none;
-
- position: absolute;
- inset-block-end: -3px;
- inset-inline-end: -3px;
-
- display: inline-flex;
- align-items: center;
- justify-content: center;
-
- width: 14px;
- height: 14px;
- border: 1.5px solid ${cssVar.colorBgContainer};
- border-radius: 999px;
-
- color: ${cssVar.colorWarning};
-
- background: ${cssVar.colorBgContainer};
- `,
- wrapper: css`
- position: relative;
- display: inline-flex;
- `,
-}));
+const styles = stylex.create({
+ badge: {
+ pointerEvents: 'none',
+ position: 'absolute',
+ insetBlockEnd: '-3px',
+ insetInlineEnd: '-3px',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minWidth: '14px',
+ height: '14px',
+ paddingInline: '3px',
+ borderWidth: '1.5px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBgContainer,
+ borderRadius: '999px',
+ fontSize: '9px',
+ fontWeight: 600,
+ lineHeight: 1,
+ color: '#fff',
+ backgroundColor: cssVar.colorError,
+ backgroundImage: 'none',
+ },
+ runningBadge: {
+ pointerEvents: 'none',
+ position: 'absolute',
+ insetBlockEnd: '-3px',
+ insetInlineEnd: '-3px',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '14px',
+ height: '14px',
+ borderWidth: '1.5px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBgContainer,
+ borderRadius: '999px',
+ color: cssVar.colorWarning,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ wrapper: { position: 'relative', display: 'inline-flex' },
+});
interface AgentItemProps {
className?: string;
@@ -159,9 +154,9 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
if (isLoading) {
return (
- <span className={styles.wrapper}>
+ <span {...stylex.props(styles.wrapper)}>
{avatarNode}
- <span className={styles.runningBadge}>
+ <span {...stylex.props(styles.runningBadge)}>
<Spin size={9} style={{ color: 'inherit' }} />
</span>
</span>
@@ -170,9 +165,9 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
if (unreadCount > 0) {
return (
- <span className={styles.wrapper}>
+ <span {...stylex.props(styles.wrapper)}>
{avatarNode}
- <span className={styles.badge}>{unreadCount > 99 ? '99+' : unreadCount}</span>
+ <span {...stylex.props(styles.badge)}>{unreadCount > 99 ? '99+' : unreadCount}</span>
</span>
);
}
diff --git a/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx b/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
index 4ee3d013a1f..82bef8db6b5 100644
--- a/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
@@ -6,13 +6,13 @@ import {
accordionStyles,
AccordionTrigger,
ContextMenuTrigger,
- createStaticStyles,
cx,
Flexbox,
Icon,
Spin,
Text,
} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { HashIcon } from 'lucide-react';
import React, { memo, useCallback, useMemo, useState } from 'react';
@@ -24,11 +24,7 @@ import SessionList from '../List';
import Actions from './Actions';
import { useGroupDropdownMenu } from './useDropdownMenu';
-const styles = createStaticStyles(({ css }) => ({
- item: css`
- padding-inline-start: 14px;
- `,
-}));
+const styles = stylex.create({ item: { paddingInlineStart: '14px' } });
const GroupItem = memo<SidebarGroup>(({ items, id, name, visibility }) => {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
@@ -89,7 +85,7 @@ const GroupItem = memo<SidebarGroup>(({ items, id, name, visibility }) => {
<SessionList
dataSource={items}
groupId={id}
- itemClassName={styles.item}
+ itemClassName={stylex.props(styles.item).className}
visibility={visibility}
/>
</AccordionPanel>
diff --git a/src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx b/src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx
index c9c779e06b0..9995b6a634c 100644
--- a/src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx
@@ -2,7 +2,9 @@
import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE } from '@lobechat/const';
import { agentDisplayName } from '@lobechat/types';
-import { Avatar, createStaticStyles, Spin } from '@lobehub/ui';
+import { Avatar, Spin } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type CSSProperties } from 'react';
import { memo } from 'react';
@@ -17,32 +19,27 @@ import { operationSelectors } from '@/store/chat/selectors';
import { usePreservedAgentUrl } from './usePreservedAgentUrl';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- runningBadge: css`
- pointer-events: none;
-
- position: absolute;
- inset-block-end: -3px;
- inset-inline-end: -3px;
-
- display: inline-flex;
- align-items: center;
- justify-content: center;
-
- width: 14px;
- height: 14px;
- border: 1.5px solid ${cssVar.colorBgContainer};
- border-radius: 999px;
-
- color: ${cssVar.colorWarning};
-
- background: ${cssVar.colorBgContainer};
- `,
- wrapper: css`
- position: relative;
- display: inline-flex;
- `,
-}));
+const styles = stylex.create({
+ runningBadge: {
+ pointerEvents: 'none',
+ position: 'absolute',
+ insetBlockEnd: '-3px',
+ insetInlineEnd: '-3px',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '14px',
+ height: '14px',
+ borderWidth: '1.5px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBgContainer,
+ borderRadius: '999px',
+ color: cssVar.colorWarning,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ wrapper: { position: 'relative', display: 'inline-flex' },
+});
interface InboxItemProps {
className?: string;
@@ -77,9 +74,9 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {
title={inboxAgentTitle}
icon={
isLoading ? (
- <span className={styles.wrapper}>
+ <span {...stylex.props(styles.wrapper)}>
{avatarNode}
- <span className={styles.runningBadge}>
+ <span {...stylex.props(styles.runningBadge)}>
<Spin size={9} style={{ color: 'inherit' }} />
</span>
</span>
diff --git a/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx b/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
index 87c6ecefe68..57677249e0c 100644
--- a/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
+++ b/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx
@@ -1,11 +1,5 @@
-import {
- ActionIcon,
- confirmModal,
- createStaticStyles,
- EditableText,
- SortableList,
- toast,
-} from '@lobehub/ui';
+import { ActionIcon, confirmModal, EditableText, SortableList, toast } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { Eye, EyeOff, PencilLine, Trash } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,24 +9,10 @@ import type { SessionGroupItemBase } from '@/types/session';
import { useSidebarGroupVisibility } from '../../useSidebarGroupVisibility';
-const styles = createStaticStyles(({ css }) => ({
- content: css`
- position: relative;
- overflow: hidden;
- flex: 1;
- `,
- // Hidden folders stay in place (they're still shared, and still ordered) but
- // read as inactive, so the row itself answers "is this in my sidebar?".
- hiddenTitle: css`
- opacity: 0.45;
- `,
- title: css`
- flex: 1;
- height: 28px;
- line-height: 28px;
- text-align: start;
- `,
-}));
+const styles = stylex.create({
+ hiddenTitle: { opacity: 0.45 },
+ title: { flex: '1', height: '28px', lineHeight: '28px', textAlign: 'start' },
+});
interface GroupItemProps extends SessionGroupItemBase {
disabled?: boolean;
@@ -51,7 +31,7 @@ const GroupItem = memo<GroupItemProps>(({ id, name, disabled }) => {
{!disabled && <SortableList.DragHandle />}
{!editing ? (
<>
- <span className={`${styles.title} ${visible ? '' : styles.hiddenTitle}`}>{name}</span>
+ <span {...stylex.props(styles.title, !visible && styles.hiddenTitle)}>{name}</span>
{/* Visibility is the caller's own view of a shared folder, so it is
deliberately NOT gated on `disabled` (the edit permission). */}
<ActionIcon
diff --git a/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx b/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx
index 7c42dc5b972..888c9f65fcf 100644
--- a/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx
@@ -1,4 +1,6 @@
-import { Button, createStaticStyles, Flexbox, Icon, SortableList } from '@lobehub/ui';
+import { Button, Flexbox, Icon, SortableList } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { Plus } from 'lucide-react';
import { memo, useState } from 'react';
@@ -12,18 +14,16 @@ import type { SessionGroupItemBase } from '@/types/session';
import GroupItem from './GroupItem';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- height: 36px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius}px;
- transition: background 0.2s ease-in-out;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = stylex.create({
+ container: {
+ height: '36px',
+ paddingInline: '8px',
+ borderRadius: `${cssVar.borderRadius}px`,
+ transition: 'background 0.2s ease-in-out',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
interface ConfigGroupModalProps {
onCancel?: () => void;
@@ -66,7 +66,7 @@ const ConfigGroupModal = memo<ConfigGroupModalProps>(({ open, onCancel, scope =
<SortableList.Item
horizontal
align={'center'}
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={4}
id={item.id}
justify={'space-between'}
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
index 0e3fbd59f44..b657697a63a 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
@@ -24,9 +24,6 @@ import {
ActionIcon,
Button,
createModal,
- createStaticStyles,
- cssVar,
- cx,
Flexbox,
Icon,
type ModalInstance,
@@ -34,6 +31,8 @@ import {
Tooltip,
useModalContext,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { t } from 'i18next';
import { ArrowDownToLine, Eye, EyeOff, GripVertical, PinIcon, RotateCcw } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -138,46 +137,45 @@ const mergeAvailableSidebarItems = (
// Styles
// ---------------------------------------------------------------------------
-const styles = createStaticStyles(({ css }) => ({
- accordionGroup: css`
- margin-inline: -5px;
- padding: 4px;
- border: 1px dashed ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
- `,
- item: css`
- height: 40px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
- transition: background 0.2s ease-in-out;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- itemDragging: css`
- opacity: 0;
- `,
- overlay: css`
- height: 40px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorBgElevated};
- box-shadow: ${cssVar.boxShadowSecondary};
- `,
- spacerLine: css`
- flex: 1;
- block-size: 1px;
- background: ${cssVar.colorBorderSecondary};
- `,
- footer: css`
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: 8px;
- padding-block-start: 16px;
- `,
-}));
+const styles = stylex.create({
+ accordionGroup: {
+ marginInline: '-5px',
+ padding: '4px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+ item: {
+ height: '40px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.2s ease-in-out',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ itemDragging: { opacity: 0 },
+ overlay: {
+ height: '40px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgElevated,
+ backgroundImage: 'none',
+ boxShadow: cssVar.boxShadowSecondary,
+ },
+ spacerLine: {
+ flex: '1',
+ blockSize: '1px',
+ backgroundColor: cssVar.colorBorderSecondary,
+ backgroundImage: 'none',
+ },
+ footer: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ gap: '8px',
+ paddingBlockStart: '16px',
+ },
+});
// ---------------------------------------------------------------------------
// SortableItem
@@ -214,10 +212,14 @@ const SortableItem = memo<{
<Flexbox
horizontal
align={'center'}
- className={isDragging ? cx(styles.item, styles.itemDragging) : styles.item}
gap={4}
justify={'space-between'}
ref={setNodeRef}
+ className={
+ isDragging
+ ? stylex.props(styles.item, styles.itemDragging).className
+ : stylex.props(styles.item).className
+ }
style={{
opacity: isHidden && !isDragging ? 0.5 : undefined,
transform: CSS.Translate.toString(transform),
@@ -270,9 +272,13 @@ const SpacerSortableItem = memo(() => {
<Flexbox
horizontal
align={'center'}
- className={isDragging ? cx(styles.item, styles.itemDragging) : styles.item}
gap={8}
ref={setNodeRef}
+ className={
+ isDragging
+ ? stylex.props(styles.item, styles.itemDragging).className
+ : stylex.props(styles.item).className
+ }
style={{
transform: CSS.Translate.toString(transform),
transition,
@@ -287,11 +293,11 @@ const SpacerSortableItem = memo(() => {
<Icon icon={GripVertical} size={14} style={{ color: cssVar.colorTextQuaternary }} />
</Flexbox>
<Icon icon={ArrowDownToLine} size={14} style={{ color: cssVar.colorTextQuaternary }} />
- <div className={styles.spacerLine} />
+ <div {...stylex.props(styles.spacerLine)} />
<Text style={{ fontSize: 12 }} type={'secondary'}>
{t('navPanel.bottomDivider' as any)}
</Text>
- <div className={styles.spacerLine} />
+ <div {...stylex.props(styles.spacerLine)} />
</Flexbox>
);
});
@@ -300,13 +306,13 @@ const BoundSpacerItem = memo(() => {
const { t } = useTranslation('common');
return (
- <Flexbox horizontal align={'center'} className={styles.item} gap={8}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.item).className} gap={8}>
<Icon icon={ArrowDownToLine} size={14} style={{ color: cssVar.colorTextQuaternary }} />
- <div className={styles.spacerLine} />
+ <div {...stylex.props(styles.spacerLine)} />
<Text style={{ fontSize: 12 }} type={'secondary'}>
{t('navPanel.bottomDivider' as any)}
</Text>
- <div className={styles.spacerLine} />
+ <div {...stylex.props(styles.spacerLine)} />
</Flexbox>
);
});
@@ -322,7 +328,7 @@ const AccordionGroup = memo<{ children: React.ReactNode }>(({ children }) => {
return (
<div
- className={styles.accordionGroup}
+ className={stylex.props(styles.accordionGroup).className}
ref={setNodeRef}
style={{
transform: CSS.Translate.toString(transform),
@@ -346,7 +352,12 @@ const OverlayItem = memo<{ id: string }>(({ id }) => {
// Accordion group overlay: render a compact representation
if (id === ACCORDION_GROUP_ID) {
return (
- <Flexbox horizontal align={'center'} className={styles.overlay} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.overlay).className}
+ gap={8}
+ >
<Icon icon={GripVertical} size={14} style={{ color: cssVar.colorTextQuaternary }} />
<Text>{t(agentLabelKey as any)}</Text>
<Text type={'secondary'}>+ {t('recents' as any)}</Text>
@@ -356,7 +367,12 @@ const OverlayItem = memo<{ id: string }>(({ id }) => {
if (isSpacer(id)) {
return (
- <Flexbox horizontal align={'center'} className={styles.overlay} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.overlay).className}
+ gap={8}
+ >
<Icon icon={GripVertical} size={14} style={{ color: cssVar.colorTextQuaternary }} />
<Icon icon={ArrowDownToLine} size={14} style={{ color: cssVar.colorTextQuaternary }} />
<Text style={{ fontSize: 12 }} type={'secondary'}>
@@ -372,7 +388,7 @@ const OverlayItem = memo<{ id: string }>(({ id }) => {
const labelKey = item.id === 'agent' ? agentLabelKey : item.labelKey;
return (
- <Flexbox horizontal align={'center'} className={styles.overlay} gap={8}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.overlay).className} gap={8}>
<Icon icon={GripVertical} size={14} style={{ color: cssVar.colorTextQuaternary }} />
{route?.icon && <Icon icon={route.icon} size={18} />}
<Text>{t(labelKey as any)}</Text>
@@ -589,7 +605,7 @@ const CustomizeSidebarContent = memo(() => {
document.body,
)}
</DndContext>
- <div className={styles.footer}>
+ <div {...stylex.props(styles.footer)}>
<Button
block
htmlType="button"
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx b/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
index 7a55c04be5a..5a6cc02e8bd 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
+++ b/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
@@ -1,7 +1,9 @@
'use client';
import type { NotificationMetadata } from '@lobechat/types';
-import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { BellOffIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,18 +24,15 @@ import NotificationItem from './NotificationItem';
import type { NotificationListHandle } from './useNotificationList';
import { PAGE_SIZE, useNotificationList } from './useNotificationList';
-const styles = createStaticStyles(({ css }) => ({
- // colorFillSecondary rather than colorBorderSecondary: see the note in
- // ../InboxModal/index.tsx — the border token collapses into the modal's own
- // surface in dark mode, which erased the separator between rows.
- item: css`
- border-block-end: 1px solid ${cssVar.colorFillSecondary};
-
- &:hover {
- background: ${cssVar.colorFillSecondary};
- }
- `,
-}));
+const styles = stylex.create({
+ item: {
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorFillSecondary,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
interface ContentProps {
category?: string;
@@ -182,7 +181,7 @@ const Content = memo<ContentProps>(
// clip once several transfers (with their manifest rows) stack up.
const transferItems = currentUserId
? liveRequests.map((request) => (
- <Flexbox className={styles.item} key={request.id}>
+ <Flexbox className={stylex.props(styles.item).className} key={request.id}>
<TransferRequestItem
currentUserId={currentUserId}
request={request}
@@ -216,7 +215,7 @@ const Content = memo<ContentProps>(
<VList ref={virtuaRef} style={{ flex: 1 }} onScroll={handleScroll}>
{transferItems}
{visibleNotifications.map((item) => (
- <Flexbox className={styles.item} key={item.id}>
+ <Flexbox className={stylex.props(styles.item).className} key={item.id}>
<NotificationItem
actionUrl={item.actionUrl}
content={item.content}
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx b/src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx
index 1215c7c9f2f..c498d32a227 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx
+++ b/src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx
@@ -7,13 +7,13 @@ import {
Block,
Button,
ContextMenuTrigger,
- createStaticStyles,
- cssVar,
Flexbox,
Icon,
Text,
useModalContext,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ArchiveIcon, BellIcon, ImageIcon, MegaphoneIcon, VideoIcon } from 'lucide-react';
import type { MouseEvent } from 'react';
import { memo, useCallback, useMemo } from 'react';
@@ -29,18 +29,17 @@ import { createNotificationDetailModal } from './NotificationDetailModal';
import { toNotificationPreview } from './toNotificationPreview';
import { useNotificationAgentMeta } from './useNotificationAgentMeta';
-const styles = createStaticStyles(({ css }) => ({
- unreadDot: css`
- flex-shrink: 0;
-
- width: 8px;
- height: 8px;
- margin-block-start: 7px;
- border-radius: 50%;
-
- background: ${cssVar.colorInfo};
- `,
-}));
+const styles = stylex.create({
+ unreadDot: {
+ flexShrink: 0,
+ width: '8px',
+ height: '8px',
+ marginBlockStart: '7px',
+ borderRadius: '50%',
+ backgroundColor: cssVar.colorInfo,
+ backgroundImage: 'none',
+ },
+});
const TYPE_ICON_MAP: Record<string, typeof BellIcon> = {
image_generation_completed: ImageIcon,
@@ -148,7 +147,7 @@ const NotificationItem = memo<NotificationItemProps>(
onClick={handleOpenDetail}
>
<Flexbox horizontal align="flex-start" gap={12}>
- {!isRead && <span className={styles.unreadDot} />}
+ {!isRead && <span {...stylex.props(styles.unreadDot)} />}
{actor ? (
<Avatar
alt={actor.name}
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/index.tsx b/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
index e693359d2f0..a9f07eee2de 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
+++ b/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
@@ -4,8 +4,6 @@ import {
ActionIcon,
Button,
createModal,
- createStaticStyles,
- cssVar,
DropdownMenu,
Flexbox,
ModalClose,
@@ -15,6 +13,8 @@ import {
Text,
toast,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import type { LucideIcon } from 'lucide-react';
import {
ArchiveIcon,
@@ -58,60 +58,38 @@ const Content = dynamic(() => import('./Content'), {
ssr: false,
});
-const styles = createStaticStyles(({ css }) => ({
- body: css`
- overflow: hidden;
- min-height: 0;
- `,
- categoryList: css`
- overflow-y: auto;
- overscroll-behavior: contain;
- flex: 1;
- `,
- // Dividers inside this modal use colorFillSecondary, not colorBorderSecondary.
- // In the dark palette colorBorderSecondary and colorBgElevated are the same
- // step of the neutral scale, so every border drawn on the modal's own surface
- // resolves to the surface colour and disappears — the panel reads as one
- // undifferentiated block. colorFillSecondary is alpha-based, so it lands on
- // #f0f0f0 over the light surface (identical to what the border token gave)
- // and stays visible over the dark one.
- header: css`
- flex: none;
- gap: 0;
- padding: 0;
- border-block-end: 1px solid ${cssVar.colorFillSecondary};
- `,
- headerMain: css`
- min-width: 0;
- padding-block: 12px;
- padding-inline: 16px;
- `,
- headerTitle: css`
- flex: none;
-
- box-sizing: border-box;
- width: clamp(160px, 22vw, 220px);
- padding-inline: 16px;
-
- white-space: nowrap;
- `,
- main: css`
- overflow: hidden;
- min-width: 0;
- `,
- root: css`
- overflow: hidden;
- `,
- sidebar: css`
- overflow: hidden;
- flex: none;
-
- box-sizing: border-box;
- width: clamp(160px, 22vw, 220px);
- padding: 8px;
- border-inline-end: 1px solid ${cssVar.colorFillSecondary};
- `,
-}));
+const styles = stylex.create({
+ body: { overflow: 'hidden', minHeight: '0' },
+ categoryList: { overflowY: 'auto', overscrollBehavior: 'contain', flex: '1' },
+ header: {
+ flex: 'none',
+ gap: '0',
+ padding: '0',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorFillSecondary,
+ },
+ headerMain: { minWidth: '0', paddingBlock: '12px', paddingInline: '16px' },
+ headerTitle: {
+ flex: 'none',
+ boxSizing: 'border-box',
+ width: 'clamp(160px, 22vw, 220px)',
+ paddingInline: '16px',
+ whiteSpace: 'nowrap',
+ },
+ main: { overflow: 'hidden', minWidth: '0' },
+ root: { overflow: 'hidden' },
+ sidebar: {
+ overflow: 'hidden',
+ flex: 'none',
+ boxSizing: 'border-box',
+ width: 'clamp(160px, 22vw, 220px)',
+ padding: '8px',
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorFillSecondary,
+ },
+});
interface CategoryCount {
category: string;
@@ -325,15 +303,15 @@ const InboxModalContent = memo(() => {
// would visibly do nothing — keep it disabled then.
const archivableTotalCount = Math.max(0, allTotalCount - liveTransferCount);
return (
- <Flexbox className={styles.root} height={'100%'}>
- <ModalHeader className={styles.header}>
- <Flexbox className={styles.headerTitle} justify="center">
+ <Flexbox className={stylex.props(styles.root).className} height={'100%'}>
+ <ModalHeader className={stylex.props(styles.header).className}>
+ <Flexbox className={stylex.props(styles.headerTitle).className} justify="center">
<ModalTitle>{t('inbox.title')}</ModalTitle>
</Flexbox>
<Flexbox
horizontal
align="center"
- className={styles.headerMain}
+ className={stylex.props(styles.headerMain).className}
flex={1}
justify="space-between"
>
@@ -393,8 +371,8 @@ const InboxModalContent = memo(() => {
</Flexbox>
</Flexbox>
</ModalHeader>
- <Flexbox horizontal className={styles.body} flex={1}>
- <Flexbox className={styles.sidebar} gap={4}>
+ <Flexbox horizontal className={stylex.props(styles.body).className} flex={1}>
+ <Flexbox className={stylex.props(styles.sidebar).className} gap={4}>
<NavItem
active={navigationFilter === ALL_FILTER}
icon={BellIcon}
@@ -408,7 +386,7 @@ const InboxModalContent = memo(() => {
}
onClick={() => setNavigationFilter(ALL_FILTER)}
/>
- <Flexbox className={styles.categoryList} gap={4}>
+ <Flexbox className={stylex.props(styles.categoryList).className} gap={4}>
{isNavigationCountsLoading ? (
<SkeletonList rows={4} />
) : (
@@ -445,7 +423,7 @@ const InboxModalContent = memo(() => {
)}
</Flexbox>
</Flexbox>
- <Flexbox className={styles.main} flex={1}>
+ <Flexbox className={stylex.props(styles.main).className} flex={1}>
<Flexbox flex={1} style={{ minHeight: 0 }}>
<Content
category={category}
diff --git a/src/features/HomeSidebar/Header/components/User.tsx b/src/features/HomeSidebar/Header/components/User.tsx
index 856688a9384..9913aeb3aec 100644
--- a/src/features/HomeSidebar/Header/components/User.tsx
+++ b/src/features/HomeSidebar/Header/components/User.tsx
@@ -1,6 +1,8 @@
'use client';
-import { Block, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ChevronDownIcon } from 'lucide-react';
import { memo } from 'react';
@@ -17,11 +19,7 @@ import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
// name) paints the system text-selection highlight across the whole row;
// that bright blue is heavier than the Sidebar's active-route fill below
// and inverts the visual hierarchy.
-const styles = createStaticStyles(({ css }) => ({
- trigger: css`
- user-select: none;
- `,
-}));
+const styles = stylex.create({ trigger: { userSelect: 'none' } });
const User = memo<{ lite?: boolean }>(({ lite }) => {
const [nickname, username, isSignedIn] = useUserStore((s) => [
@@ -43,7 +41,7 @@ const User = memo<{ lite?: boolean }>(({ lite }) => {
clickable
horizontal
align={'center'}
- className={styles.trigger}
+ className={stylex.props(styles.trigger).className}
gap={8}
paddingBlock={2}
variant={'borderless'}
diff --git a/src/features/MCPPluginDetail/Header.tsx b/src/features/MCPPluginDetail/Header.tsx
index a4d49fb683b..d945e29aa68 100644
--- a/src/features/MCPPluginDetail/Header.tsx
+++ b/src/features/MCPPluginDetail/Header.tsx
@@ -16,6 +16,8 @@ import {
Tooltip,
useResponsive,
} from '@lobehub/ui';
+import { cssVar as vars } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import {
BookmarkIcon,
BookmarkMinusIcon,
@@ -43,15 +45,15 @@ import InstallationIcon from '../../components/MCPDepsIcon';
import PublishedTime from '../../components/PublishedTime';
import { useDetailContext } from './DetailProvider';
+const timeStyles = stylex.create({
+ time: { fontSize: '12px', color: vars.colorTextDescription },
+});
+
const styles = createStaticStyles(({ css }) => {
return {
desc: css`
color: ${cssVar.colorTextSecondary};
`,
- time: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
version: css`
font-family: ${cssVar.fontFamilyCode};
font-size: 13px;
@@ -234,7 +236,7 @@ const Header = memo<{ inModal?: boolean; mobile?: boolean }>(({ mobile: isMobile
)}
{isClaimed && <Tag size={'small'}>{t('isClaimed')}</Tag>}
<Icon icon={DotIcon} />
- <PublishedTime className={styles.time} date={(updatedAt || createdAt) as string} />
+ <PublishedTime date={(updatedAt || createdAt) as string} xstyle={timeStyles.time} />
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/features/MessageList/AgentConversation.test.tsx b/src/features/MessageList/AgentConversation.test.tsx
index b07a67dffab..470d06c5c9c 100644
--- a/src/features/MessageList/AgentConversation.test.tsx
+++ b/src/features/MessageList/AgentConversation.test.tsx
@@ -85,7 +85,9 @@ describe('AgentConversation avatar', () => {
}),
);
- expect(screen.getByTestId('menu')).toHaveTextContent('delete,divider,channel-archive,channel-delete');
+ expect(screen.getByTestId('menu')).toHaveTextContent(
+ 'delete,divider,channel-archive,channel-delete',
+ );
});
it('offers unarchive instead for an archived direct Channel', () => {
diff --git a/src/features/PluginSettings/index.tsx b/src/features/PluginSettings/index.tsx
index b4cf256ac14..70b01ef123a 100644
--- a/src/features/PluginSettings/index.tsx
+++ b/src/features/PluginSettings/index.tsx
@@ -1,5 +1,9 @@
import { type ToolManifestSettings } from '@lobechat/types';
-import { createStaticStyles, Markdown } from '@lobehub/ui';
+import {
+ // oxlint-disable-next-line stylex-migration/no-emotion-styles -- rendered Markdown paragraphs get no className
+ createStaticStyles,
+ Markdown,
+} from '@lobehub/ui';
import { Form, useForm } from '@lobehub/ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
@@ -30,7 +34,7 @@ interface PluginSettingsConfigProps {
schema: ToolManifestSettings;
}
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const fallback = createStaticStyles(({ css, cssVar }) => ({
markdown: css`
p {
color: ${cssVar.colorTextDescription};
@@ -70,7 +74,7 @@ const PluginSettingsConfig = memo<PluginSettingsConfigProps>(({ schema, id }) =>
/>
),
desc: item.desc && (
- <Markdown className={styles.markdown} variant={'chat'}>
+ <Markdown className={fallback.markdown} variant={'chat'}>
{item.desc as string}
</Markdown>
),
diff --git a/src/features/Setting/Footer.tsx b/src/features/Setting/Footer.tsx
index 3e83c1aa1f7..6b438b19379 100644
--- a/src/features/Setting/Footer.tsx
+++ b/src/features/Setting/Footer.tsx
@@ -1,7 +1,9 @@
'use client';
import { BRANDING_NAME } from '@lobechat/business-const';
-import { Center, createStaticStyles, Flexbox, Icon } from '@lobehub/ui';
+import { Center, Flexbox, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { MessageSquareHeart } from 'lucide-react';
import { type PropsWithChildren } from 'react';
import { memo } from 'react';
@@ -13,12 +15,12 @@ import { GITHUB, GITHUB_ISSUES } from '@/const/url';
import { useServerConfigStore } from '@/store/serverConfig';
import { isOnServerSide } from '@/utils/env';
-const styles = createStaticStyles(
- ({ css, cssVar }) => css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
-);
+const styles = stylex.create({
+ footer: {
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ },
+});
export const LayoutSettingsFooterClassName = 'settings-layout-footer';
@@ -69,7 +71,14 @@ const Footer = memo<PropsWithChildren>(() => {
return hideGitHubEngagementFooter ? null : (
<Flexbox className={LayoutSettingsFooterClassName} justify={'flex-end'}>
- <Center horizontal as={'footer'} className={styles} flex={'none'} padding={16} width={'100%'}>
+ <Center
+ horizontal
+ as={'footer'}
+ className={stylex.props(styles.footer).className}
+ flex={'none'}
+ padding={16}
+ width={'100%'}
+ >
<div style={{ textAlign: 'center' }}>
<Icon icon={MessageSquareHeart} /> {`${t('footer.title')} `}
<a
diff --git a/src/features/Settings/Layout/index.tsx b/src/features/Settings/Layout/index.tsx
index 8970d995202..bfa6d746622 100644
--- a/src/features/Settings/Layout/index.tsx
+++ b/src/features/Settings/Layout/index.tsx
@@ -1,6 +1,7 @@
'use client';
import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { type FC } from 'react';
import { Outlet } from 'react-router';
@@ -19,7 +20,7 @@ const Layout: FC = () => {
}}
>
<SideBar />
- <Flexbox className={styles.mainContainer} flex={1} height={'100%'}>
+ <Flexbox className={stylex.props(styles.mainContainer).className} flex={1} height={'100%'}>
<RouteSkeletonChromeProvider>
<Outlet />
</RouteSkeletonChromeProvider>
diff --git a/src/features/Settings/Layout/style.ts b/src/features/Settings/Layout/style.ts
index ea3f8047a08..c35e1f33419 100644
--- a/src/features/Settings/Layout/style.ts
+++ b/src/features/Settings/Layout/style.ts
@@ -1,10 +1,11 @@
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- // Main container
- mainContainer: css`
- position: relative;
- overflow: hidden;
- background: ${cssVar.colorBgContainer};
- `,
-}));
+export const styles = stylex.create({
+ mainContainer: {
+ position: 'relative',
+ overflow: 'hidden',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
diff --git a/src/features/Settings/about/features/About.tsx b/src/features/Settings/about/features/About.tsx
index 29295de9ca2..7a6ce77656e 100644
--- a/src/features/Settings/about/features/About.tsx
+++ b/src/features/Settings/about/features/About.tsx
@@ -6,8 +6,10 @@ import SiRss from '@icons-pack/react-simple-icons/icons/SiRss';
import SiX from '@icons-pack/react-simple-icons/icons/SiX';
import SiYoutube from '@icons-pack/react-simple-icons/icons/SiYoutube';
import { BRANDING_EMAIL, BRANDING_NAME, SOCIAL_URL } from '@lobechat/business-const';
-import { createStaticStyles, Divider, Flexbox } from '@lobehub/ui';
+import { Divider, Flexbox } from '@lobehub/ui';
import { Form } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,13 +20,9 @@ import ItemCard from './ItemCard';
import ItemLink from './ItemLink';
import Version from './Version';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- title: css`
- font-size: 14px;
- font-weight: bold;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+const styles = stylex.create({
+ title: { fontSize: '14px', fontWeight: 'bold', color: cssVar.colorTextSecondary },
+});
const About = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation('common');
@@ -77,7 +75,7 @@ const About = memo<{ mobile?: boolean }>(({ mobile }) => {
]}
/>
<Divider style={{ marginBlock: 0 }} />
- <div className={styles.title}>{t('contact')}</div>
+ <div {...stylex.props(styles.title)}>{t('contact')}</div>
<AboutList
ItemRender={ItemLink}
items={[
@@ -99,7 +97,7 @@ const About = memo<{ mobile?: boolean }>(({ mobile }) => {
]}
/>
<Divider style={{ marginBlock: 0 }} />
- <div className={styles.title}>{t('legal')}</div>
+ <div {...stylex.props(styles.title)}>{t('legal')}</div>
<AboutList
ItemRender={ItemLink}
items={[
diff --git a/src/features/Settings/about/features/Version.tsx b/src/features/Settings/about/features/Version.tsx
index 4b0c6fe4605..dc7f07d1d56 100644
--- a/src/features/Settings/about/features/Version.tsx
+++ b/src/features/Settings/about/features/Version.tsx
@@ -4,7 +4,9 @@ import {
type UpdaterState,
useWatchBroadcast,
} from '@lobechat/electron-client-ipc';
-import { Block, Button, createStaticStyles, Flexbox, Tag, Tooltip } from '@lobehub/ui';
+import { Block, Button, Flexbox, Tag, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -47,11 +49,7 @@ const OtaVersionTag = memo(() => {
OtaVersionTag.displayName = 'OtaVersionTag';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- logo: css`
- border-radius: calc(${cssVar.borderRadiusLG} * 2);
- `,
-}));
+const styles = stylex.create({ logo: { borderRadius: `calc(${cssVar.borderRadiusLG} * 2)` } });
const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
const hasNewVersion = useNewVersion();
@@ -196,7 +194,7 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
<Block
clickable
align={'center'}
- className={styles.logo}
+ className={stylex.props(styles.logo).className}
height={64}
justify={'center'}
width={64}
diff --git a/src/features/Settings/apikey/features/ApiKey.tsx b/src/features/Settings/apikey/features/ApiKey.tsx
index 67dfab6708a..63c6e535136 100644
--- a/src/features/Settings/apikey/features/ApiKey.tsx
+++ b/src/features/Settings/apikey/features/ApiKey.tsx
@@ -6,7 +6,6 @@ import {
Button,
Center,
confirmModal,
- createStaticStyles,
DropdownMenu,
Empty,
Flexbox,
@@ -14,6 +13,8 @@ import {
Text,
toast,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { useMutation } from '@tanstack/react-query';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
@@ -39,39 +40,36 @@ import { useWorkspaceApiKeyPolicy } from '../WorkspaceApiKeyPolicyContext';
import ApiKeyDetail from './ApiKeyDetail';
import { ApiKeyDisplay, createApiKeyModal } from './index';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
- padding-block: 16px;
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorBgContainer};
- `,
- expired: css`
- color: ${cssVar.colorError};
- `,
- header: css`
- display: flex;
- gap: 16px;
- align-items: flex-start;
- justify-content: space-between;
-
- padding-block-end: 16px;
- padding-inline: 24px;
- `,
- /* Dates and "never used / never expires" placeholders read as metadata, not
- content — keep them quieter than the name and key. */
- muted: css`
- color: ${cssVar.colorTextTertiary};
- `,
- /* The name doubles as the entry point into the detail drawer. */
- nameLink: css`
- font-weight: 500;
-
- tr:hover & {
- color: ${cssVar.colorLink};
- }
- `,
-}));
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ paddingBlock: '16px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ expired: {
+ color: cssVar.colorError,
+ },
+ header: {
+ display: 'flex',
+ gap: '16px',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ paddingBlockEnd: '16px',
+ paddingInline: '24px',
+ },
+ // Dates and "never used / never expires" placeholders read as metadata, not
+ // content — keep them quieter than the name and key.
+ muted: {
+ color: cssVar.colorTextTertiary,
+ },
+ // The name doubles as the entry point into the detail drawer.
+ nameLink: {
+ fontWeight: 500,
+ color: { 'default': null, ':is(tr:hover *)': cssVar.colorLink },
+ },
+});
dayjs.extend(relativeTime);
@@ -173,7 +171,7 @@ const ApiKey: FC = () => {
// the row reads as navigable rather than inert.
render: (apiKey) => (
<Flexbox horizontal align={'center'} gap={8}>
- <span className={styles.nameLink}>{apiKey.name}</span>
+ <span {...stylex.props(styles.nameLink)}>{apiKey.name}</span>
{apiKey.enabled === false && <Tag>{t('apikey.status.disabled')}</Tag>}
</Flexbox>
),
@@ -228,13 +226,13 @@ const ApiKey: FC = () => {
render: (apiKey) =>
apiKey.expiresAt ? (
<span
- className={isExpired(apiKey) ? styles.expired : undefined}
+ {...stylex.props(isExpired(apiKey) ? styles.expired : null)}
title={apiKey.expiresAt.toLocaleString()}
>
{isExpired(apiKey) ? t('apikey.status.expired') : apiKey.expiresAt.toLocaleDateString()}
</span>
) : (
- <span className={styles.muted}>{t('apikey.display.neverExpires')}</span>
+ <span {...stylex.props(styles.muted)}>{t('apikey.display.neverExpires')}</span>
),
title: t('apikey.list.columns.expiresAt'),
width: 130,
@@ -249,7 +247,7 @@ const ApiKey: FC = () => {
{dayjs(apiKey.lastUsedAt).fromNow()}
</span>
) : (
- <span className={styles.muted}>{t('apikey.display.neverUsed')}</span>
+ <span {...stylex.props(styles.muted)}>{t('apikey.display.neverUsed')}</span>
),
title: t('apikey.list.columns.lastUsedAt'),
},
@@ -294,8 +292,8 @@ const ApiKey: FC = () => {
];
return (
- <div className={styles.container}>
- <div className={styles.header}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.header)}>
<Flexbox gap={4}>
<Text as={'h3'} style={{ fontSize: 16, fontWeight: 500, margin: 0 }}>
{t('apikey.list.title')}
diff --git a/src/features/Settings/apikey/features/ApiKeyDetail.tsx b/src/features/Settings/apikey/features/ApiKeyDetail.tsx
index 91b7c4e306f..babb73e21d2 100644
--- a/src/features/Settings/apikey/features/ApiKeyDetail.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyDetail.tsx
@@ -1,14 +1,8 @@
'use client';
-import {
- Button,
- confirmModal,
- createStaticStyles,
- Drawer,
- Flexbox,
- Switch,
- Text,
-} from '@lobehub/ui';
+import { Button, confirmModal, Drawer, Flexbox, Switch, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Pencil, Trash } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -23,36 +17,19 @@ import { type ApiKeyItem, type UpdateApiKeyParams } from '@/types/apiKey';
import ScopeSelector, { ScopeOverview } from './ApiKeyModal/ScopeSelector';
import { ApiKeyDisplay, EditableCell } from './index';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- fullAccessCard: css`
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
- `,
- label: css`
- flex: none;
- width: 96px;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- metaRow: css`
- display: flex;
- gap: 16px;
- align-items: center;
- min-height: 28px;
- `,
- sectionTitle: css`
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- overflow: hidden;
- display: flex;
- align-items: center;
- font-size: 13px;
- `,
-}));
+const styles = stylex.create({
+ fullAccessCard: {
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+ label: { flex: 'none', width: '96px', fontSize: '12px', color: cssVar.colorTextSecondary },
+ metaRow: { display: 'flex', gap: '16px', alignItems: 'center', minHeight: '28px' },
+ sectionTitle: { fontSize: '13px', fontWeight: 500, color: cssVar.colorTextSecondary },
+ value: { overflow: 'hidden', display: 'flex', alignItems: 'center', fontSize: '13px' },
+});
export interface ApiKeyDetailProps {
apiKey?: ApiKeyItem;
@@ -131,7 +108,7 @@ const ApiKeyScopeEditor: FC<ApiKeyScopeEditorProps> = ({ apiKey, canEdit, onUpda
return (
<Flexbox gap={8}>
{initialFullAccess ? (
- <Flexbox className={styles.fullAccessCard} gap={2}>
+ <Flexbox className={stylex.props(styles.fullAccessCard).className} gap={2}>
<Text style={{ fontSize: 14 }}>{t('apikey.scopes.fullAccess')}</Text>
<Text style={{ fontSize: 12 }} type={'secondary'}>
{t('apikey.form.fields.scopes.fullAccessDescription')}
@@ -181,9 +158,9 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
{apiKey && (
<Flexbox gap={24}>
<Flexbox gap={4}>
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.name')}</span>
- <span className={styles.value}>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.name')}</span>
+ <span {...stylex.props(styles.value)}>
<EditableCell
disabled={!canEdit}
placeholder={t('apikey.display.enterPlaceholder')}
@@ -197,9 +174,9 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
</span>
</div>
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.key')}</span>
- <span className={styles.value}>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.key')}</span>
+ <span {...stylex.props(styles.value)}>
{apiKey.isMine === false ? (
<span style={{ opacity: 0.5 }}>{`sk-lh-${'*'.repeat(12)}`}</span>
) : apiKey.keyDecryptionFailed ? (
@@ -213,27 +190,27 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
</div>
{apiKey.creator && (
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.creator')}</span>
- <span className={styles.value}>{apiKey.creator}</span>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.creator')}</span>
+ <span {...stylex.props(styles.value)}>{apiKey.creator}</span>
</div>
)}
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.detail.createdAt')}</span>
- <span className={styles.value}>{apiKey.createdAt.toLocaleString()}</span>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.detail.createdAt')}</span>
+ <span {...stylex.props(styles.value)}>{apiKey.createdAt.toLocaleString()}</span>
</div>
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.lastUsedAt')}</span>
- <span className={styles.value}>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.lastUsedAt')}</span>
+ <span {...stylex.props(styles.value)}>
{apiKey.lastUsedAt?.toLocaleString() || t('apikey.display.neverUsed')}
</span>
</div>
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.expiresAt')}</span>
- <span className={styles.value}>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.expiresAt')}</span>
+ <span {...stylex.props(styles.value)}>
<EditableCell
disabled={!canEdit}
placeholder={t('apikey.display.neverExpires')}
@@ -249,9 +226,9 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
</span>
</div>
- <div className={styles.metaRow}>
- <span className={styles.label}>{t('apikey.list.columns.status')}</span>
- <span className={styles.value} title={canEdit ? undefined : manageTooltip}>
+ <div {...stylex.props(styles.metaRow)}>
+ <span {...stylex.props(styles.label)}>{t('apikey.list.columns.status')}</span>
+ <span {...stylex.props(styles.value)} title={canEdit ? undefined : manageTooltip}>
<Switch
checked={!!apiKey.enabled}
disabled={!canEdit}
@@ -265,7 +242,9 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
</Flexbox>
<Flexbox gap={8}>
- <span className={styles.sectionTitle}>{t('apikey.form.fields.scopes.label')}</span>
+ <span {...stylex.props(styles.sectionTitle)}>
+ {t('apikey.form.fields.scopes.label')}
+ </span>
<ApiKeyScopeEditor
apiKey={apiKey}
canEdit={canEdit}
diff --git a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
index 2bec26eb0aa..ca017d19460 100644
--- a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
@@ -1,18 +1,19 @@
-import { ActionIcon, CopyButton, createStaticStyles, Flexbox } from '@lobehub/ui';
+import { ActionIcon, CopyButton, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Eye, EyeOff } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- key: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ key: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface ApiKeyDisplayProps {
apiKey?: string;
@@ -43,7 +44,7 @@ const ApiKeyDisplay: FC<ApiKeyDisplayProps> = ({ apiKey }) => {
return (
<Flexbox horizontal align={'center'} gap={4}>
- <span className={styles.key}>{displayValue}</span>
+ <span {...stylex.props(styles.key)}>{displayValue}</span>
<ActionIcon
icon={isVisible ? EyeOff : Eye}
size={'small'}
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
index 33a2fc4bb59..bddd1140c81 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
@@ -3,7 +3,6 @@
import {
Button,
CopyButton,
- createStaticStyles,
Flexbox,
Icon,
Input,
@@ -12,6 +11,8 @@ import {
useModalContext,
} from '@lobehub/ui';
import { Form, useForm } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import { type Dayjs } from 'dayjs';
import { CheckCircle2 } from 'lucide-react';
@@ -24,25 +25,25 @@ import { type CreateApiKeyParams } from '@/types/apiKey';
import ApiKeyDatePicker from '../ApiKeyDatePicker';
import ScopeSelector from './ScopeSelector';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- keyBlock: css`
- padding-block: 10px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- keyText: css`
- flex: 1;
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- word-break: break-all;
- `,
- successIcon: css`
- color: ${cssVar.colorSuccess};
- `,
-}));
+const styles = stylex.create({
+ keyBlock: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ keyText: {
+ flex: '1',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ wordBreak: 'break-all',
+ },
+ successIcon: { color: cssVar.colorSuccess },
+});
type FormValues = Omit<CreateApiKeyParams, 'expiresAt' | 'scopes'>;
@@ -114,11 +115,20 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
return (
<Flexbox gap={16}>
<Flexbox horizontal align={'center'} gap={8}>
- <Icon className={styles.successIcon} icon={CheckCircle2} size={18} />
+ <Icon
+ className={stylex.props(styles.successIcon).className}
+ icon={CheckCircle2}
+ size={18}
+ />
<Text style={{ fontWeight: 500 }}>{t('apikey.created.title')}</Text>
</Flexbox>
- <Flexbox horizontal align={'center'} className={styles.keyBlock} gap={8}>
- <span className={styles.keyText}>{createdKey}</span>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.keyBlock).className}
+ gap={8}
+ >
+ <span {...stylex.props(styles.keyText)}>{createdKey}</span>
<CopyButton content={createdKey} size={'small'} title={t('apikey.display.copy')} />
</Flexbox>
<Text style={{ fontSize: 12 }} type={'secondary'}>
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
index 883876bcbf5..33f67bb3e21 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
@@ -1,66 +1,60 @@
'use client';
-import { Checkbox, createStaticStyles, Flexbox, Switch, Text } from '@lobehub/ui';
+import { Checkbox, Flexbox, Switch, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Check } from 'lucide-react';
import type { FC } from 'react';
import { useTranslation } from 'react-i18next';
import type { ApiKeyScope } from '@/const/apiKeyScope';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- disabled: css`
- pointer-events: none;
- opacity: 0.45;
- `,
- fullAccessRow: css`
- display: flex;
- gap: 16px;
- align-items: center;
- justify-content: space-between;
-
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
- `,
- grid: css`
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: 12px 16px;
-
- /* same card treatment as the full-access row so the whole Scope block
- reads as one system */
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
- `,
- grantCheck: css`
- flex: none;
- color: ${cssVar.colorSuccess};
- `,
+const styles = stylex.create({
+ disabled: { pointerEvents: 'none', opacity: 0.45 },
+ fullAccessRow: {
+ display: 'flex',
+ gap: '16px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+ grid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ rowGap: '12px',
+ columnGap: '16px',
+ // same card treatment as the full-access row so the whole Scope block
+ // reads as one system
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+ grantCheck: { flex: 'none', color: cssVar.colorSuccess },
/* Granted-only list: one row per domain the key actually reaches. Hairline
separators, no card-in-card — the surrounding card is the container. */
- grantList: css`
- padding-block: 4px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
- `,
- grantRow: css`
- padding-block: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- groupTitle: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- scopeRow: css`
- flex-wrap: wrap;
- `,
-}));
+ grantList: {
+ paddingBlock: '4px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+ grantRow: {
+ paddingBlock: '12px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: { 'default': 'solid', ':last-child': 'none' },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ groupTitle: { fontSize: '12px', color: cssVar.colorTextSecondary },
+ scopeRow: { flexWrap: 'wrap' },
+});
/**
* Scope groups shown to the user. Most domains carry read and write scopes;
@@ -132,10 +126,16 @@ export const ScopeOverview: FC<ScopeOverviewProps> = ({ scopes }) => {
if (grants.length === 0) return <Text type={'secondary'}>{t('apikey.scopes.none')}</Text>;
return (
- <Flexbox className={styles.grantList}>
+ <Flexbox className={stylex.props(styles.grantList).className}>
{grants.map((grant) => (
- <Flexbox horizontal align={'center'} className={styles.grantRow} gap={10} key={grant.key}>
- <Check className={styles.grantCheck} size={16} />
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.grantRow).className}
+ gap={10}
+ key={grant.key}
+ >
+ <Check className={stylex.props(styles.grantCheck).className} size={16} />
<span style={{ fontSize: 13 }}>
<strong>{grant.label}</strong>
{t('apikey.scopes.grantJoin')}
@@ -180,7 +180,7 @@ const ScopeSelector: FC<ScopeSelectorProps> = ({
return (
<Flexbox gap={12}>
- <div className={styles.fullAccessRow}>
+ <div {...stylex.props(styles.fullAccessRow)}>
<Flexbox gap={2}>
<Text style={{ fontSize: 14 }}>{t('apikey.form.fields.scopes.fullAccess')}</Text>
<Text style={{ fontSize: 12 }} type={'secondary'}>
@@ -190,13 +190,13 @@ const ScopeSelector: FC<ScopeSelectorProps> = ({
<Switch checked={fullAccess} onChange={onFullAccessChange} />
</div>
- <div className={fullAccess ? styles.disabled : undefined}>
+ <div {...stylex.props(fullAccess ? styles.disabled : undefined)}>
<Flexbox gap={10}>
- <div className={styles.grid}>
+ <div {...stylex.props(styles.grid)}>
{SCOPE_GROUPS.map((group) => (
<Flexbox gap={4} key={group.key}>
- <span className={styles.groupTitle}>{t(group.label)}</span>
- <Flexbox horizontal className={styles.scopeRow} gap={12}>
+ <span {...stylex.props(styles.groupTitle)}>{t(group.label)}</span>
+ <Flexbox horizontal className={stylex.props(styles.scopeRow).className} gap={12}>
<Checkbox
checked={selectedSet.has(group.read)}
disabled={fullAccess}
diff --git a/src/features/Settings/apikey/features/EditableCell/index.tsx b/src/features/Settings/apikey/features/EditableCell/index.tsx
index 237d4cdc451..338c74a64c0 100644
--- a/src/features/Settings/apikey/features/EditableCell/index.tsx
+++ b/src/features/Settings/apikey/features/EditableCell/index.tsx
@@ -1,6 +1,8 @@
'use client';
-import { ActionIcon, createStaticStyles, cx, Input, toast } from '@lobehub/ui';
+import { ActionIcon, Input, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import { type Dayjs } from 'dayjs';
import { Check, Edit, X } from 'lucide-react';
@@ -27,52 +29,39 @@ export interface EditableCellProps {
}
// Style definitions
-const styles = createStaticStyles(({ css, cssVar }) => ({
- actionButtons: css`
- display: flex;
- flex-shrink: 0;
- gap: 4px;
- `,
- container: css`
- position: relative;
-
- display: flex;
- gap: 8px;
- align-items: center;
-
- min-height: 32px;
-
- &:hover .edit-button {
- opacity: 1;
- }
- `,
- content: css`
- min-width: 0;
- line-height: 1.5;
- color: ${cssVar.colorText};
- word-break: break-all;
- `,
- editButton: css`
- opacity: 0;
- transition: opacity 0.2s ease;
-
- &.edit-button {
- opacity: 0;
- }
- `,
- editingContainer: css`
- display: flex;
- gap: 8px;
- align-items: center;
- width: 100%;
- `,
- inputWrapper: css`
- flex: 1;
- `,
- textareaWrapper: css`
- flex: 1;
- `,
-}));
+const styles = stylex.create({
+ actionButtons: {
+ display: 'flex',
+ flexShrink: 0,
+ gap: '4px',
+ },
+ container: {
+ position: 'relative',
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ minHeight: '32px',
+ },
+ content: {
+ minWidth: 0,
+ lineHeight: 1.5,
+ color: cssVar.colorText,
+ wordBreak: 'break-all',
+ },
+ editButton: {
+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },
+ transition: 'opacity 0.2s ease',
+ },
+ editingContainer: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ width: '100%',
+ },
+ inputWrapper: {
+ flex: '1',
+ },
+});
// Main component implementation
const EditableCell = memo<EditableCellProps>(
@@ -147,7 +136,7 @@ const EditableCell = memo<EditableCellProps>(
switch (type) {
case 'text': {
return (
- <div className={styles.inputWrapper}>
+ <div {...stylex.props(styles.inputWrapper)}>
<Input
autoFocus
defaultValue={value as string}
@@ -174,9 +163,9 @@ const EditableCell = memo<EditableCellProps>(
// Text type editing mode, showing save and cancel buttons
if (type === 'text' && isEditing) {
return (
- <div className={styles.editingContainer}>
+ <div {...stylex.props(styles.editingContainer)}>
{renderEditMode()}
- <div className={styles.actionButtons}>
+ <div {...stylex.props(styles.actionButtons)}>
<ActionIcon icon={Check} size="small" onClick={handleSubmit} />
<ActionIcon icon={X} size="small" onClick={handleCancel} />
</div>
@@ -187,7 +176,7 @@ const EditableCell = memo<EditableCellProps>(
// Date type editing mode, showing date picker
if (type === 'date' && isEditing) {
return (
- <div className={styles.editingContainer}>
+ <div {...stylex.props(styles.editingContainer)}>
{renderEditMode()}
<ActionIcon icon={X} size="small" onClick={handleCancel} />
</div>
@@ -196,10 +185,10 @@ const EditableCell = memo<EditableCellProps>(
// Display mode
return (
- <div className={styles.container}>
- <div className={styles.content}>{formatDisplayValue(value)}</div>
+ <div {...stylex.props(styles.container, stylex.defaultMarker())}>
+ <div {...stylex.props(styles.content)}>{formatDisplayValue(value)}</div>
<ActionIcon
- className={cx(styles.editButton, 'edit-button')}
+ className={stylex.props(styles.editButton).className}
icon={Edit}
size="small"
onClick={handleEdit}
diff --git a/src/features/Settings/appearance/features/Font/FallbackFontList.tsx b/src/features/Settings/appearance/features/Font/FallbackFontList.tsx
index f5db2cf85f5..efd56b56dd0 100644
--- a/src/features/Settings/appearance/features/Font/FallbackFontList.tsx
+++ b/src/features/Settings/appearance/features/Font/FallbackFontList.tsx
@@ -3,13 +3,14 @@
import {
ActionIcon,
Button,
- createStaticStyles,
Flexbox,
Select,
type SelectOption,
SortableList,
Text,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { PlusIcon, XIcon } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,11 +19,9 @@ import { MAX_FALLBACK_FONTS } from './fontStack';
import { useFontFallbackStack } from './useFontFallbackStack';
const width = { width: 320 };
-const styles = createStaticStyles(({ css, cssVar }) => ({
- item: css`
- padding-inline: ${cssVar.paddingSM} ${cssVar.paddingXXS};
- `,
-}));
+const styles = stylex.create({
+ item: { paddingInlineStart: cssVar.paddingSM, paddingInlineEnd: cssVar.paddingXXS },
+});
interface FallbackFontListProps {
ariaLabel: string;
@@ -57,7 +56,7 @@ const FallbackFontList = ({
<SortableList.Item
horizontal
align={'center'}
- className={styles.item}
+ className={stylex.props(styles.item).className}
gap={4}
id={item.id}
justify={'space-between'}
diff --git a/src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx b/src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx
index b15cfca55b9..9e641942c4f 100644
--- a/src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx
+++ b/src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx
@@ -1,27 +1,26 @@
'use client';
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { Trans } from 'react-i18next';
import { OFFICIAL_SITE } from '@/const/url';
import { EntityLinkRender, type LobeLinkKind } from '@/features/EntityLink';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- bubble: css`
- align-self: flex-start;
-
- padding-block: 10px;
- padding-inline: 14px;
- border-radius: 12px;
-
- font-size: 14px;
- line-height: 1.8;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+const styles = stylex.create({
+ bubble: {
+ alignSelf: 'flex-start',
+ paddingBlock: '10px',
+ paddingInline: '14px',
+ borderRadius: '12px',
+ fontSize: '14px',
+ lineHeight: 1.8,
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface SampleLinkProps {
domain?: string;
@@ -44,7 +43,7 @@ const SampleLink = memo<SampleLinkProps>(({ kind, href, label, domain }) => (
));
const LinkIconPreview = memo(() => (
- <div className={styles.bubble}>
+ <div {...stylex.props(styles.bubble)}>
<Trans
i18nKey="settingChatAppearance.linkIcon.previewMessage"
ns="setting"
diff --git a/src/features/Settings/common/features/Appearance/Preview.tsx b/src/features/Settings/common/features/Appearance/Preview.tsx
index 6a31a12d305..9f6566d267e 100644
--- a/src/features/Settings/common/features/Appearance/Preview.tsx
+++ b/src/features/Settings/common/features/Appearance/Preview.tsx
@@ -1,57 +1,64 @@
-import { Block, createStaticStyles, cssVar, cx, Flexbox } from '@lobehub/ui';
+import { Block, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => {
- return {
- agent: css`
- padding: 4px;
- border-radius: 2px;
- `,
- agentActive: css`
- background: ${cssVar.colorFillSecondary};
- `,
- bubble: css`
- padding: 6px;
- border: 1px solid color-mix(in srgb, ${cssVar.colorBorderSecondary} 66%, transparent);
- border-radius: 3px;
- background-color: ${cssVar.colorBgContainer};
- `,
- container: css`
- overflow: hidden;
- justify-self: flex-end;
-
- width: 332px;
- height: 200px;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: ${cssVar.borderRadiusLG};
-
- background: ${cssVar.colorBgLayout};
- `,
- conversation: css`
- background: ${cssVar.colorBgContainer};
- `,
- header: css`
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- icon: css`
- flex: none;
- border-radius: 2px;
- background: ${cssVar.colorFillSecondary};
- `,
- input: css`
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- nav: css`
- padding: 4px;
- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
- background: ${cssVar.colorBgLayout};
- `,
- sidebar: css`
- padding: 4px;
- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
- background: ${cssVar.colorBgLayout};
- `,
- };
+const styles = stylex.create({
+ agent: { padding: '4px', borderRadius: '2px' },
+ agentActive: { backgroundColor: cssVar.colorFillSecondary, backgroundImage: 'none' },
+ bubble: {
+ padding: '6px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: `color-mix(in srgb, ${cssVar.colorBorderSecondary} 66%, transparent)`,
+ borderRadius: '3px',
+ backgroundColor: cssVar.colorBgContainer,
+ },
+ container: {
+ overflow: 'hidden',
+ justifySelf: 'flex-end',
+ width: '332px',
+ height: '200px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundImage: 'none',
+ },
+ conversation: { backgroundColor: cssVar.colorBgContainer, backgroundImage: 'none' },
+ header: {
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ icon: {
+ flex: 'none',
+ borderRadius: '2px',
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ input: {
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ nav: {
+ padding: '4px',
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundImage: 'none',
+ },
+ sidebar: {
+ padding: '4px',
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundImage: 'none',
+ },
});
const AgentItem = memo<{
@@ -62,19 +69,19 @@ const AgentItem = memo<{
<Flexbox
horizontal
align={'center'}
- className={cx(styles.agent, active && styles.agentActive)}
+ className={stylex.props(styles.agent, active && styles.agentActive).className}
gap={4}
width={'100%'}
>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={12}
style={{ background: color, borderRadius: '50%' }}
width={12}
/>
<Flexbox flex={1} gap={4}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'66%'}
style={{
@@ -82,7 +89,7 @@ const AgentItem = memo<{
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -96,21 +103,21 @@ const AgentItem = memo<{
const Preview = memo(() => {
const nav = (
- <Flexbox align={'center'} className={styles.nav} gap={8} width={24}>
+ <Flexbox align={'center'} className={stylex.props(styles.nav).className} gap={8} width={24}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={14}
style={{ border: `2px solid ${cssVar.colorPrimary}`, borderRadius: '50%' }}
width={14}
/>
- <Flexbox className={styles.icon} height={12} width={12} />
- <Flexbox className={styles.icon} height={12} width={12} />
- <Flexbox className={styles.icon} height={12} width={12} />
+ <Flexbox className={stylex.props(styles.icon).className} height={12} width={12} />
+ <Flexbox className={stylex.props(styles.icon).className} height={12} width={12} />
+ <Flexbox className={stylex.props(styles.icon).className} height={12} width={12} />
</Flexbox>
);
const sidebar = (
- <Flexbox className={styles.sidebar} gap={4} width={72}>
+ <Flexbox className={stylex.props(styles.sidebar).className} gap={4} width={72}>
<Flexbox
gap={4}
paddingInline={2}
@@ -118,9 +125,9 @@ const Preview = memo(() => {
paddingTop: 4,
}}
>
- <Flexbox className={styles.icon} height={8} width={'50%'} />
+ <Flexbox className={stylex.props(styles.icon).className} height={8} width={'50%'} />
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={8}
width={'100%'}
style={{
@@ -139,17 +146,22 @@ const Preview = memo(() => {
<Flexbox
horizontal
align={'center'}
- className={styles.header}
+ className={stylex.props(styles.header).className}
justify={'space-between'}
padding={4}
>
<Flexbox horizontal align={'center'} gap={4}>
- <Flexbox className={styles.icon} height={12} style={{ borderRadius: '50%' }} width={12} />
- <Flexbox className={styles.icon} height={8} width={32} />
+ <Flexbox
+ className={stylex.props(styles.icon).className}
+ height={12}
+ style={{ borderRadius: '50%' }}
+ width={12}
+ />
+ <Flexbox className={stylex.props(styles.icon).className} height={8} width={32} />
</Flexbox>
<Flexbox horizontal gap={2}>
- <Flexbox className={styles.icon} height={10} width={10} />
- <Flexbox className={styles.icon} height={10} width={10} />
+ <Flexbox className={stylex.props(styles.icon).className} height={10} width={10} />
+ <Flexbox className={stylex.props(styles.icon).className} height={10} width={10} />
</Flexbox>
</Flexbox>
);
@@ -157,13 +169,13 @@ const Preview = memo(() => {
const input = (
<Flexbox
align={'flex-end'}
- className={styles.input}
+ className={stylex.props(styles.input).className}
height={48}
justify={'flex-end'}
padding={8}
>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={12}
width={32}
style={{
@@ -174,16 +186,21 @@ const Preview = memo(() => {
);
return (
- <Block horizontal shadow className={styles.container} variant={'outlined'}>
+ <Block
+ horizontal
+ shadow
+ className={stylex.props(styles.container).className}
+ variant={'outlined'}
+ >
{nav}
{sidebar}
- <Flexbox className={styles.conversation} flex={1}>
+ <Flexbox className={stylex.props(styles.conversation).className} flex={1}>
{header}
<Flexbox align={'flex-start'} flex={1} gap={8} padding={6}>
<Flexbox horizontal align={'center'} gap={4} justify={'flex-end'} width={'100%'}>
- <Flexbox className={styles.bubble} gap={4} width={64}>
+ <Flexbox className={stylex.props(styles.bubble).className} gap={4} width={64}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -191,7 +208,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'66%'}
style={{
@@ -200,7 +217,7 @@ const Preview = memo(() => {
/>
</Flexbox>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={14}
style={{ borderRadius: '50%' }}
width={14}
@@ -208,14 +225,14 @@ const Preview = memo(() => {
</Flexbox>
<Flexbox horizontal gap={4}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={14}
style={{ borderRadius: '50%' }}
width={14}
/>
- <Flexbox className={styles.bubble} gap={4} width={160}>
+ <Flexbox className={stylex.props(styles.bubble).className} gap={4} width={160}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -223,7 +240,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'66%'}
style={{
@@ -231,7 +248,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -239,7 +256,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -247,7 +264,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'33%'}
style={{
@@ -257,9 +274,9 @@ const Preview = memo(() => {
</Flexbox>
</Flexbox>
<Flexbox horizontal align={'center'} gap={4} justify={'flex-end'} width={'100%'}>
- <Flexbox className={styles.bubble} gap={4} width={100}>
+ <Flexbox className={stylex.props(styles.bubble).className} gap={4} width={100}>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'100%'}
style={{
@@ -267,7 +284,7 @@ const Preview = memo(() => {
}}
/>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={2}
width={'66%'}
style={{
@@ -276,7 +293,7 @@ const Preview = memo(() => {
/>
</Flexbox>
<Flexbox
- className={styles.icon}
+ className={stylex.props(styles.icon).className}
height={14}
style={{ borderRadius: '50%' }}
width={14}
diff --git a/src/features/Settings/creds/features/CredItem.tsx b/src/features/Settings/creds/features/CredItem.tsx
index 9f95b79d9c4..ccdfc4d1c8e 100644
--- a/src/features/Settings/creds/features/CredItem.tsx
+++ b/src/features/Settings/creds/features/CredItem.tsx
@@ -12,6 +12,7 @@ import {
stopPropagation,
Tag,
} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import {
Eye,
File,
@@ -130,24 +131,24 @@ const CredItem: FC<CredItemProps> = memo(
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={16}
justify="space-between"
>
<Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>
- <div className={styles.icon}>{renderAvatar()}</div>
+ <div {...stylex.props(styles.icon)}>{renderAvatar()}</div>
<Flexbox gap={4} style={{ overflow: 'hidden' }}>
<Flexbox horizontal align="center" gap={8}>
- <span className={styles.title}>{cred.name}</span>
+ <span {...stylex.props(styles.title)}>{cred.name}</span>
<Tag color={typeColors[cred.type]}>{t(`creds.types.${cred.type}`)}</Tag>
{tags}
</Flexbox>
<Flexbox horizontal align="center" gap={8}>
- <code className={styles.key}>{cred.key}</code>
+ <code {...stylex.props(styles.key)}>{cred.key}</code>
{cred.description && (
<>
<span style={{ color: 'var(--lobe-color-text-quaternary)' }}>·</span>
- <span className={styles.description}>{cred.description}</span>
+ <span {...stylex.props(styles.description)}>{cred.description}</span>
</>
)}
</Flexbox>
diff --git a/src/features/Settings/creds/features/style.ts b/src/features/Settings/creds/features/style.ts
index decf8ee167c..a2a9e2414a5 100644
--- a/src/features/Settings/creds/features/style.ts
+++ b/src/features/Settings/creds/features/style.ts
@@ -1,38 +1,37 @@
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- padding-block: 12px;
- padding-inline: 0;
- `,
- description: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- icon: css`
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- width: 48px;
- height: 48px;
- border-radius: 12px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- key: css`
- font-family: monospace;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- title: css`
- font-size: 15px;
- font-weight: 500;
- color: ${cssVar.colorText};
- `,
-}));
+export const styles = stylex.create({
+ container: {
+ paddingBlock: '12px',
+ paddingInline: 0,
+ },
+ description: {
+ overflow: 'hidden',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ icon: {
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '48px',
+ height: '48px',
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ key: {
+ fontFamily: 'monospace',
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ },
+ title: {
+ fontSize: '15px',
+ fontWeight: 500,
+ color: cssVar.colorText,
+ },
+});
diff --git a/src/features/Settings/integrations/index.tsx b/src/features/Settings/integrations/index.tsx
index bf319c5ebcc..59aee89d384 100644
--- a/src/features/Settings/integrations/index.tsx
+++ b/src/features/Settings/integrations/index.tsx
@@ -1,17 +1,13 @@
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import IntegrationsSettings from '@/features/Integrations';
import SettingHeader from '@/features/Settings/features/SettingHeader';
-const styles = createStaticStyles(({ css }) => ({
- header: css`
- width: 100%;
- max-width: 760px;
- margin-inline: auto;
- `,
-}));
+const styles = stylex.create({
+ header: { width: '100%', maxWidth: '760px', marginInline: 'auto' },
+});
interface PageProps {
showSettingHeader?: boolean;
@@ -26,7 +22,7 @@ const Page = ({ showSettingHeader = true }: PageProps) => {
return (
<>
{showHeader && (
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<SettingHeader description={t('overview.description')} title={t('overview.title')} />
</div>
)}
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx
index 694450499d2..655741c76df 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx
@@ -1,6 +1,8 @@
'use client';
-import { Button, createStaticStyles, Flexbox, Tag, Text } from '@lobehub/ui';
+import { Button, Flexbox, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,21 +11,16 @@ import { type OAuthAppItem } from '@/types/oauthApp';
import ClientIdDisplay from '../ClientIdDisplay';
import SectionCard from './SectionCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- label: css`
- flex: none;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- row: css`
- display: flex;
- gap: 16px;
- align-items: center;
- justify-content: space-between;
-
- min-width: 0;
- `,
-}));
+const styles = stylex.create({
+ label: { flex: 'none', fontSize: '12px', color: cssVar.colorTextSecondary },
+ row: {
+ display: 'flex',
+ gap: '16px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ minWidth: '0',
+ },
+});
interface CredentialsCardProps {
canEdit: boolean;
@@ -77,19 +74,19 @@ const CredentialsCard: FC<CredentialsCardProps> = ({
return (
<SectionCard title={t('oauthApp.detail.credentials')}>
<Flexbox gap={16}>
- <div className={styles.row}>
- <span className={styles.label}>{t('oauthApp.detail.clientId')}</span>
+ <div {...stylex.props(styles.row)}>
+ <span {...stylex.props(styles.label)}>{t('oauthApp.detail.clientId')}</span>
<ClientIdDisplay clientId={detail.id} />
</div>
- <div className={styles.row}>
- <span className={styles.label}>{t('oauthApp.detail.type')}</span>
+ <div {...stylex.props(styles.row)}>
+ <span {...stylex.props(styles.label)}>{t('oauthApp.detail.type')}</span>
<Tag>{t(isWebApp ? 'oauthApp.type.webBadge' : 'oauthApp.type.badge')}</Tag>
</div>
{isWebApp && (
- <div className={styles.row}>
- <span className={styles.label}>{t('oauthApp.detail.clientSecret')}</span>
+ <div {...stylex.props(styles.row)}>
+ <span {...stylex.props(styles.label)}>{t('oauthApp.detail.clientSecret')}</span>
{renderSecretAction()}
</div>
)}
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx
index 2f4522f9477..7532950f636 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx
@@ -1,6 +1,8 @@
'use client';
-import { Button, createStaticStyles, Flexbox, Text, toast } from '@lobehub/ui';
+import { Button, Flexbox, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CopyIcon } from 'lucide-react';
import { type FC, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,27 +15,22 @@ import { getIntegrationEndpoints, resolveIssuer } from '../../integrationEndpoin
import { integrationPromptKey, integrationPromptValues } from '../../integrationPrompt';
import SectionCard from './SectionCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- prompt: css`
- overflow: auto;
-
- max-height: 180px;
- padding-block: 10px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
-
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- white-space: pre-wrap;
-
- background: ${cssVar.colorFillTertiary};
- `,
- subTitle: css`
- font-size: 13px;
- font-weight: 500;
- `,
-}));
+const styles = stylex.create({
+ prompt: {
+ overflow: 'auto',
+ maxHeight: '180px',
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorTextSecondary,
+ whiteSpace: 'pre-wrap',
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ subTitle: { fontSize: '13px', fontWeight: 500 },
+});
interface IntegrationCardProps {
applicationType?: string | null;
@@ -84,7 +81,7 @@ const IntegrationCard: FC<IntegrationCardProps> = ({ applicationType, clientId,
<Flexbox gap={12}>
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
<Flexbox gap={2}>
- <span className={styles.subTitle}>{t('oauthApp.integration.oneClick')}</span>
+ <span {...stylex.props(styles.subTitle)}>{t('oauthApp.integration.oneClick')}</span>
<Text style={{ fontSize: 12 }} type={'secondary'}>
{t('oauthApp.integration.oneClickDesc')}
</Text>
@@ -98,7 +95,7 @@ const IntegrationCard: FC<IntegrationCardProps> = ({ applicationType, clientId,
{t('oauthApp.integration.copyPrompt')}
</Button>
</Flexbox>
- <div className={styles.prompt}>{prompt}</div>
+ <div {...stylex.props(styles.prompt)}>{prompt}</div>
</Flexbox>
</SectionCard>
);
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx
index 5cc648de395..290b84627ab 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx
@@ -1,6 +1,8 @@
'use client';
-import { CopyButton, createStaticStyles, Flexbox, Icon, Text } from '@lobehub/ui';
+import { CopyButton, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ChevronDownIcon } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,34 +11,23 @@ import { type IntegrationEndpointKey } from '../../integrationEndpoints';
import { useIntegrationEndpoints } from './IntegrationCard';
import SectionCard from './SectionCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chevron: css`
- color: ${cssVar.colorTextTertiary};
- transition: transform 0.2s ease;
- `,
- chevronOpen: css`
- transform: rotate(180deg);
- `,
- header: css`
- cursor: pointer;
- user-select: none;
- `,
- label: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- value: css`
- padding-block: 2px;
- padding-inline: 12px 2px;
- border-radius: ${cssVar.borderRadius};
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 13px;
- overflow-wrap: anywhere;
-
- background: ${cssVar.colorFillQuaternary};
- `,
-}));
+const styles = stylex.create({
+ chevron: { color: cssVar.colorTextTertiary, transition: 'transform 0.2s ease' },
+ chevronOpen: { transform: 'rotate(180deg)' },
+ header: { cursor: 'pointer', userSelect: 'none' },
+ label: { fontSize: '12px', color: cssVar.colorTextSecondary },
+ value: {
+ paddingBlock: '2px',
+ paddingInlineStart: '12px',
+ paddingInlineEnd: '2px',
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '13px',
+ overflowWrap: 'anywhere',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+});
const LABEL_KEYS = {
authorization: 'oauthApp.integration.authorization',
@@ -66,7 +57,7 @@ const ManualSetupCard: FC<ManualSetupCardProps> = ({ applicationType }) => {
<SectionCard
extra={
<Icon
- className={open ? `${styles.chevron} ${styles.chevronOpen}` : styles.chevron}
+ className={stylex.props(styles.chevron, open && styles.chevronOpen).className}
icon={ChevronDownIcon}
size={16}
onClick={toggle}
@@ -75,7 +66,7 @@ const ManualSetupCard: FC<ManualSetupCardProps> = ({ applicationType }) => {
title={
<span
aria-expanded={open}
- className={styles.header}
+ {...stylex.props(styles.header)}
role={'button'}
tabIndex={0}
onClick={toggle}
@@ -97,8 +88,13 @@ const ManualSetupCard: FC<ManualSetupCardProps> = ({ applicationType }) => {
</Text>
{endpoints.map(({ key, url }) => (
<Flexbox gap={6} key={key}>
- <span className={styles.label}>{t(LABEL_KEYS[key])}</span>
- <Flexbox horizontal align={'center'} className={styles.value} gap={8}>
+ <span {...stylex.props(styles.label)}>{t(LABEL_KEYS[key])}</span>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.value).className}
+ gap={8}
+ >
<Flexbox flex={1}>{url}</Flexbox>
<CopyButton content={url} size={'small'} title={t('oauthApp.copy.tooltip')} />
</Flexbox>
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
index d36a13f3eee..4ddc40c2d36 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
@@ -1,7 +1,9 @@
'use client';
-import { ActionIcon, Button, createStaticStyles, Flexbox, Input, Text } from '@lobehub/ui';
+import { ActionIcon, Button, Flexbox, Input, Text } from '@lobehub/ui';
import { Form, useForm } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,33 +18,27 @@ import {
} from '../../redirectUris';
import SectionCard from './SectionCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- empty: css`
- padding: 16px;
- border: 1px dashed ${cssVar.colorBorder};
- border-radius: ${cssVar.borderRadius};
- `,
- fieldError: css`
- font-size: 12px;
- color: ${cssVar.colorError};
- `,
- listError: css`
- font-size: 14px;
- line-height: 1.5;
- color: ${cssVar.colorError};
- `,
- uri: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 13px;
- overflow-wrap: anywhere;
-
- background: ${cssVar.colorFillQuaternary};
- `,
-}));
+const styles = stylex.create({
+ empty: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadius,
+ },
+ fieldError: { fontSize: '12px', color: cssVar.colorError },
+ listError: { fontSize: '14px', lineHeight: 1.5, color: cssVar.colorError },
+ uri: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '13px',
+ overflowWrap: 'anywhere',
+ backgroundColor: cssVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+});
interface RedirectUrisValues {
redirectUris: string[];
@@ -124,7 +120,7 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
onBlur={onBlur}
onChange={(e) => onChange(e.target.value)}
/>
- {error && <div className={styles.fieldError}>{error}</div>}
+ {error && <div {...stylex.props(styles.fieldError)}>{error}</div>}
</Flexbox>
)}
validate={(value?: string) => {
@@ -146,7 +142,7 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
bare
name={'redirectUris'}
render={({ error }) =>
- error ? <div className={styles.listError}>{error}</div> : null
+ error ? <div {...stylex.props(styles.listError)}>{error}</div> : null
}
validate={(values?: (string | undefined)[]) => {
const messageKey = redirectUriListMessageKey(values);
@@ -184,7 +180,7 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
) : saved.length > 0 ? (
<Flexbox gap={6}>
{saved.map((uri) => (
- <div className={styles.uri} key={uri}>
+ <div {...stylex.props(styles.uri)} key={uri}>
{uri}
</div>
))}
@@ -193,7 +189,7 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
<Flexbox
horizontal
align={'center'}
- className={styles.empty}
+ className={stylex.props(styles.empty).className}
gap={16}
justify={'space-between'}
>
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx
index bb5e254667e..1e494bd308c 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx
@@ -1,16 +1,21 @@
'use client';
-import { createStaticStyles, Flexbox, Text } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type FC, type PropsWithChildren, type ReactNode } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
-}));
+const styles = stylex.create({
+ card: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
interface SectionCardProps {
extra?: ReactNode;
@@ -18,7 +23,7 @@ interface SectionCardProps {
}
const SectionCard: FC<PropsWithChildren<SectionCardProps>> = ({ children, extra, title }) => (
- <Flexbox className={styles.card} gap={16}>
+ <Flexbox className={stylex.props(styles.card).className} gap={16}>
<Flexbox horizontal align={'center'} justify={'space-between'} style={{ minHeight: 28 }}>
<Text weight={500}>{title}</Text>
{extra}
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx b/src/features/Settings/oauth-apps/features/AppDetail/index.tsx
index 8086e42cc23..ed9bbb63517 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/index.tsx
@@ -5,7 +5,6 @@ import {
Alert,
Button,
confirmModal,
- createStaticStyles,
Flexbox,
Skeleton,
Tabs,
@@ -13,6 +12,8 @@ import {
Text,
toast,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import { ArrowLeftIcon, PowerIcon, PowerOffIcon, Trash2Icon } from 'lucide-react';
import { type FC, useEffect, useState } from 'react';
@@ -34,52 +35,52 @@ import ManualSetupCard from './ManualSetupCard';
import RedirectUrisCard from './RedirectUrisCard';
import SectionCard from './SectionCard';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
- dangerCard: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorErrorBorder};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
- dangerDesc: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
- dangerRow: css`
- display: flex;
- gap: 16px;
- align-items: center;
- justify-content: space-between;
- `,
+const styles = stylex.create({
+ card: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ dangerCard: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorErrorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ dangerDesc: { fontSize: '12px', color: cssVar.colorTextSecondary },
+ dangerRow: {
+ display: 'flex',
+ gap: '16px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ },
// The stats slot is a business stub that renders nothing in the open-source
// build; an empty bordered card must not be left behind.
- statsCard: css`
- padding: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
-
- &:empty {
- display: none;
- }
- `,
- meta: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+ statsCard: {
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ display: { 'default': null, ':empty': 'none' },
+ },
+ meta: { fontSize: '12px', color: cssVar.colorTextTertiary },
+});
/** The app page while it loads; also shown while the Labs flag resolves on a direct visit. */
export const AppDetailSkeleton = () => (
<Flexbox gap={16}>
<Skeleton.Text rows={1} width={200} />
- <div className={styles.card}>
+ <div {...stylex.props(styles.card)}>
<Skeleton.Text rows={4} />
</div>
</Flexbox>
@@ -242,7 +243,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack }) => {
clientId={detail.id}
name={detail.name}
/>
- <div className={styles.statsCard}>
+ <div {...stylex.props(styles.statsCard)}>
<OAuthAppStats clientId={detail.id} />
</div>
</>
@@ -275,10 +276,10 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack }) => {
const advancedTab = (
<>
<SectionCard title={t('oauthApp.detail.status')}>
- <div className={styles.dangerRow}>
+ <div {...stylex.props(styles.dangerRow)}>
<Flexbox gap={2}>
<Text>{t(isDisabled ? 'oauthApp.actions.enable' : 'oauthApp.actions.disable')}</Text>
- <span className={styles.dangerDesc}>
+ <span {...stylex.props(styles.dangerDesc)}>
{t(isDisabled ? 'oauthApp.detail.enableDesc' : 'oauthApp.detail.disableDesc')}
</span>
</Flexbox>
@@ -294,12 +295,12 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack }) => {
</div>
</SectionCard>
- <Flexbox className={styles.dangerCard} gap={16}>
+ <Flexbox className={stylex.props(styles.dangerCard).className} gap={16}>
<Text weight={500}>{t('oauthApp.detail.dangerZone')}</Text>
- <div className={styles.dangerRow}>
+ <div {...stylex.props(styles.dangerRow)}>
<Flexbox gap={2}>
<Text>{t('oauthApp.detail.delete')}</Text>
- <span className={styles.dangerDesc}>{t('oauthApp.detail.deleteDesc')}</span>
+ <span {...stylex.props(styles.dangerDesc)}>{t('oauthApp.detail.deleteDesc')}</span>
</Flexbox>
<Button
danger
@@ -334,7 +335,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack }) => {
</Text>
{isDisabled && <Tag>{t('oauthApp.item.disabledTag')}</Tag>}
</Flexbox>
- <span className={styles.meta} style={{ paddingInlineStart: 36 }}>
+ <span className={stylex.props(styles.meta).className} style={{ paddingInlineStart: 36 }}>
{meta}
</span>
</Flexbox>
diff --git a/src/features/Settings/oauth-apps/features/AppItem/index.tsx b/src/features/Settings/oauth-apps/features/AppItem/index.tsx
index d8e3e8176f3..3a2898881cb 100644
--- a/src/features/Settings/oauth-apps/features/AppItem/index.tsx
+++ b/src/features/Settings/oauth-apps/features/AppItem/index.tsx
@@ -1,15 +1,8 @@
'use client';
-import {
- ActionIcon,
- confirmModal,
- createStaticStyles,
- DropdownMenu,
- Flexbox,
- Icon,
- Tag,
- Text,
-} from '@lobehub/ui';
+import { ActionIcon, confirmModal, DropdownMenu, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import { MoreVerticalIcon, PowerIcon, PowerOffIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
@@ -22,31 +15,22 @@ import { appTypeLabelKey } from '../../appList';
import AppLogo from '../AppLogo';
import { confirmDisableOAuthApp } from '../confirmDisable';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- meta: css`
- flex: none;
- font-size: ${cssVar.fontSizeSM};
- color: ${cssVar.colorTextTertiary};
- `,
- row: css`
- cursor: pointer;
-
- padding-block: 12px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
-
- transition: background 0.15s ease;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
-
- &:focus-visible {
- outline: 2px solid ${cssVar.colorPrimary};
- outline-offset: -1px;
- }
- `,
-}));
+const styles = stylex.create({
+ meta: { flex: 'none', fontSize: cssVar.fontSizeSM, color: cssVar.colorTextTertiary },
+ row: {
+ cursor: 'pointer',
+ paddingBlock: '12px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.15s ease',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ outlineWidth: { 'default': null, ':focus-visible': '2px' },
+ outlineStyle: { 'default': null, ':focus-visible': 'solid' },
+ outlineColor: { 'default': null, ':focus-visible': cssVar.colorPrimary },
+ outlineOffset: { 'default': null, ':focus-visible': '-1px' },
+ },
+});
interface AppItemProps {
app: OAuthAppItem;
@@ -79,7 +63,7 @@ const AppItem = memo<AppItemProps>(({ app, canEdit, onOpen }) => {
<Flexbox
horizontal
align={'center'}
- className={styles.row}
+ className={stylex.props(styles.row).className}
gap={12}
role={'button'}
tabIndex={0}
@@ -108,7 +92,7 @@ const AppItem = memo<AppItemProps>(({ app, canEdit, onOpen }) => {
)}
</Flexbox>
- <span className={styles.meta}>
+ <span {...stylex.props(styles.meta)}>
{t(appTypeLabelKey(app.applicationType))} · {lastUsed}
</span>
diff --git a/src/features/Settings/oauth-apps/features/AppListSkeleton.tsx b/src/features/Settings/oauth-apps/features/AppListSkeleton.tsx
index a1fd1290c7e..19f96ff24e1 100644
--- a/src/features/Settings/oauth-apps/features/AppListSkeleton.tsx
+++ b/src/features/Settings/oauth-apps/features/AppListSkeleton.tsx
@@ -1,23 +1,25 @@
'use client';
-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { SkeletonBar } from '@/components/Skeleton';
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = stylex.create({
// Same card chrome as the loaded list column in `OAuthApps`.
- listCol: css`
- overflow: hidden;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
+ listCol: {
+ overflow: 'hidden',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
// Same padding and gap as `AppItem`'s row.
- row: css`
- padding-block: 12px;
- padding-inline: 12px;
- `,
-}));
+ row: { paddingBlock: '12px', paddingInline: '12px' },
+});
/** Centres a text-height skeleton bar inside the line box of the text it replaces. */
const Line = ({
@@ -46,7 +48,13 @@ interface AppRowsSkeletonProps {
export const AppRowsSkeleton = ({ rows = 2 }: AppRowsSkeletonProps) => (
<>
{Array.from({ length: rows }).map((_, index) => (
- <Flexbox horizontal align={'center'} className={styles.row} gap={12} key={index}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.row).className}
+ gap={12}
+ key={index}
+ >
<SkeletonBar height={36} radius={cssVar.borderRadius} width={36} />
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
<Line height={14} lineHeight={22} width={index % 2 ? 112 : 144} />
@@ -60,7 +68,7 @@ export const AppRowsSkeleton = ({ rows = 2 }: AppRowsSkeletonProps) => (
/** The OAuth app list card (same chrome as the loaded list) filled with row skeletons. */
const AppListSkeleton = ({ rows }: AppRowsSkeletonProps) => (
- <Flexbox aria-busy className={styles.listCol} gap={2} padding={4}>
+ <Flexbox aria-busy className={stylex.props(styles.listCol).className} gap={2} padding={4}>
<AppRowsSkeleton rows={rows} />
</Flexbox>
);
diff --git a/src/features/Settings/oauth-apps/features/AppLogo/index.tsx b/src/features/Settings/oauth-apps/features/AppLogo/index.tsx
index cbcbab292e1..18216a25e0e 100644
--- a/src/features/Settings/oauth-apps/features/AppLogo/index.tsx
+++ b/src/features/Settings/oauth-apps/features/AppLogo/index.tsx
@@ -1,26 +1,23 @@
'use client';
-import { Avatar, createStaticStyles, cx, Icon } from '@lobehub/ui';
+import { Avatar, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AppWindowIcon } from 'lucide-react';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = stylex.create({
// An upload target reads as an empty slot: outline only, no fill.
- dashed: css`
- border: 1px dashed ${cssVar.colorBorder};
- `,
- filled: css`
- background: ${cssVar.colorFillTertiary};
- `,
- placeholder: css`
- display: flex;
- flex: none;
- align-items: center;
- justify-content: center;
-
- color: ${cssVar.colorTextTertiary};
- `,
-}));
+ dashed: { borderWidth: '1px', borderStyle: 'dashed', borderColor: cssVar.colorBorder },
+ filled: { backgroundColor: cssVar.colorFillTertiary, backgroundImage: 'none' },
+ placeholder: {
+ display: 'flex',
+ flex: 'none',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: cssVar.colorTextTertiary,
+ },
+});
interface AppLogoPlaceholderProps {
/** Dashed outline, for slots where the placeholder is also an upload target. */
@@ -35,7 +32,7 @@ interface AppLogoPlaceholderProps {
*/
export const AppLogoPlaceholder = memo<AppLogoPlaceholderProps>(({ dashed, size }) => (
<span
- className={cx(styles.placeholder, dashed ? styles.dashed : styles.filled)}
+ className={stylex.props(styles.placeholder, dashed ? styles.dashed : styles.filled).className}
style={{ borderRadius: Math.max(size / 6, 2), height: size, width: size }}
>
<Icon icon={AppWindowIcon} size={Math.round(size * 0.45)} />
diff --git a/src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx b/src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx
index 99849df4653..4db0c3a13d9 100644
--- a/src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx
+++ b/src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx
@@ -1,20 +1,21 @@
'use client';
-import { ActionIcon, createStaticStyles, Flexbox, toast } from '@lobehub/ui';
+import { ActionIcon, Flexbox, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Copy } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- id: css`
- overflow: hidden;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 13px;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
+const styles = stylex.create({
+ id: {
+ overflow: 'hidden',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '13px',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
interface ClientIdDisplayProps {
clientId: string;
@@ -34,7 +35,7 @@ const ClientIdDisplay: FC<ClientIdDisplayProps> = ({ clientId }) => {
return (
<Flexbox horizontal align={'center'} gap={4}>
- <span className={styles.id}>{clientId}</span>
+ <span {...stylex.props(styles.id)}>{clientId}</span>
<ActionIcon
icon={Copy}
size="small"
diff --git a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
index 40fa22f6020..9631505fb99 100644
--- a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
+++ b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
@@ -1,18 +1,10 @@
'use client';
import { type OAuthAppType } from '@lobechat/types';
-import {
- Button,
- createStaticStyles,
- cx,
- Flexbox,
- Icon,
- Input,
- Text,
- TextArea,
- useModalContext,
-} from '@lobehub/ui';
+import { Button, Flexbox, Icon, Input, Text, TextArea, useModalContext } from '@lobehub/ui';
import { Form, useForm, useWatch } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CheckIcon, GlobeIcon, type LucideIcon, TerminalIcon } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -25,66 +17,41 @@ import { AppLogoPlaceholder } from '../AppLogo';
const LOGO_SIZE = 64;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- typeCard: css`
- cursor: pointer;
-
- position: relative;
-
- flex: 1;
-
- min-width: 0;
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
-
- transition:
- border-color 0.15s ease,
- background 0.15s ease;
-
- &:hover {
- border-color: ${cssVar.colorBorder};
- }
-
- &:focus-visible {
- outline: 2px solid ${cssVar.colorBorder};
- outline-offset: 2px;
- }
- `,
+const styles = stylex.create({
+ typeCard: {
+ cursor: 'pointer',
+ position: 'relative',
+ flex: '1',
+ minWidth: '0',
+ padding: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },
+ borderRadius: cssVar.borderRadiusLG,
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ outlineWidth: { 'default': null, ':focus-visible': '2px' },
+ outlineStyle: { 'default': null, ':focus-visible': 'solid' },
+ outlineColor: { 'default': null, ':focus-visible': cssVar.colorBorder },
+ outlineOffset: { 'default': null, ':focus-visible': '2px' },
+ },
// LobeHub's primary is a near-black neutral, so the selection rides a
// text-colored border alone — no fill, which read as a disabled block.
- typeCardSelected: css`
- border-color: ${cssVar.colorText};
-
- &:hover {
- border-color: ${cssVar.colorText};
- }
- `,
- typeCheck: css`
- flex: none;
- margin-inline-start: auto;
- color: ${cssVar.colorText};
- `,
- typeDesc: css`
- font-size: 12px;
- line-height: 1.5;
- color: ${cssVar.colorTextTertiary};
- `,
- typeIcon: css`
- display: inline-flex;
- flex: none;
- align-items: center;
- justify-content: center;
-
- width: 28px;
- height: 28px;
- border-radius: ${cssVar.borderRadius};
-
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
-}));
+ typeCardSelected: { borderColor: cssVar.colorText },
+ typeCheck: { flex: 'none', marginInlineStart: 'auto', color: cssVar.colorText },
+ typeDesc: { fontSize: '12px', lineHeight: 1.5, color: cssVar.colorTextTertiary },
+ typeIcon: {
+ display: 'inline-flex',
+ flex: 'none',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '28px',
+ height: '28px',
+ borderRadius: cssVar.borderRadius,
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+});
interface TypeOption {
description: string;
@@ -107,7 +74,7 @@ const TypeSelect: FC<TypeSelectProps> = ({ onChange, options, value }) => (
return (
<Flexbox
aria-checked={selected}
- className={cx(styles.typeCard, selected && styles.typeCardSelected)}
+ className={stylex.props(styles.typeCard, selected && styles.typeCardSelected).className}
gap={8}
key={option.value}
role={'radio'}
@@ -121,13 +88,19 @@ const TypeSelect: FC<TypeSelectProps> = ({ onChange, options, value }) => (
}}
>
<Flexbox horizontal align={'center'} gap={8}>
- <span className={styles.typeIcon}>
+ <span {...stylex.props(styles.typeIcon)}>
<Icon icon={option.icon} size={16} />
</span>
<Text weight={500}>{option.title}</Text>
- {selected && <Icon className={styles.typeCheck} icon={CheckIcon} size={16} />}
+ {selected && (
+ <Icon
+ className={stylex.props(styles.typeCheck).className}
+ icon={CheckIcon}
+ size={16}
+ />
+ )}
</Flexbox>
- <span className={styles.typeDesc}>{option.description}</span>
+ <span {...stylex.props(styles.typeDesc)}>{option.description}</span>
</Flexbox>
);
})}
diff --git a/src/features/Settings/oauth-apps/features/OAuthApps.tsx b/src/features/Settings/oauth-apps/features/OAuthApps.tsx
index a68935c7760..50db5e6a624 100644
--- a/src/features/Settings/oauth-apps/features/OAuthApps.tsx
+++ b/src/features/Settings/oauth-apps/features/OAuthApps.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, Empty, Flexbox } from '@lobehub/ui';
+import { Empty, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AppWindowIcon } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,14 +18,17 @@ import { AppRowsSkeleton } from './AppListSkeleton';
import CreateAppButton from './CreateAppButton';
import { useOAuthAppList } from './useOAuthAppList';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- listCol: css`
- overflow: hidden;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
-}));
+const styles = stylex.create({
+ listCol: {
+ overflow: 'hidden',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
interface OAuthAppsProps {
canEdit: boolean;
@@ -85,7 +90,7 @@ const OAuthApps: FC<OAuthAppsProps> = ({ canEdit }) => {
};
return (
- <Flexbox className={styles.listCol} gap={2} padding={4}>
+ <Flexbox className={stylex.props(styles.listCol).className} gap={2} padding={4}>
{renderRows()}
</Flexbox>
);
diff --git a/src/features/Settings/oauth-apps/features/SecretModal/index.tsx b/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
index 5bfd6fb87e2..6651f60b207 100644
--- a/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
+++ b/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
@@ -4,38 +4,38 @@ import {
Button,
CopyButton,
createModal,
- createStaticStyles,
Flexbox,
type ModalInstance,
useModalContext,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { t } from 'i18next';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- hint: css`
- font-size: 12px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
- inlineCode: css`
- padding-inline: 4px;
- border-radius: 4px;
- font-family: ${cssVar.fontFamilyCode};
- background: ${cssVar.colorFillTertiary};
- `,
- secret: css`
- padding-block: 4px;
- padding-inline: 12px 4px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadius};
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 13px;
- overflow-wrap: anywhere;
- `,
-}));
+const styles = stylex.create({
+ hint: { fontSize: '12px', lineHeight: 1.6, color: cssVar.colorTextSecondary },
+ inlineCode: {
+ paddingInline: '4px',
+ borderRadius: '4px',
+ fontFamily: cssVar.fontFamilyCode,
+ backgroundColor: cssVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ secret: {
+ paddingBlock: '4px',
+ paddingInlineStart: '12px',
+ paddingInlineEnd: '4px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '13px',
+ overflowWrap: 'anywhere',
+ },
+});
/** Renders the copy's backtick-quoted parameter names as inline code. */
const withInlineCode = (text: string, className: string) =>
@@ -59,13 +59,21 @@ const SecretContent: FC<SecretContentProps> = ({ clientSecret }) => {
return (
<Flexbox gap={12}>
- <Flexbox horizontal align={'center'} className={styles.secret} gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.secret).className}
+ gap={8}
+ >
<Flexbox flex={1}>{clientSecret}</Flexbox>
<CopyButton content={clientSecret} title={t('oauthApp.secret.copy')} />
</Flexbox>
- <span className={styles.hint}>
+ <span {...stylex.props(styles.hint)}>
{t('oauthApp.secret.onceWarning')}{' '}
- {withInlineCode(t('oauthApp.secret.usage'), styles.inlineCode)}
+ {withInlineCode(
+ t('oauthApp.secret.usage'),
+ stylex.props(styles.inlineCode).className ?? '',
+ )}
</span>
<Flexbox horizontal justify={'flex-end'} style={{ marginTop: 4 }}>
<Button type={'primary'} onClick={close}>
diff --git a/src/features/Settings/profile/features/AvatarRow.tsx b/src/features/Settings/profile/features/AvatarRow.tsx
index eeaa9349859..e95a90b3eeb 100644
--- a/src/features/Settings/profile/features/AvatarRow.tsx
+++ b/src/features/Settings/profile/features/AvatarRow.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, cssVar, Icon, Upload } from '@lobehub/ui';
+import { cssVar, Icon, Upload } from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { Loader2Icon, PencilIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,41 +11,34 @@ import UserAvatar from '@/features/User/UserAvatar';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import { saveToast } from '@/store/utils/saveToast';
+import { sx } from '@/styles/sx';
import { imageToBase64 } from '@/utils/imageToBase64';
import { createUploadImageHandler } from '@/utils/uploadFIle';
import ProfileRow from './ProfileRow';
-const styles = createStaticStyles(({ css }) => ({
- overlay: css`
- cursor: pointer;
-
- position: absolute;
- z-index: 1;
- inset: 0;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- border-radius: 8px;
-
- opacity: 0;
- background: ${cssVar.colorBgMask};
-
- transition: opacity ${cssVar.motionDurationMid} ease;
- `,
- wrapper: css`
- cursor: pointer;
- position: relative;
- overflow: hidden;
- border-radius: 8px;
-
- &:hover .avatar-edit-overlay {
- opacity: 1;
- }
- `,
-}));
+const styles = stylex.create({
+ overlay: {
+ cursor: 'pointer',
+ position: 'absolute',
+ zIndex: 1,
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: '8px',
+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },
+ backgroundColor: sxVar.colorBgMask,
+ backgroundImage: 'none',
+ transition: `opacity ${sxVar.motionDurationMid} ease`,
+ },
+ wrapper: {
+ cursor: 'pointer',
+ position: 'relative',
+ overflow: 'hidden',
+ borderRadius: '8px',
+ },
+});
const AvatarRow = () => {
const { t } = useTranslation('auth');
@@ -84,12 +79,9 @@ const AvatarRow = () => {
const avatarContent = canUpload ? (
<Upload maxCount={1} onFiles={([file]) => handleUploadAvatar(file)}>
- <div className={styles.wrapper}>
+ <div {...stylex.props(styles.wrapper, stylex.defaultMarker())}>
<UserAvatar size={40} />
- <div
- className={`${styles.overlay} avatar-edit-overlay`}
- style={uploading ? { opacity: 1 } : undefined}
- >
+ <div {...sx(styles.overlay, uploading && { opacity: 1 })}>
<Icon
color={cssVar.colorTextLightSolid}
icon={uploading ? Loader2Icon : PencilIcon}
diff --git a/src/features/Settings/profile/features/ProfileRow.tsx b/src/features/Settings/profile/features/ProfileRow.tsx
index 51f1e2d236b..bc20c7c0b36 100644
--- a/src/features/Settings/profile/features/ProfileRow.tsx
+++ b/src/features/Settings/profile/features/ProfileRow.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, Text } from '@lobehub/ui';
+import { Text } from '@lobehub/ui';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type ReactNode } from 'react';
import { SETTINGS_ANCHOR_ROW_ATTR, SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
@@ -14,56 +16,45 @@ interface ProfileRowProps {
labelSlot?: ReactNode;
}
-const styles = createStaticStyles(({ css, responsive }) => ({
- action: css`
- flex-shrink: 0;
-
- /* Keep action trailing even for action-only rows (AvatarRow / PasswordRow) where body has no children and space-between degenerates to flex-start. */
- margin-inline-start: auto;
- `,
- body: css`
- display: flex;
- flex: 1;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- min-width: 0;
- `,
- label: css`
- flex: 0 0 160px;
-
- ${responsive.md} {
- flex: 0 0 auto;
- }
- `,
- row: css`
- display: flex;
- gap: 24px;
- align-items: center;
-
- min-height: 48px;
- padding-block: 16px;
-
- ${responsive.md} {
- flex-direction: column;
- gap: 12px;
- align-items: stretch;
- }
- `,
-}));
+const styles = stylex.create({
+ action: {
+ flexShrink: 0,
+ // Keep action trailing even for action-only rows (AvatarRow / PasswordRow) where body has no children and space-between degenerates to flex-start.
+ marginInlineStart: 'auto',
+ },
+ body: {
+ display: 'flex',
+ flex: '1',
+ gap: '12px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ minWidth: '0',
+ },
+ label: { flexGrow: 0, flexShrink: 0, flexBasis: { default: '160px', [media.md]: 'auto' } },
+ row: {
+ display: 'flex',
+ gap: { default: '24px', [media.md]: '12px' },
+ alignItems: { default: 'center', [media.md]: 'stretch' },
+ minHeight: '48px',
+ paddingBlock: '16px',
+ flexDirection: { default: null, [media.md]: 'column' },
+ },
+});
const ProfileRow = ({ anchor, label, labelSlot, children, action }: ProfileRowProps) => {
const labelNode = labelSlot ?? (label && <Text strong>{label}</Text>);
return (
- <div className={styles.row} {...(anchor ? { [SETTINGS_ANCHOR_ROW_ATTR]: '' } : undefined)}>
- <div className={styles.label}>
+ <div
+ {...stylex.props(styles.row)}
+ {...(anchor ? { [SETTINGS_ANCHOR_ROW_ATTR]: '' } : undefined)}
+ >
+ <div {...stylex.props(styles.label)}>
{anchor ? <SettingsSearchAnchor id={anchor}>{labelNode}</SettingsSearchAnchor> : labelNode}
</div>
- <div className={styles.body}>
+ <div {...stylex.props(styles.body)}>
{children}
- {action && <div className={styles.action}>{action}</div>}
+ {action && <div {...stylex.props(styles.action)}>{action}</div>}
</div>
</div>
);
diff --git a/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx b/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
index 69421852b96..bd22d30b79e 100644
--- a/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
+++ b/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
@@ -1,5 +1,6 @@
import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { Avatar, cssVar, cx, Divider, Flexbox, Skeleton, Tag, Text } from '@lobehub/ui';
+import { Avatar, cssVar, Divider, Flexbox, Skeleton, Tag, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,9 +34,11 @@ const ProviderCard = memo<ProviderCardProps>(
if (loading)
return (
<Flexbox
- className={cx(isDarkMode ? styles.containerDark : styles.containerLight)}
gap={24}
padding={16}
+ className={
+ stylex.props(isDarkMode ? styles.containerDark : styles.containerLight).className
+ }
>
<Skeleton />
</Flexbox>
@@ -46,7 +49,12 @@ const ProviderCard = memo<ProviderCardProps>(
}
return (
- <Flexbox className={cx(isDarkMode ? styles.containerDark : styles.containerLight)} gap={24}>
+ <Flexbox
+ gap={24}
+ className={
+ stylex.props(isDarkMode ? styles.containerDark : styles.containerLight).className
+ }
+ >
<Flexbox gap={12} padding={16} width={'100%'}>
<div
style={{ cursor: 'pointer' }}
@@ -95,7 +103,7 @@ const ProviderCard = memo<ProviderCardProps>(
)}
</Flexbox>
<Text
- className={styles.desc}
+ className={stylex.props(styles.desc).className}
ellipsis={{
rows: 2,
}}
diff --git a/src/features/Settings/provider/(list)/ProviderGrid/style.ts b/src/features/Settings/provider/(list)/ProviderGrid/style.ts
index 486ed05b2cb..ed57675c135 100644
--- a/src/features/Settings/provider/(list)/ProviderGrid/style.ts
+++ b/src/features/Settings/provider/(list)/ProviderGrid/style.ts
@@ -1,69 +1,36 @@
-import { createStaticStyles } from '@lobehub/ui';
-
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- bannerDark: css`
- opacity: 0.9;
- `,
- bannerLight: css`
- opacity: 0.4;
- `,
- containerDark: css`
- position: relative;
-
- overflow: hidden;
-
- height: 100%;
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- box-shadow: 0 0 1px 1px ${cssVar.colorFillQuaternary} inset;
-
- transition: box-shadow 0.2s ${cssVar.motionEaseInOut};
-
- &:hover {
- box-shadow: 0 0 1px 1px ${cssVar.colorFillSecondary} inset;
- }
- `,
- containerLight: css`
- position: relative;
-
- overflow: hidden;
-
- height: 100%;
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- box-shadow: 0 0 1px 1px ${cssVar.colorFillSecondary} inset;
-
- transition: box-shadow 0.2s ${cssVar.motionEaseInOut};
-
- &:hover {
- box-shadow: 0 0 1px 1px ${cssVar.colorFill} inset;
- }
- `,
- desc: css`
- min-height: 44px;
- margin-block-end: 0 !important;
- color: ${cssVar.colorTextDescription};
- `,
- tagBlue: css`
- color: ${cssVar.geekblue};
- background: ${cssVar.geekblue1};
- `,
- tagGreen: css`
- color: ${cssVar.green};
- background: ${cssVar.green1};
- `,
- time: css`
- color: ${cssVar.colorTextDescription};
- `,
- title: css`
- zoom: 1.2;
- margin-block-end: 0 !important;
- font-size: 18px !important;
- font-weight: bold;
- `,
- token: css`
- font-family: ${cssVar.fontFamilyCode};
- `,
-}));
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+export const styles = stylex.create({
+ containerDark: {
+ position: 'relative',
+ overflow: 'hidden',
+ height: '100%',
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ boxShadow: {
+ 'default': `0 0 1px 1px ${cssVar.colorFillQuaternary} inset`,
+ ':hover': `0 0 1px 1px ${cssVar.colorFillSecondary} inset`,
+ },
+ transition: `box-shadow 0.2s ${cssVar.motionEaseInOut}`,
+ },
+ containerLight: {
+ position: 'relative',
+ overflow: 'hidden',
+ height: '100%',
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ boxShadow: {
+ 'default': `0 0 1px 1px ${cssVar.colorFillSecondary} inset`,
+ ':hover': `0 0 1px 1px ${cssVar.colorFill} inset`,
+ },
+ transition: `box-shadow 0.2s ${cssVar.motionEaseInOut}`,
+ },
+ desc: {
+ minHeight: '44px',
+ marginBlockEnd: '0 !important',
+ color: cssVar.colorTextDescription,
+ },
+});
diff --git a/src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx b/src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx
index a478db8633e..0aeaed45f86 100644
--- a/src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx
+++ b/src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx
@@ -1,4 +1,6 @@
-import { Button, createStaticStyles, Flexbox, SortableList, toast } from '@lobehub/ui';
+import { Button, Flexbox, SortableList, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,18 +11,16 @@ import { type AiProviderListItem } from '@/types/aiProvider';
import GroupItem from './GroupItem';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- height: 36px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
- transition: background 0.2s ease-in-out;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = stylex.create({
+ container: {
+ height: '36px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.2s ease-in-out',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
interface ConfigGroupModalProps {
defaultItems: AiProviderListItem[];
@@ -50,7 +50,7 @@ const ConfigGroupModal = memo<ConfigGroupModalProps>(({ open, onCancel, defaultI
<SortableList.Item
horizontal
align={'center'}
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={4}
id={item.id}
justify={'space-between'}
diff --git a/src/features/Settings/provider/_layout/Desktop/index.tsx b/src/features/Settings/provider/_layout/Desktop/index.tsx
index 8180e9abc55..f56cb749ccb 100644
--- a/src/features/Settings/provider/_layout/Desktop/index.tsx
+++ b/src/features/Settings/provider/_layout/Desktop/index.tsx
@@ -1,4 +1,5 @@
import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { type PropsWithChildren } from 'react';
import ProviderMenu from '../../ProviderMenu';
@@ -12,7 +13,7 @@ const Layout = ({
onProviderSelect: (providerKey: string) => void;
}) => {
return (
- <Flexbox horizontal className={styles.mainContainer} width={'100%'}>
+ <Flexbox horizontal className={stylex.props(styles.mainContainer).className} width={'100%'}>
<ProviderMenu mobile={false} onProviderSelect={onProviderSelect} />
<Container>{children}</Container>
</Flexbox>
diff --git a/src/features/Settings/provider/_layout/Desktop/style.ts b/src/features/Settings/provider/_layout/Desktop/style.ts
index 556ce6e818e..80a623993cc 100644
--- a/src/features/Settings/provider/_layout/Desktop/style.ts
+++ b/src/features/Settings/provider/_layout/Desktop/style.ts
@@ -1,8 +1,7 @@
-import { createStaticStyles } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
-export const styles = createStaticStyles(({ css }) => ({
- // Main container
- mainContainer: css`
- max-height: 100%;
- `,
-}));
+export const styles = stylex.create({
+ mainContainer: {
+ maxHeight: '100%',
+ },
+});
diff --git a/src/features/Settings/provider/detail/github/index.tsx b/src/features/Settings/provider/detail/github/index.tsx
index e71be49fac0..226ca954c96 100644
--- a/src/features/Settings/provider/detail/github/index.tsx
+++ b/src/features/Settings/provider/detail/github/index.tsx
@@ -1,6 +1,10 @@
'use client';
-import { createStaticStyles, Markdown } from '@lobehub/ui';
+import {
+ // oxlint-disable-next-line stylex-migration/no-emotion-styles -- rendered Markdown paragraphs get no className
+ createStaticStyles,
+ Markdown,
+} from '@lobehub/ui';
import { GithubProviderCard } from 'model-bank/modelProviders';
import { useTranslation } from 'react-i18next';
@@ -13,16 +17,12 @@ import { KeyVaultsConfigKey, LLMProviderApiTokenKey } from '../../const';
import { type ProviderItem } from '../../type';
import ProviderDetail from '../default';
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const fallback = createStaticStyles(({ css, cssVar }) => ({
markdown: css`
p {
color: ${cssVar.colorTextDescription} !important;
}
`,
- tip: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
}));
const providerKey: GlobalLLMProviderKey = 'github';
@@ -45,7 +45,7 @@ const useProviderCard = (): ProviderItem => {
/>
),
desc: (
- <Markdown className={styles.markdown} fontSize={12} variant={'chat'}>
+ <Markdown className={fallback.markdown} fontSize={12} variant={'chat'}>
{t('github.personalAccessToken.desc')}
</Markdown>
),
diff --git a/src/features/Settings/provider/detail/ollama/Container.tsx b/src/features/Settings/provider/detail/ollama/Container.tsx
index 0da739382de..03c5e8a30c3 100644
--- a/src/features/Settings/provider/detail/ollama/Container.tsx
+++ b/src/features/Settings/provider/detail/ollama/Container.tsx
@@ -1,30 +1,25 @@
-import { ActionIcon, createStaticStyles, Flexbox, responsive } from '@lobehub/ui';
+import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
import { XIcon } from 'lucide-react';
import { type ReactNode } from 'react';
import { useState } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- close: css`
- position: absolute;
- inset-block-start: 16px;
- inset-inline-end: 16px;
- `,
- container: css`
- position: relative;
-
- width: 100%;
- padding-inline: 40px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
-
- background: ${cssVar.colorBgContainer};
-
- ${responsive.sm} {
- width: 100%;
- padding-inline: 12px;
- }
- `,
-}));
+const styles = stylex.create({
+ close: { position: 'absolute', insetBlockStart: '16px', insetInlineEnd: '16px' },
+ container: {
+ position: 'relative',
+ width: '100%',
+ paddingInline: { default: '40px', [media.sm]: '12px' },
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: '8px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+});
const Container = ({
setError,
@@ -37,9 +32,9 @@ const Container = ({
return (
show && (
- <Flexbox className={styles.container}>
+ <Flexbox className={stylex.props(styles.container).className}>
<ActionIcon
- className={styles.close}
+ className={stylex.props(styles.close).className}
icon={XIcon}
onClick={() => {
setShow(false);
diff --git a/src/features/Settings/provider/detail/vertexai/index.tsx b/src/features/Settings/provider/detail/vertexai/index.tsx
index 1d6b8750d21..4c237c63e32 100644
--- a/src/features/Settings/provider/detail/vertexai/index.tsx
+++ b/src/features/Settings/provider/detail/vertexai/index.tsx
@@ -1,6 +1,11 @@
'use client';
-import { createStaticStyles, Markdown, Select } from '@lobehub/ui';
+import {
+ // oxlint-disable-next-line stylex-migration/no-emotion-styles -- rendered Markdown paragraphs get no className
+ createStaticStyles,
+ Markdown,
+ Select,
+} from '@lobehub/ui';
import { VertexAIProviderCard } from 'model-bank/modelProviders';
import { useTranslation } from 'react-i18next';
@@ -13,16 +18,12 @@ import { KeyVaultsConfigKey, LLMProviderApiTokenKey } from '../../const';
import { type ProviderItem } from '../../type';
import ProviderDetail from '../default';
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const fallback = createStaticStyles(({ css, cssVar }) => ({
markdown: css`
p {
color: ${cssVar.colorTextDescription} !important;
}
`,
- tip: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
}));
const providerKey: GlobalLLMProviderKey = 'vertexai';
@@ -87,7 +88,7 @@ const useProviderCard = (): ProviderItem => {
/>
),
desc: (
- <Markdown className={styles.markdown} fontSize={12} variant={'chat'}>
+ <Markdown className={fallback.markdown} fontSize={12} variant={'chat'}>
{t('vertexai.apiKey.desc')}
</Markdown>
),
@@ -108,7 +109,7 @@ const useProviderCard = (): ProviderItem => {
/>
),
desc: (
- <Markdown className={styles.markdown} fontSize={12} variant={'chat'}>
+ <Markdown className={fallback.markdown} fontSize={12} variant={'chat'}>
{t('vertexai.region.desc')}
</Markdown>
),
diff --git a/src/features/Settings/provider/features/ModelList/EmptyModels.tsx b/src/features/Settings/provider/features/ModelList/EmptyModels.tsx
index 368abef697d..4bc1533c62c 100644
--- a/src/features/Settings/provider/features/ModelList/EmptyModels.tsx
+++ b/src/features/Settings/provider/features/ModelList/EmptyModels.tsx
@@ -1,4 +1,6 @@
-import { Button, Center, createStaticStyles, Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';
+import { Button, Center, Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { BrainIcon, LucideRefreshCcwDot, PlusIcon } from 'lucide-react';
import { memo, use, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,41 +11,33 @@ import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { createCreateNewModelModal } from './CreateNewModelModal';
import { ProviderSettingsContext } from './ProviderSettingsContext';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- circle: css`
- width: 80px;
- height: 80px;
- border-radius: 50%;
- background: ${cssVar.colorFillSecondary};
- `,
- container: css`
- width: 100%;
- border: 1px dashed ${cssVar.colorBorder};
- border-radius: 12px;
- background: ${cssVar.colorBgContainer};
- `,
- description: css`
- max-width: 280px;
-
- font-size: ${cssVar.fontSize};
- color: ${cssVar.colorTextDescription};
- text-align: center;
- text-wrap: balance;
- `,
- iconWrapper: css`
- position: relative;
- width: 64px;
- height: 64px;
- `,
- sparklesIcon: css`
- font-size: 40px;
- color: ${cssVar.colorText};
- `,
- title: css`
- font-size: ${cssVar.fontSizeLG};
- font-weight: 500;
- `,
-}));
+const styles = stylex.create({
+ circle: {
+ width: '80px',
+ height: '80px',
+ borderRadius: '50%',
+ backgroundColor: cssVar.colorFillSecondary,
+ backgroundImage: 'none',
+ },
+ container: {
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorder,
+ borderRadius: '12px',
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ description: {
+ maxWidth: '280px',
+ fontSize: cssVar.fontSize,
+ color: cssVar.colorTextDescription,
+ textAlign: 'center',
+ textWrap: 'balance',
+ },
+ sparklesIcon: { fontSize: '40px', color: cssVar.colorText },
+ title: { fontSize: cssVar.fontSizeLG, fontWeight: 500 },
+});
const EmptyState = memo<{ provider: string }>(({ provider }) => {
const { t } = useTranslation('modelProvider');
@@ -56,13 +50,13 @@ const EmptyState = memo<{ provider: string }>(({ provider }) => {
const { showDeployName } = use(ProviderSettingsContext);
return (
- <Center className={styles.container} gap={24} paddingBlock={40}>
- <Center className={styles.circle}>
- <Icon className={styles.sparklesIcon} icon={BrainIcon} />
+ <Center className={stylex.props(styles.container).className} gap={24} paddingBlock={40}>
+ <Center className={stylex.props(styles.circle).className}>
+ <Icon className={stylex.props(styles.sparklesIcon).className} icon={BrainIcon} />
</Center>
<Flexbox align={'center'} gap={8}>
- <div className={styles.title}>{t('providerModels.list.empty.title')}</div>
- <div className={styles.description}>{t('providerModels.list.empty.desc')}</div>
+ <div {...stylex.props(styles.title)}>{t('providerModels.list.empty.title')}</div>
+ <div {...stylex.props(styles.description)}>{t('providerModels.list.empty.desc')}</div>
</Flexbox>
<Flexbox horizontal gap={8}>
diff --git a/src/features/Settings/provider/features/ModelList/ModelItem.tsx b/src/features/Settings/provider/features/ModelList/ModelItem.tsx
index d716c76f84a..ba57c7e3343 100644
--- a/src/features/Settings/provider/features/ModelList/ModelItem.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelItem.tsx
@@ -2,7 +2,6 @@ import {
ActionIcon,
confirmModal,
copyToClipboard,
- createStaticStyles,
cssVar,
Flexbox,
Switch,
@@ -10,6 +9,8 @@ import {
Text,
toast,
} from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { LucidePencil, TrashIcon } from 'lucide-react';
import { type AiProviderModelListItem } from 'model-bank';
import { AiModelSourceEnum } from 'model-bank/aiModel';
@@ -28,39 +29,17 @@ import { createModelConfigModal } from './ModelConfigModal';
import { formatModelPricingLabels } from './pricingLabels';
import { ProviderSettingsContext } from './ProviderSettingsContext';
-const styles = createStaticStyles(({ css, cx }) => {
- return {
- config: cx(
- 'model-item-config',
- css`
- opacity: 0;
- transition: all 100ms ease-in-out;
- `,
- ),
- container: css`
- position: relative;
- border-radius: ${cssVar.borderRadiusLG}px;
- transition: all 200ms ease-in-out;
-
- &:hover {
- background-color: ${cssVar.colorFillTertiary};
-
- .model-item-config {
- opacity: 1;
- }
- }
- `,
- desc: css`
- flex: 1;
- min-width: 0;
-
- span {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- `,
- };
+const styles = stylex.create({
+ config: {
+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },
+ transition: 'all 100ms ease-in-out',
+ },
+ container: {
+ position: 'relative',
+ borderRadius: `${sxVar.borderRadiusLG}px`,
+ transition: 'all 200ms ease-in-out',
+ backgroundColor: { 'default': null, ':hover': sxVar.colorFillTertiary },
+ },
});
interface ModelItemProps extends AiProviderModelListItem {
@@ -138,7 +117,7 @@ const ModelItem = memo<ModelItemProps>(
const Actions =
modelEditable &&
((style?: React.CSSProperties) => (
- <Flexbox horizontal className={styles.config} style={style}>
+ <Flexbox horizontal className={stylex.props(styles.config).className} style={style}>
<ActionIcon
disabled={!canManageProvider}
icon={LucidePencil}
@@ -217,7 +196,7 @@ const ModelItem = memo<ModelItemProps>(
<Flexbox
horizontal
align={'center'}
- className={styles.container}
+ className={stylex.props(styles.container, stylex.defaultMarker()).className}
gap={24}
justify={'space-between'}
padding={12}
diff --git a/src/features/Settings/provider/features/ModelList/SkeletonList.tsx b/src/features/Settings/provider/features/ModelList/SkeletonList.tsx
index 47fe6e72cc8..02ae4dbe761 100644
--- a/src/features/Settings/provider/features/ModelList/SkeletonList.tsx
+++ b/src/features/Settings/provider/features/ModelList/SkeletonList.tsx
@@ -1,47 +1,30 @@
'use client';
-import { createStaticStyles, Flexbox, Skeleton } from '@lobehub/ui';
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- display: flex;
- gap: 24px;
- align-items: center;
- justify-content: space-between;
-
- padding: 12px;
- border-radius: ${cssVar.borderRadiusLG};
- `,
- leftContent: css`
- display: flex;
- flex: 1;
- gap: 8px;
- align-items: center;
-
- min-width: 0;
- `,
- rightContent: css`
- display: flex;
- gap: 4px;
- align-items: center;
- `,
- textContent: css`
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 4px;
-
- min-width: 0;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ gap: '24px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '12px',
+ borderRadius: cssVar.borderRadiusLG,
+ },
+ leftContent: { display: 'flex', flex: '1', gap: '8px', alignItems: 'center', minWidth: '0' },
+ rightContent: { display: 'flex', gap: '4px', alignItems: 'center' },
+ textContent: { display: 'flex', flex: '1', flexDirection: 'column', gap: '4px', minWidth: '0' },
+});
export const Placeholder = memo(() => {
return (
- <Flexbox horizontal className={styles.container}>
- <Flexbox horizontal className={styles.leftContent}>
+ <Flexbox horizontal className={stylex.props(styles.container).className}>
+ <Flexbox horizontal className={stylex.props(styles.leftContent).className}>
<Skeleton.Avatar shape="square" size={32} style={{ flex: 'none' }} />
- <Flexbox className={styles.textContent}>
+ <Flexbox className={stylex.props(styles.textContent).className}>
<Skeleton height={18} width={160} />
<Flexbox horizontal gap={4}>
<Skeleton height={16} width={60} />
@@ -49,7 +32,7 @@ export const Placeholder = memo(() => {
</Flexbox>
</Flexbox>
</Flexbox>
- <Flexbox horizontal className={styles.rightContent}>
+ <Flexbox horizontal className={stylex.props(styles.rightContent).className}>
<Skeleton
style={{
borderRadius: 12,
diff --git a/src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx b/src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx
index 3985c19fb30..bcde0fad354 100644
--- a/src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx
+++ b/src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx
@@ -1,4 +1,6 @@
-import { Button, createStaticStyles, Flexbox, SortableList, toast } from '@lobehub/ui';
+import { Button, Flexbox, SortableList, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { type AiProviderModelListItem } from 'model-bank';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,18 +11,16 @@ import { useAiInfraStore } from '@/store/aiInfra';
import ListItem from './ListItem';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- height: 36px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
- transition: background 0.2s ease-in-out;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = stylex.create({
+ container: {
+ height: '36px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.2s ease-in-out',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
interface SortModelModalProps {
defaultItems: AiProviderModelListItem[];
@@ -53,7 +53,7 @@ const SortModelModal = memo<SortModelModalProps>(({ open, onCancel, defaultItems
<SortableList.Item
horizontal
align={'center'}
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={4}
id={item.id}
justify={'space-between'}
diff --git a/src/features/Settings/provider/features/ProviderConfig/Checker.tsx b/src/features/Settings/provider/features/ProviderConfig/Checker.tsx
index 2f4a5e51f41..ca599028998 100644
--- a/src/features/Settings/provider/features/ProviderConfig/Checker.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/Checker.tsx
@@ -3,17 +3,9 @@
import { type ChatMessageError } from '@lobechat/types';
import { RequestTrigger, TraceNameMap } from '@lobechat/types';
import { isRecord, pickTrimmedString } from '@lobechat/utils/object';
-import {
- Alert,
- Button,
- createStaticStyles,
- cssVar,
- cx,
- Flexbox,
- Highlighter,
- Select,
- Spin,
-} from '@lobehub/ui';
+import { Alert, Button, Flexbox, Highlighter, Select, Spin } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleCheckIcon } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo, useEffect, useMemo, useState } from 'react';
@@ -26,11 +18,7 @@ import { chatService } from '@/services/chat';
import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { getRuntimeErrorMessage } from '@/utils/locale/runtimeErrorMessage';
-const styles = createStaticStyles(({ css }) => ({
- popup: css`
- width: 380px;
- `,
-}));
+const styles = stylex.create({ popup: { width: '380px' } });
const Error = memo<{ error: ChatMessageError }>(({ error }) => {
const { t } = useTranslation(['error', 'modelRuntime']);
const providerName = useProviderName(error.body?.provider);
@@ -199,7 +187,7 @@ const Checker = memo<ConnectionCheckerProps>(
disabled={!canManageProvider}
listItemHeight={36}
options={sortedModels.map((id) => ({ label: id, value: id }))}
- popupClassName={cx(styles.popup)}
+ popupClassName={stylex.props(styles.popup).className}
suffixIcon={isProviderConfigUpdating && <Spin size="small" />}
value={checkModel}
optionRender={({ value }) => {
diff --git a/src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx b/src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx
index a20f3c718e7..dd0b4cdf0b5 100644
--- a/src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx
@@ -1,18 +1,19 @@
-import { createStaticStyles, Skeleton, Tooltip } from '@lobehub/ui';
+import { Skeleton, Tooltip } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { type FC } from 'react';
import InstantSwitch from '@/components/InstantSwitch';
import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
-const styles = createStaticStyles(({ css }) => ({
- switchLoading: css`
- width: 44px !important;
- min-width: 44px !important;
- height: 22px !important;
- border-radius: 12px !important;
- `,
-}));
+const styles = stylex.create({
+ switchLoading: {
+ width: '44px !important',
+ minWidth: '44px !important',
+ height: '22px !important',
+ borderRadius: '12px !important',
+ },
+});
interface SwitchProps {
Component?: FC<{ id: string }>;
@@ -27,7 +28,8 @@ const Switch = ({ id, Component }: SwitchProps) => {
]);
const { allowed: canManageProvider, reason } = usePermission('manage_provider_key');
- if (isLoading) return <Skeleton className={styles.switchLoading} height={36} />;
+ if (isLoading)
+ return <Skeleton className={stylex.props(styles.switchLoading).className} height={36} />;
// slot for cloud
if (Component) return <Component id={id} />;
diff --git a/src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx b/src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
index 58ec31dd3d5..44903333d96 100644
--- a/src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
@@ -6,7 +6,6 @@ import {
Button,
confirmModal,
CopyButton,
- createStaticStyles,
cssVar,
Flexbox,
Icon,
@@ -14,6 +13,8 @@ import {
Spin,
Text,
} from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { CircleCheckIcon, LogOutIcon, UnplugIcon } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo, useCallback, useState } from 'react';
@@ -21,94 +22,90 @@ import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { lambdaQuery } from '@/libs/trpc/client';
+import { sx } from '@/styles/sx';
import { useOAuthDeviceFlow } from './useOAuthDeviceFlow';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- overflow: hidden;
-
- /* matches the borderless form below so both boxes end on the same edge */
- width: 100%;
- max-width: ${MAX_WIDTH}px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
- `,
- codeBox: css`
- display: flex;
- flex: 1;
- align-items: center;
- justify-content: center;
-
- padding-block: 16px;
- padding-inline: 24px;
- border-radius: 12px;
-
- font-family: monospace;
- font-size: 28px;
- font-weight: 600;
- letter-spacing: 6px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- content: css`
- display: flex;
- flex-direction: column;
- gap: 16px;
- align-items: center;
-
- padding-block: 8px 4px;
- `,
- errorText: css`
- color: ${cssVar.colorError};
- `,
- header: css`
- display: flex;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- padding-block: 12px;
- padding-inline: 16px;
- `,
+// matches the borderless form below so both boxes end on the same edge
+const cardWidth = { maxWidth: MAX_WIDTH };
+
+const styles = stylex.create({
+ card: {
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: sxVar.colorBorderSecondary,
+ borderRadius: '12px',
+ },
+ codeBox: {
+ display: 'flex',
+ flex: '1',
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: '16px',
+ paddingInline: '24px',
+ borderRadius: '12px',
+ fontFamily: 'monospace',
+ fontSize: '28px',
+ fontWeight: 600,
+ letterSpacing: '6px',
+ backgroundColor: sxVar.colorFillTertiary,
+ backgroundImage: 'none',
+ },
+ content: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '16px',
+ alignItems: 'center',
+ paddingBlockStart: '8px',
+ paddingBlockEnd: '4px',
+ },
+ errorText: {
+ color: sxVar.colorError,
+ },
+ header: {
+ display: 'flex',
+ gap: '12px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingBlock: '12px',
+ paddingInline: '16px',
+ },
// Prose, so it reads from the left edge rather than being centred with the
// code box below it.
- hint: css`
- width: 100%;
-
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- text-align: start;
- `,
- pollingHint: css`
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: center;
-
- padding-block: 12px;
- padding-inline: 16px;
- border-radius: 8px;
-
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- successBadge: css`
- display: flex;
- gap: 6px;
- align-items: center;
-
- font-size: 13px;
- color: ${cssVar.colorSuccess};
- `,
- username: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+ hint: {
+ width: '100%',
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: sxVar.colorTextSecondary,
+ textAlign: 'start',
+ },
+ pollingHint: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: '12px',
+ paddingInline: '16px',
+ borderRadius: '8px',
+ fontSize: '13px',
+ color: sxVar.colorTextSecondary,
+ backgroundColor: sxVar.colorFillQuaternary,
+ backgroundImage: 'none',
+ },
+ successBadge: {
+ display: 'flex',
+ gap: '6px',
+ alignItems: 'center',
+ fontSize: '13px',
+ color: sxVar.colorSuccess,
+ },
+ username: {
+ fontSize: '13px',
+ color: sxVar.colorTextSecondary,
+ },
+});
export interface OAuthDeviceFlowAuthProps {
/**
@@ -205,7 +202,7 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
{username && (
<Flexbox horizontal align={'center'} gap={6}>
{avatarUrl && <Avatar avatar={avatarUrl} size={20} title={username} />}
- <span className={styles.username}>{username}</span>
+ <span {...stylex.props(styles.username)}>{username}</span>
</Flexbox>
)}
<Button
@@ -239,7 +236,7 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
// Loading state
if (state === 'requesting' || !deviceCodeInfo)
return (
- <div className={styles.content}>
+ <div {...stylex.props(styles.content)}>
<Spin size="middle" />
<Text as={'span'} type={'secondary'}>
{t('providerModels.config.oauth.connecting')}
@@ -251,10 +248,10 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
if (state === 'error' && error) {
const errorKey = `providerModels.config.oauth.${error}`;
return (
- <div className={styles.content}>
+ <div {...stylex.props(styles.content)}>
<Flexbox horizontal align="center" gap={8}>
<Icon color={cssVar.colorError} icon={UnplugIcon} size={20} />
- <Text as={'span'} className={styles.errorText}>
+ <Text as={'span'} className={stylex.props(styles.errorText).className}>
{t(errorKey as any)}
</Text>
</Flexbox>
@@ -274,8 +271,8 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
// Connect, so the link is the fallback for when a popup blocker ate it —
// and the only route when authorizing on a second device.
return (
- <div className={styles.content}>
- <div className={styles.hint}>
+ <div {...stylex.props(styles.content)}>
+ <div {...stylex.props(styles.hint)}>
{t('providerModels.config.oauth.enterCode')}{' '}
<a href={deviceCodeInfo.verificationUri} rel="noopener noreferrer" target="_blank">
{deviceCodeInfo.verificationUri}
@@ -283,11 +280,11 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
</div>
<Flexbox horizontal align="center" gap={12} style={{ width: '100%' }}>
- <div className={styles.codeBox}>{deviceCodeInfo.userCode}</div>
+ <div {...stylex.props(styles.codeBox)}>{deviceCodeInfo.userCode}</div>
<CopyButton content={deviceCodeInfo.userCode} />
</Flexbox>
- <div className={styles.pollingHint}>
+ <div {...stylex.props(styles.pollingHint)}>
<Spin size="small" />
<span>{t('providerModels.config.oauth.polling')}</span>
</div>
@@ -297,14 +294,14 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
return (
<>
- <div className={styles.card}>
- <div className={styles.header}>
+ <div {...sx(styles.card, cardWidth)}>
+ <div {...stylex.props(styles.header)}>
{/* The badge is a property of the provider, not an action on it, so
it sits with the name rather than among the controls. */}
<Flexbox horizontal align={'center'} gap={8}>
{title}
{enabled && isAuthenticated && (
- <div className={styles.successBadge}>
+ <div {...stylex.props(styles.successBadge)}>
<Icon icon={CircleCheckIcon} />
<span>{t('providerModels.config.oauth.connected')}</span>
</div>
diff --git a/src/features/Settings/provider/features/ProviderConfig/index.tsx b/src/features/Settings/provider/features/ProviderConfig/index.tsx
index 386c34c06db..73df0a0a614 100644
--- a/src/features/Settings/provider/features/ProviderConfig/index.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/index.tsx
@@ -5,12 +5,9 @@ import { AES_GCM_URL, BASE_PROVIDER_DOC_URL, FORM_STYLE } from '@lobechat/const'
import {
Avatar,
Center,
- createStaticStyles,
cssVar,
- cx,
Flexbox,
Icon,
- responsive,
Skeleton,
Spin,
stopPropagation,
@@ -25,6 +22,9 @@ import {
useForm,
useWatch,
} from '@lobehub/ui/form';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
import { useDebounceFn } from 'ahooks';
import { get, set } from 'es-toolkit/compat';
import { InfoIcon, LockIcon } from 'lucide-react';
@@ -41,6 +41,7 @@ import { usePermission } from '@/hooks/usePermission';
import { lambdaQuery } from '@/libs/trpc/client';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { sx } from '@/styles/sx';
import {
type AiProviderDetailItem,
type AiProviderSourceType,
@@ -56,49 +57,28 @@ import EnableSwitch from './EnableSwitch';
import OAuthDeviceFlowAuth from './OAuthDeviceFlowAuth';
import UpdateProviderInfo from './UpdateProviderInfo';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- aceGcm: css`
- width: 100%;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
-
- opacity: 0.66;
-
- transition: opacity 0.2s ${cssVar.motionEaseInOut};
-
- &:hover {
- opacity: 1;
- }
- `,
- form: css`
- ${responsive.sm} {
- width: 100%;
- min-width: unset !important;
- }
- `,
- help: css`
- border-radius: 50%;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextDescription};
-
- background: ${cssVar.colorFillTertiary};
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFill};
- }
- `,
- switchLoading: css`
- width: 44px !important;
- min-width: 44px !important;
- height: 22px !important;
- border-radius: 12px !important;
- `,
-}));
+const styles = stylex.create({
+ aceGcm: {
+ width: '100%',
+ fontSize: '12px',
+ color: sxVar.colorTextSecondary,
+ textAlign: 'center',
+ opacity: { 'default': 0.66, ':hover': 1 },
+ transition: `opacity 0.2s ${sxVar.motionEaseInOut}`,
+ },
+ form: {
+ width: { default: null, [media.sm]: '100%' },
+ minWidth: { default: null, [media.sm]: 'unset !important' },
+ },
+ help: {
+ borderRadius: '50%',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: { 'default': sxVar.colorTextDescription, ':hover': sxVar.colorText },
+ backgroundColor: { 'default': sxVar.colorFillTertiary, ':hover': sxVar.colorFill },
+ backgroundImage: 'none',
+ },
+});
export interface ProviderConfigProps extends Omit<AiProviderDetailItem, 'enabled' | 'source'> {
apiKeyItems?: FormFieldProps[];
@@ -316,7 +296,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
const aceGcmItem: FormFieldProps = {
bare: true,
children: (
- <div className={styles.aceGcm}>
+ <div {...stylex.props(styles.aceGcm)}>
<Icon icon={LockIcon} style={{ marginRight: 4 }} />
<Trans
i18nKey="providerModels.config.aesGcm"
@@ -518,7 +498,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
target="_blank"
onClick={stopPropagation}
>
- <Center className={styles.help} height={20} width={20}>
+ <Center className={stylex.props(styles.help).className} height={20} width={20}>
?
</Center>
</a>
@@ -577,7 +557,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
)}
{shouldShowForm && (
<Form
- className={cx(styles.form, className)}
+ {...sx(styles.form, className)}
form={form}
items={[model]}
variant={'borderless'}
diff --git a/src/features/Settings/proxy/features/SaveBar.tsx b/src/features/Settings/proxy/features/SaveBar.tsx
index 6f9707f536c..51dcb17764e 100644
--- a/src/features/Settings/proxy/features/SaveBar.tsx
+++ b/src/features/Settings/proxy/features/SaveBar.tsx
@@ -1,76 +1,75 @@
'use client';
-import { Button, createStaticStyles } from '@lobehub/ui';
+import { Button } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { AnimatePresence } from 'motion/react';
import * as m from 'motion/react-m';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- pointer-events: none;
-
- position: fixed;
- z-index: 1000;
- inset-block-end: 24px;
- inset-inline-start: 50%;
- transform: translateX(-50%);
- `,
- pill: css`
- pointer-events: auto;
-
- display: inline-flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 6px;
- padding-inline: 16px 6px;
- border: 1px solid color-mix(in srgb, ${cssVar.colorBorderSecondary} 60%, transparent);
- border-radius: 999px;
-
- font-size: 13px;
- color: ${cssVar.colorText};
-
- background: color-mix(in srgb, ${cssVar.colorBgElevated} 85%, transparent);
- backdrop-filter: blur(16px) saturate(1.2);
- box-shadow: ${cssVar.boxShadowSecondary};
- `,
- dot: css`
- flex-shrink: 0;
-
- width: 6px;
- height: 6px;
- border-radius: 50%;
-
- background: ${cssVar.colorWarning};
- `,
- message: css`
- color: ${cssVar.colorTextSecondary};
- `,
- resetButton: css`
- height: 28px;
- padding-block: 0;
- padding-inline: 12px;
- border-radius: 999px;
-
- color: ${cssVar.colorTextSecondary} !important;
-
- background: transparent;
-
- &:hover {
- color: ${cssVar.colorText} !important;
- background: ${cssVar.colorFillSecondary} !important;
- }
- `,
- saveButton: css`
- height: 28px;
- padding-block: 0;
- padding-inline: 14px;
- border-radius: 999px;
-
- font-weight: 500;
- `,
-}));
+const styles = stylex.create({
+ container: {
+ pointerEvents: 'none',
+ position: 'fixed',
+ zIndex: 1000,
+ insetBlockEnd: '24px',
+ insetInlineStart: '50%',
+ transform: 'translateX(-50%)',
+ },
+ pill: {
+ pointerEvents: 'auto',
+ display: 'inline-flex',
+ gap: '8px',
+ alignItems: 'center',
+ paddingBlock: '6px',
+ paddingInlineStart: '16px',
+ paddingInlineEnd: '6px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: `color-mix(in srgb, ${cssVar.colorBorderSecondary} 60%, transparent)`,
+ borderRadius: '999px',
+ fontSize: '13px',
+ color: cssVar.colorText,
+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgElevated} 85%, transparent)`,
+ backgroundImage: 'none',
+ backdropFilter: 'blur(16px) saturate(1.2)',
+ boxShadow: cssVar.boxShadowSecondary,
+ },
+ dot: {
+ flexShrink: 0,
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: cssVar.colorWarning,
+ backgroundImage: 'none',
+ },
+ message: {
+ color: cssVar.colorTextSecondary,
+ },
+ resetButton: {
+ height: '28px',
+ paddingBlock: 0,
+ paddingInline: '12px',
+ borderRadius: '999px',
+ color: {
+ 'default': `${cssVar.colorTextSecondary} !important`,
+ ':hover': `${cssVar.colorText} !important`,
+ },
+ backgroundColor: {
+ 'default': 'transparent',
+ ':hover': `${cssVar.colorFillSecondary} !important`,
+ },
+ backgroundImage: 'none',
+ },
+ saveButton: {
+ height: '28px',
+ paddingBlock: 0,
+ paddingInline: '14px',
+ borderRadius: '999px',
+ fontWeight: 500,
+ },
+});
interface SaveBarProps {
isDirty: boolean;
@@ -88,17 +87,17 @@ const SaveBar = memo<SaveBarProps>(({ isDirty, isSaving, onReset, onSave }) => {
<m.div
animate={{ opacity: 1, y: 0 }}
aria-live="polite"
- className={styles.container}
+ className={stylex.props(styles.container).className}
exit={{ opacity: 0, y: 16 }}
initial={{ opacity: 0, y: 16 }}
role="status"
transition={{ duration: 0.18, ease: 'easeOut' }}
>
- <div className={styles.pill}>
- <span className={styles.dot} />
- <span className={styles.message}>{t('proxy.unsavedChanges')}</span>
+ <div {...stylex.props(styles.pill)}>
+ <span {...stylex.props(styles.dot)} />
+ <span {...stylex.props(styles.message)}>{t('proxy.unsavedChanges')}</span>
<Button
- className={styles.resetButton}
+ className={stylex.props(styles.resetButton).className}
disabled={isSaving}
size="small"
type="text"
@@ -107,7 +106,7 @@ const SaveBar = memo<SaveBarProps>(({ isDirty, isSaving, onReset, onSave }) => {
{t('proxy.resetButton')}
</Button>
<Button
- className={styles.saveButton}
+ className={stylex.props(styles.saveButton).className}
loading={isSaving}
size="small"
type="primary"
diff --git a/src/features/Settings/skill/features/AgentSkillItem.tsx b/src/features/Settings/skill/features/AgentSkillItem.tsx
index ce6418a6aa1..7d1a56a6201 100644
--- a/src/features/Settings/skill/features/AgentSkillItem.tsx
+++ b/src/features/Settings/skill/features/AgentSkillItem.tsx
@@ -13,6 +13,7 @@ import {
stopPropagation,
} from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
+import * as stylex from '@stylexjs/stylex';
import { DownloadIcon, MoreHorizontalIcon, Plus, Trash2 } from 'lucide-react';
import { lazy, memo, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -106,9 +107,9 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
const renderStatus = () => {
if (!isBuiltin) return null;
if (isBuiltinInstalled) {
- return <span className={styles.connected}>{t('tools.builtins.installed')}</span>;
+ return <span {...stylex.props(styles.connected)}>{t('tools.builtins.installed')}</span>;
}
- return <span className={styles.disconnected}>{t('tools.builtins.uninstalled')}</span>;
+ return <span {...stylex.props(styles.disconnected)}>{t('tools.builtins.uninstalled')}</span>;
};
const renderActions = () => {
@@ -231,7 +232,7 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={16}
justify="space-between"
style={{
@@ -248,10 +249,10 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect
style={{ cursor: onSelect ? undefined : 'pointer' }}
onClick={onSelect ? undefined : handleOpenDetail}
>
- <div className={`${styles.icon} ${showDisconnected ? styles.disconnectedIcon : ''}`}>
+ <div {...stylex.props(styles.icon, showDisconnected && styles.disconnectedIcon)}>
{avatar ? <Avatar avatar={avatar} size={16} /> : <Icon icon={SkillsIcon} size={16} />}
</div>
- <span className={`${styles.title} ${showDisconnected ? styles.disconnectedTitle : ''}`}>
+ <span {...stylex.props(styles.title, showDisconnected && styles.disconnectedTitle)}>
{title}
</span>
</Flexbox>
diff --git a/src/features/Settings/skill/features/BuiltinSkillItem.tsx b/src/features/Settings/skill/features/BuiltinSkillItem.tsx
index fe1cbea6331..0f49db3246e 100644
--- a/src/features/Settings/skill/features/BuiltinSkillItem.tsx
+++ b/src/features/Settings/skill/features/BuiltinSkillItem.tsx
@@ -10,6 +10,7 @@ import {
Icon,
stopPropagation,
} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { MoreHorizontalIcon, Plus, Trash2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -67,13 +68,13 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
const renderStatus = () => {
if (isInstalled) {
return (
- <span className={styles.connected}>
+ <span {...stylex.props(styles.connected)}>
{t('tools.builtins.installed', { ns: 'setting' })}
</span>
);
}
return (
- <span className={styles.disconnected}>
+ <span {...stylex.props(styles.disconnected)}>
{t('tools.builtins.uninstalled', { ns: 'setting' })}
</span>
);
@@ -128,7 +129,7 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={8}
justify="space-between"
style={{
@@ -145,10 +146,10 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(
style={{ cursor: onSelect ? undefined : 'pointer' }}
onClick={onSelect ? undefined : () => createBuiltinSkillDetailModal({ identifier })}
>
- <div className={`${styles.icon} ${!isInstalled ? styles.disconnectedIcon : ''}`}>
+ <div {...stylex.props(styles.icon, !isInstalled && styles.disconnectedIcon)}>
<Avatar avatar={avatar} size={16} />
</div>
- <span className={`${styles.title} ${!isInstalled ? styles.disconnectedTitle : ''}`}>
+ <span {...stylex.props(styles.title, !isInstalled && styles.disconnectedTitle)}>
{title}
</span>
</Flexbox>
diff --git a/src/features/Settings/skill/features/ComposioSkillItem.tsx b/src/features/Settings/skill/features/ComposioSkillItem.tsx
index 3a7fb0c3b4f..88059578832 100644
--- a/src/features/Settings/skill/features/ComposioSkillItem.tsx
+++ b/src/features/Settings/skill/features/ComposioSkillItem.tsx
@@ -12,6 +12,7 @@ import {
Icon,
Tooltip,
} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { MoreHorizontalIcon, RotateCcw, SquareArrowOutUpRight, Trash2, Unplug } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -240,7 +241,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(
const renderStatus = () => {
if (!server) {
return (
- <span className={styles.disconnected}>
+ <span {...stylex.props(styles.disconnected)}>
{t('tools.composio.disconnected', { defaultValue: 'Disconnected' })}
</span>
);
@@ -248,17 +249,17 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(
switch (server.status) {
case ComposioServerStatus.ACTIVE: {
- return <span className={styles.connected}>{t('tools.composio.connected')}</span>;
+ return <span {...stylex.props(styles.connected)}>{t('tools.composio.connected')}</span>;
}
case ComposioServerStatus.PENDING_AUTH: {
- return <span className={styles.pending}>{t('tools.composio.authRequired')}</span>;
+ return <span {...stylex.props(styles.pending)}>{t('tools.composio.authRequired')}</span>;
}
case ComposioServerStatus.ERROR: {
- return <span className={styles.error}>{t('tools.composio.error')}</span>;
+ return <span {...stylex.props(styles.error)}>{t('tools.composio.error')}</span>;
}
default: {
return (
- <span className={styles.disconnected}>
+ <span {...stylex.props(styles.disconnected)}>
{t('tools.composio.disconnected', { defaultValue: 'Disconnected' })}
</span>
);
@@ -452,7 +453,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={8}
justify="space-between"
style={{
@@ -468,10 +469,10 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(
gap={8}
style={{ cursor: onSelect ? undefined : 'pointer' }}
>
- <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>
+ <div {...stylex.props(styles.icon, !isConnected && styles.disconnectedIcon)}>
{renderIcon()}
</div>
- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>
+ <span {...stylex.props(styles.title, !isConnected && styles.disconnectedTitle)}>
{serverType.label}
</span>
</Flexbox>
diff --git a/src/features/Settings/skill/features/LeftPanel.tsx b/src/features/Settings/skill/features/LeftPanel.tsx
index ad8fb388693..3990817b153 100644
--- a/src/features/Settings/skill/features/LeftPanel.tsx
+++ b/src/features/Settings/skill/features/LeftPanel.tsx
@@ -1,15 +1,9 @@
'use client';
-import {
- Button,
- createStaticStyles,
- DropdownMenu,
- Flexbox,
- Icon,
- Text,
- Tooltip,
-} from '@lobehub/ui';
+import { Button, DropdownMenu, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { GithubIcon } from '@lobehub/ui/icons';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FileArchive, Grid2x2Plus, Link, Store } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,51 +20,43 @@ import { type ToolDetailType } from './SkillDetail';
import SkillList, { type SkillViewMode } from './SkillList';
import { SkillListVariantProvider } from './SkillListRow';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- body: css`
- overflow-y: auto;
- flex: 1;
- padding-block: 4px;
- padding-inline: 8px;
- `,
- pageBody: css`
- padding-block: 0 24px;
- padding-inline: 0;
- `,
- pageHeader: css`
- display: flex;
- flex-shrink: 0;
- gap: 16px;
- align-items: flex-start;
- justify-content: space-between;
-
- padding-block: 24px 16px;
- padding-inline: 12px;
- `,
- header: css`
- display: flex;
- flex-shrink: 0;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
-
- height: 42px;
- padding-inline: 16px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- root: css`
- overflow-y: auto;
- display: flex;
- flex-direction: column;
-
- width: 300px;
- min-width: 260px;
- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- tooltipAnchor: css`
- display: inline-flex;
- `,
-}));
+const styles = stylex.create({
+ body: { overflowY: 'auto', flex: '1', paddingBlock: '4px', paddingInline: '8px' },
+ pageBody: { paddingBlockStart: '0', paddingBlockEnd: '24px', paddingInline: '0' },
+ pageHeader: {
+ display: 'flex',
+ flexShrink: 0,
+ gap: '16px',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ paddingBlockStart: '24px',
+ paddingBlockEnd: '16px',
+ paddingInline: '12px',
+ },
+ header: {
+ display: 'flex',
+ flexShrink: 0,
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ height: '42px',
+ paddingInline: '16px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ root: {
+ overflowY: 'auto',
+ display: 'flex',
+ flexDirection: 'column',
+ width: '300px',
+ minWidth: '260px',
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ },
+ tooltipAnchor: { display: 'inline-flex' },
+});
interface LeftPanelProps {
/** Fill the page instead of sitting as a 300px column beside the detail (mobile). */
@@ -104,7 +90,7 @@ const LeftPanel = memo<LeftPanelProps>(
if (isConnectorPage)
return (
<SkillListVariantProvider value={'page'}>
- <div className={styles.pageHeader}>
+ <div {...stylex.props(styles.pageHeader)}>
<Flexbox gap={4}>
<Text as={'h1'} fontSize={20} style={{ margin: 0 }} weight={600}>
{t('skillView.connectors', 'Connectors')}
@@ -127,7 +113,7 @@ const LeftPanel = memo<LeftPanelProps>(
}
>
{/* Disabled buttons swallow hover events; the wrapper anchors the tooltip. */}
- <span className={styles.tooltipAnchor}>
+ <span {...stylex.props(styles.tooltipAnchor)}>
<Button
disabled={!canAddConnector}
icon={Grid2x2Plus}
@@ -140,7 +126,7 @@ const LeftPanel = memo<LeftPanelProps>(
</Flexbox>
</div>
<ConnectorManagePolicy variant={'page'} />
- <div className={styles.pageBody}>
+ <div {...stylex.props(styles.pageBody)}>
<SkillList
viewMode={viewMode}
onDeleteSelected={onDeleteSelected}
@@ -157,10 +143,10 @@ const LeftPanel = memo<LeftPanelProps>(
return (
<>
<div
- className={styles.root}
+ className={stylex.props(styles.root).className}
style={fullWidth ? { borderInlineEnd: 'none', width: '100%' } : undefined}
>
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<Text strong style={{ fontSize: 14 }}>
{isConnectorView
? t('skillView.connectors', 'Connectors')
@@ -178,7 +164,7 @@ const LeftPanel = memo<LeftPanelProps>(
}
>
{/* Disabled buttons swallow hover events; the wrapper anchors the tooltip. */}
- <span className={styles.tooltipAnchor}>
+ <span {...stylex.props(styles.tooltipAnchor)}>
<Button
disabled={!canAddConnector}
icon={Grid2x2Plus}
@@ -243,7 +229,7 @@ const LeftPanel = memo<LeftPanelProps>(
{isConnectorView && <ConnectorManagePolicy />}
- <div className={styles.body}>
+ <div {...stylex.props(styles.body)}>
<SkillList
selectedIdentifier={selectedIdentifier}
viewMode={viewMode}
diff --git a/src/features/Settings/skill/features/LobehubSkillItem.tsx b/src/features/Settings/skill/features/LobehubSkillItem.tsx
index 2165558a762..0d9052e6f36 100644
--- a/src/features/Settings/skill/features/LobehubSkillItem.tsx
+++ b/src/features/Settings/skill/features/LobehubSkillItem.tsx
@@ -12,6 +12,7 @@ import {
Icon,
Tooltip,
} from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { MoreHorizontalIcon, SquareArrowOutUpRight, Unplug } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -233,7 +234,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
const renderStatus = () => {
if (!server) {
return (
- <span className={styles.disconnected}>
+ <span {...stylex.props(styles.disconnected)}>
{t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}
</span>
);
@@ -242,17 +243,17 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
switch (server.status) {
case LobehubSkillStatus.CONNECTED: {
return (
- <span className={styles.connected}>
+ <span {...stylex.props(styles.connected)}>
{t('tools.lobehubSkill.connected', { defaultValue: 'Connected' })}
</span>
);
}
case LobehubSkillStatus.ERROR: {
- return <span className={styles.error}>{t('tools.lobehubSkill.error')}</span>;
+ return <span {...stylex.props(styles.error)}>{t('tools.lobehubSkill.error')}</span>;
}
default: {
return (
- <span className={styles.disconnected}>
+ <span {...stylex.props(styles.disconnected)}>
{t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}
</span>
);
@@ -374,7 +375,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={8}
justify="space-between"
style={{
@@ -395,10 +396,10 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(
: () => createLobehubSkillDetailModal({ identifier: provider.id })
}
>
- <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>
+ <div {...stylex.props(styles.icon, !isConnected && styles.disconnectedIcon)}>
{renderIcon()}
</div>
- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>
+ <span {...stylex.props(styles.title, !isConnected && styles.disconnectedTitle)}>
{provider.label}
</span>
</Flexbox>
diff --git a/src/features/Settings/skill/features/McpSkillItem.tsx b/src/features/Settings/skill/features/McpSkillItem.tsx
index 11573b2964e..4181058b563 100644
--- a/src/features/Settings/skill/features/McpSkillItem.tsx
+++ b/src/features/Settings/skill/features/McpSkillItem.tsx
@@ -2,6 +2,7 @@
import { Avatar, createModal, Flexbox, Icon } from '@lobehub/ui';
import { McpIcon } from '@lobehub/ui/icons';
+import * as stylex from '@stylexjs/stylex';
import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
@@ -85,7 +86,7 @@ const McpSkillItem = memo<McpSkillItemProps>(
<Flexbox
horizontal
align="center"
- className={styles.container}
+ className={stylex.props(styles.container).className}
gap={8}
justify="space-between"
style={{
@@ -95,14 +96,14 @@ const McpSkillItem = memo<McpSkillItemProps>(
onClick={onSelect}
>
<Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}>
- <div className={styles.icon}>
+ <div {...stylex.props(styles.icon)}>
{avatar && avatar !== 'MCP_AVATAR' ? (
<Avatar avatar={avatar} shape={'square'} size={16} />
) : (
<Icon icon={McpIcon} size={16} />
)}
</div>
- <span className={styles.title} onClick={onSelect ? undefined : openDetail}>
+ <span {...stylex.props(styles.title)} onClick={onSelect ? undefined : openDetail}>
{title}
</span>
</Flexbox>
diff --git a/src/features/Settings/skill/features/SkillDetail/index.tsx b/src/features/Settings/skill/features/SkillDetail/index.tsx
index 25037eb2191..8d82d5e60bf 100644
--- a/src/features/Settings/skill/features/SkillDetail/index.tsx
+++ b/src/features/Settings/skill/features/SkillDetail/index.tsx
@@ -2,16 +2,9 @@
import { getLobehubSkillProviderById } from '@lobechat/const';
import { agentDisplayName } from '@lobechat/types';
-import {
- Avatar,
- Button,
- confirmModal,
- createStaticStyles,
- Markdown,
- Skeleton,
- toast,
- Tooltip,
-} from '@lobehub/ui';
+import { Avatar, Button, confirmModal, Markdown, Skeleton, toast, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { Plus, SquareArrowOutUpRight, Trash2, Unplug, Wrench } from 'lucide-react';
import type { ReactNode } from 'react';
@@ -49,47 +42,36 @@ export type ToolDetailType =
| 'mcp-connector'
| 'plugin';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- description: css`
- margin-block-start: 8px;
- font-size: 13px;
- line-height: 1.6;
- color: ${cssVar.colorTextSecondary};
- `,
- header: css`
- display: flex;
- gap: 12px;
- align-items: flex-start;
- justify-content: space-between;
-
- padding-block: 20px 16px;
- padding-inline: 24px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- name: css`
- font-size: 16px;
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
- noPermissions: css`
- padding: 24px;
- font-size: 14px;
- color: ${cssVar.colorTextTertiary};
- `,
- noPermissionsHeader: css`
- display: flex;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- margin-block-end: 8px;
- `,
- noPermissionsTitle: css`
- font-size: 16px;
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ description: {
+ marginBlockStart: '8px',
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorTextSecondary,
+ },
+ header: {
+ display: 'flex',
+ gap: '12px',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ paddingBlockStart: '20px',
+ paddingBlockEnd: '16px',
+ paddingInline: '24px',
+ borderBlockEndWidth: '1px',
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ },
+ name: { fontSize: '16px', fontWeight: 600, color: cssVar.colorText },
+ noPermissions: { padding: '24px', fontSize: '14px', color: cssVar.colorTextTertiary },
+ noPermissionsHeader: {
+ display: 'flex',
+ gap: '12px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBlockEnd: '8px',
+ },
+ noPermissionsTitle: { fontSize: '16px', fontWeight: 600, color: cssVar.colorText },
+});
interface SkillDetailProps {
identifier: string;
@@ -458,13 +440,13 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {
if (type === 'builtin-skill') {
return (
<div style={{ flex: 1, overflow: 'auto' }}>
- <div className={styles.header}>
+ <div {...stylex.props(styles.header)}>
<div style={{ alignItems: 'flex-start', display: 'flex', gap: 12 }}>
{builtinSkill?.avatar && <Avatar avatar={builtinSkill.avatar} size={40} />}
<div>
- <div className={styles.name}>{builtinSkillTitle}</div>
+ <div {...stylex.props(styles.name)}>{builtinSkillTitle}</div>
{builtinSkillDescription && (
- <div className={styles.description}>{builtinSkillDescription}</div>
+ <div {...stylex.props(styles.description)}>{builtinSkillDescription}</div>
)}
</div>
</div>
@@ -512,9 +494,9 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {
if (noManifest || !connector) {
return (
- <div className={styles.noPermissions}>
- <div className={styles.noPermissionsHeader}>
- <div className={styles.noPermissionsTitle}>
+ <div {...stylex.props(styles.noPermissions)}>
+ <div {...stylex.props(styles.noPermissionsHeader)}>
+ <div {...stylex.props(styles.noPermissionsTitle)}>
{type === 'lobehub-connector' ? lobehubLabel : noPermissionsTitle}
</div>
{canMigrateLegacy ? (
diff --git a/src/features/Settings/skill/features/SkillList.tsx b/src/features/Settings/skill/features/SkillList.tsx
index 5cb57d89aca..816beee159b 100644
--- a/src/features/Settings/skill/features/SkillList.tsx
+++ b/src/features/Settings/skill/features/SkillList.tsx
@@ -8,8 +8,10 @@ import {
resolveConnectorCatalogItem,
} from '@lobechat/const';
import type { BuiltinSkillManifest, LobeBuiltinTool } from '@lobechat/types';
-import { Center, createStaticStyles, cx, Empty } from '@lobehub/ui';
+import { Center, Empty } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import type React from 'react';
@@ -41,54 +43,31 @@ import McpSkillItem from './McpSkillItem';
import type { ToolDetailType } from './SkillDetail';
import { useSkillListVariant } from './SkillListRow';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- display: flex;
- flex-direction: column;
- gap: 2px;
- `,
- description: css`
- margin-block-end: 8px;
- color: ${cssVar.colorTextSecondary};
- `,
- empty: css`
- padding: 24px;
- color: ${cssVar.colorTextTertiary};
- text-align: center;
- `,
- sectionHeader: css`
- cursor: pointer;
- user-select: none;
-
- display: flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 12px 4px;
- padding-inline: 4px;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
-
- &:hover {
- color: ${cssVar.colorText};
- }
- `,
- sectionHeaderPage: css`
- gap: 8px;
-
- padding-block: 24px 8px;
- padding-inline: 12px;
-
- font-size: 13px;
- font-weight: 600;
- `,
- sectionCount: css`
- font-weight: 400;
- color: ${cssVar.colorTextDescription};
- `,
-}));
+const styles = stylex.create({
+ container: { display: 'flex', flexDirection: 'column', gap: '2px' },
+ sectionHeader: {
+ cursor: 'pointer',
+ userSelect: 'none',
+ display: 'flex',
+ gap: '4px',
+ alignItems: 'center',
+ paddingBlockStart: '12px',
+ paddingBlockEnd: '4px',
+ paddingInline: '4px',
+ fontSize: '12px',
+ fontWeight: 500,
+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },
+ },
+ sectionHeaderPage: {
+ gap: '8px',
+ paddingBlockStart: '24px',
+ paddingBlockEnd: '8px',
+ paddingInline: '12px',
+ fontSize: '13px',
+ fontWeight: 600,
+ },
+ sectionCount: { fontWeight: 400, color: cssVar.colorTextDescription },
+});
export type SkillViewMode = 'connector' | 'skill';
@@ -337,7 +316,7 @@ const SkillList = memo<SkillListProps>(
// empty (error gated ahead of empty).
if (skillsError && !hasAnySkills) {
return (
- <Center className={styles.container} paddingBlock={48}>
+ <Center className={stylex.props(styles.container).className} paddingBlock={48}>
<AsyncError error={skillsError} variant={'block'} onRetry={reloadSkills} />
</Center>
);
@@ -345,7 +324,7 @@ const SkillList = memo<SkillListProps>(
if (!hasAnySkills) {
return (
- <Center className={styles.container} paddingBlock={48}>
+ <Center className={stylex.props(styles.container).className} paddingBlock={48}>
<Empty description={t('tab.skillDesc')} icon={SkillsIcon} title={t('tab.skillEmpty')} />
</Center>
);
@@ -443,16 +422,16 @@ const SkillList = memo<SkillListProps>(
if (isPage)
return (
<>
- <div className={cx(styles.sectionHeader, styles.sectionHeaderPage)}>
+ <div {...stylex.props(styles.sectionHeader, styles.sectionHeaderPage)}>
{label}
- {count !== undefined && <span className={styles.sectionCount}>{count}</span>}
+ {count !== undefined && <span {...stylex.props(styles.sectionCount)}>{count}</span>}
</div>
{children}
</>
);
return (
<>
- <div className={styles.sectionHeader} onClick={() => toggleSection(key)}>
+ <div {...stylex.props(styles.sectionHeader)} onClick={() => toggleSection(key)}>
{isCollapsed ? <ChevronRightIcon size={10} /> : <ChevronDownIcon size={10} />}
{label}
</div>
@@ -480,7 +459,7 @@ const SkillList = memo<SkillListProps>(
const hasAgentConnectors = isConnectorView && agentBoundConnectors.length > 0;
return (
- <div className={styles.container}>
+ <div {...stylex.props(styles.container)}>
{hasBuiltinTools &&
renderSection(
'builtinTools',
diff --git a/src/features/Settings/skill/features/style.ts b/src/features/Settings/skill/features/style.ts
index 85362b04a93..52c753e3b98 100644
--- a/src/features/Settings/skill/features/style.ts
+++ b/src/features/Settings/skill/features/style.ts
@@ -1,50 +1,46 @@
-import { createStaticStyles } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- connected: css`
- font-size: 12px;
- color: ${cssVar.colorSuccess};
- `,
- container: css`
- padding-block: 6px;
- padding-inline: 4px;
- `,
- disconnected: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- disconnectedIcon: css`
- opacity: 0.4;
- `,
- disconnectedTitle: css`
- opacity: 0.5;
- `,
- error: css`
- font-size: 12px;
- color: ${cssVar.colorError};
- `,
- icon: css`
- overflow: hidden;
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- width: 20px;
- height: 20px;
- border-radius: 4px;
- `,
- pending: css`
- font-size: 12px;
- color: ${cssVar.colorWarning};
- `,
- title: css`
- cursor: pointer;
- font-size: 14px;
- color: ${cssVar.colorText};
-
- &:hover {
- color: ${cssVar.colorPrimary};
- }
- `,
-}));
+export const styles = stylex.create({
+ connected: {
+ fontSize: '12px',
+ color: cssVar.colorSuccess,
+ },
+ container: {
+ paddingBlock: '6px',
+ paddingInline: '4px',
+ },
+ disconnected: {
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ },
+ disconnectedIcon: {
+ opacity: 0.4,
+ },
+ disconnectedTitle: {
+ opacity: 0.5,
+ },
+ error: {
+ fontSize: '12px',
+ color: cssVar.colorError,
+ },
+ icon: {
+ overflow: 'hidden',
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '20px',
+ height: '20px',
+ borderRadius: '4px',
+ },
+ pending: {
+ fontSize: '12px',
+ color: cssVar.colorWarning,
+ },
+ title: {
+ cursor: 'pointer',
+ fontSize: '14px',
+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorPrimary },
+ },
+});
diff --git a/src/features/Settings/skill/index.tsx b/src/features/Settings/skill/index.tsx
index ccba15cb2b7..78ffc57d2ff 100644
--- a/src/features/Settings/skill/index.tsx
+++ b/src/features/Settings/skill/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { ActionIcon, Button, createStaticStyles, Flexbox } from '@lobehub/ui';
+import { ActionIcon, Button, Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { ArrowLeft, ChevronLeft } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
@@ -27,32 +28,12 @@ export interface SelectedTool {
type: ToolDetailType;
}
-const styles = createStaticStyles(({ css }) => ({
- detail: css`
- overflow-y: auto;
- flex: 1;
- `,
- page: css`
- overflow-y: auto;
- display: flex;
- flex: 1;
- justify-content: center;
-
- height: 100%;
- `,
- pageBody: css`
- display: flex;
- flex-direction: column;
- width: 100%;
- max-width: 960px;
- `,
- root: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- height: 100%;
- `,
-}));
+const styles = stylex.create({
+ detail: { overflowY: 'auto', flex: '1' },
+ page: { overflowY: 'auto', display: 'flex', flex: '1', justifyContent: 'center', height: '100%' },
+ pageBody: { display: 'flex', flexDirection: 'column', width: '100%', maxWidth: '960px' },
+ root: { overflow: 'hidden', display: 'flex', flex: '1', height: '100%' },
+});
interface ToolSettingsProps {
/**
@@ -177,7 +158,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
// full-width instead of a 300px list squeezing the detail.
if (mobile)
return stackedSelected ? (
- <Flexbox className={styles.detail}>
+ <Flexbox className={stylex.props(styles.detail).className}>
<Flexbox horizontal align={'center'} paddingBlock={4} paddingInline={8}>
<ActionIcon icon={ChevronLeft} title={t('back')} onClick={closeStackedDetail} />
</Flexbox>
@@ -188,7 +169,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
/>
</Flexbox>
) : (
- <div className={styles.root}>
+ <div {...stylex.props(styles.root)}>
<LeftPanel
fullWidth
viewMode={viewMode}
@@ -204,8 +185,8 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
return (
<>
<NavHeader />
- <div className={styles.page}>
- <div className={styles.pageBody}>
+ <div {...stylex.props(styles.page)}>
+ <div {...stylex.props(styles.pageBody)}>
{stackedSelected ? (
<>
<Flexbox horizontal align={'center'} paddingBlock={12} paddingInline={4}>
@@ -236,7 +217,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
return (
<>
<NavHeader />
- <div className={styles.root}>
+ <div {...stylex.props(styles.root)}>
<LeftPanel
selectedIdentifier={selected?.identifier}
viewMode={viewMode}
@@ -245,7 +226,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
/>
{selected && (
- <div className={styles.detail}>
+ <div {...stylex.props(styles.detail)}>
<SkillDetail
identifier={selected.identifier}
type={selected.type}
diff --git a/src/features/Settings/stats/features/overview/ShareButton/Preview.tsx b/src/features/Settings/stats/features/overview/ShareButton/Preview.tsx
index ab6feb42a12..49b3ed5c78b 100644
--- a/src/features/Settings/stats/features/overview/ShareButton/Preview.tsx
+++ b/src/features/Settings/stats/features/overview/ShareButton/Preview.tsx
@@ -1,112 +1,112 @@
import { imageUrl, OFFICIAL_URL } from '@lobechat/const';
import {
Center,
+ // oxlint-disable-next-line stylex-migration/no-emotion-styles -- AiHeatmaps legend/footer and every descendant's scrollbar get no className
createStaticStyles,
cx,
Flexbox,
Grid,
lobeStaticStylish,
- responsive,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ProductLogo } from '@/components/Branding';
import UserAvatar from '@/features/User/UserAvatar';
+import { sx } from '@/styles/sx';
import AiHeatmaps from '../../visualization/AiHeatmaps';
import TotalMessages from '../TotalMessages';
import TotalTokens from '../TotalTokens';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- avatar: css`
- box-sizing: content-box;
- border: 4px solid ${cssVar.colorBgLayout};
- background: ${cssVar.colorText};
- `,
- background: css`
- position: relative;
-
- width: 100%;
- padding: 24px;
-
- background-color: ${cssVar.colorBgLayout};
- background-image: url(${imageUrl('screenshot_background.webp')});
- background-position: center;
- background-size: 120% 120%;
- `,
-
- container: css`
- position: relative;
-
- overflow: hidden;
-
- width: 100%;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: calc(${cssVar.borderRadiusLG} * 2);
+const styles = stylex.create({
+ avatar: {
+ boxSizing: 'content-box',
+ borderWidth: '4px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBgLayout,
+ backgroundColor: cssVar.colorText,
+ backgroundImage: 'none',
+ },
+ background: {
+ position: 'relative',
+ width: '100%',
+ padding: '24px',
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundPosition: 'center',
+ backgroundSize: '120% 120%',
+ },
+ container: {
+ position: 'relative',
+ overflow: 'hidden',
+ width: '100%',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: `calc(${cssVar.borderRadiusLG} * 2)`,
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundImage: 'none',
+ boxShadow: cssVar.boxShadow,
+ },
+ footer: {
+ fontSize: '12px',
+ color: cssVar.colorTextDescription,
+ },
+ preview: {
+ overflowX: 'hidden',
+ overflowY: 'scroll',
+ width: '100%',
+ maxHeight: { default: '70dvh', [media.sm]: '40dvh' },
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgLayout,
+ backgroundImage: 'none',
+ },
+ title: {
+ fontSize: '24px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ },
+});
- background: ${cssVar.colorBgLayout};
- box-shadow: ${cssVar.boxShadow};
- `,
- decs: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
- footer: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
+const fallback = createStaticStyles(({ css }) => ({
heatmaps: css`
.legend-month,
footer {
display: none;
}
`,
- preview: cx(
- lobeStaticStylish.noScrollbar,
- css`
- overflow: hidden scroll;
-
- width: 100%;
- max-height: 70dvh;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: ${cssVar.borderRadiusLG};
-
- background: ${cssVar.colorBgLayout};
-
- * {
- pointer-events: none;
+ preview: css`
+ * {
+ pointer-events: none;
- ::-webkit-scrollbar {
- width: 0 !important;
- height: 0 !important;
- }
+ ::-webkit-scrollbar {
+ width: 0 !important;
+ height: 0 !important;
}
-
- ${responsive.sm} {
- max-height: 40dvh;
- }
- `,
- ),
- title: css`
- font-size: 24px;
- font-weight: bold;
- text-align: center;
+ }
`,
}));
+const backgroundImage = { backgroundImage: `url(${imageUrl('screenshot_background.webp')})` };
+
const Preview = memo(() => {
const { t } = useTranslation('auth');
return (
- <div className={styles.preview}>
- <div className={styles.background} id={'preview'}>
- <Center className={styles.container} gap={12} padding={24}>
+ <div {...sx(styles.preview, cx(lobeStaticStylish.noScrollbar, fallback.preview))}>
+ <div {...sx(styles.background, backgroundImage)} id={'preview'}>
+ <Center className={stylex.props(styles.container).className} gap={12} padding={24}>
<ProductLogo size={24} type={'text'} />
- <div className={styles.title}>{t('stats.share.title')}</div>
+ <div {...stylex.props(styles.title)}>{t('stats.share.title')}</div>
<Flexbox horizontal align={'center'}>
<UserAvatar
- className={styles.avatar}
+ className={stylex.props(styles.avatar).className}
shape={'circle'}
size={48}
style={{
@@ -115,7 +115,7 @@ const Preview = memo(() => {
}}
/>
<Center
- className={styles.avatar}
+ className={stylex.props(styles.avatar).className}
height={48}
width={48}
style={{
@@ -132,7 +132,7 @@ const Preview = memo(() => {
blockMargin={2}
blockRadius={1}
blockSize={4.5}
- className={styles.heatmaps}
+ className={fallback.heatmaps}
width={'100%'}
style={{
marginTop: -12,
@@ -143,7 +143,7 @@ const Preview = memo(() => {
<TotalTokens inShare />
</Grid>
</Flexbox>
- <div className={styles.footer}>{OFFICIAL_URL}</div>
+ <div {...stylex.props(styles.footer)}>{OFFICIAL_URL}</div>
</Center>
</div>
</div>
diff --git a/src/features/Settings/stats/features/usage/UsageTable.tsx b/src/features/Settings/stats/features/usage/UsageTable.tsx
index 69502b2e026..ec0783212da 100644
--- a/src/features/Settings/stats/features/usage/UsageTable.tsx
+++ b/src/features/Settings/stats/features/usage/UsageTable.tsx
@@ -1,4 +1,6 @@
-import { createStaticStyles, cssVar, Flexbox, type TableColumn, Text, Tooltip } from '@lobehub/ui';
+import { Flexbox, type TableColumn, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -35,12 +37,10 @@ interface SortState {
order: 'ascend' | 'descend';
}
-const styles = createStaticStyles(({ css }) => ({
+const styles = stylex.create({
// Line the footer up with InlineTable's first/last cells.
- pagination: css`
- padding-inline: 24px;
- `,
-}));
+ pagination: { paddingInline: '24px' },
+});
const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
const { t } = useTranslation('auth');
@@ -187,7 +187,7 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
/>
{total > 0 && (
<TablePagination
- className={styles.pagination}
+ className={stylex.props(styles.pagination).className}
current={page}
pageSize={pageSize}
pageSizeOptions={PAGE_SIZE_OPTIONS}
diff --git a/src/features/Settings/trash/features/ProjectFilter.tsx b/src/features/Settings/trash/features/ProjectFilter.tsx
index e6248aaa142..b5c0e91bb14 100644
--- a/src/features/Settings/trash/features/ProjectFilter.tsx
+++ b/src/features/Settings/trash/features/ProjectFilter.tsx
@@ -3,7 +3,6 @@
import type { TrashProjectFilter } from '@lobechat/types';
import {
controlHeight,
- createStaticStyles,
cssVar,
Flexbox,
Icon,
@@ -11,6 +10,8 @@ import {
type SelectOptions,
Text,
} from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { FolderKanbanIcon, LockIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -29,19 +30,14 @@ import {
* that track's height (`controlHeight.middle`), radius and surface while
* keeping the small control's 12px text. Open / hover feedback stays.
*/
-const styles = createStaticStyles(({ css }) => ({
- trigger: css`
- min-height: ${controlHeight.middle}px;
- border-color: ${cssVar.colorFillQuaternary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgLayout};
-
- &:hover {
- border-color: ${cssVar.colorBorderSecondary};
- background: ${cssVar.colorBgLayout};
- }
- `,
-}));
+const styles = stylex.create({
+ trigger: {
+ borderColor: { 'default': sxVar.colorFillQuaternary, ':hover': sxVar.colorBorderSecondary },
+ borderRadius: sxVar.borderRadiusLG,
+ backgroundColor: sxVar.colorBgLayout,
+ backgroundImage: 'none',
+ },
+});
interface ProjectFilterProps {
error?: unknown;
@@ -112,13 +108,13 @@ export const ProjectFilter = ({
<Select
showSearch
aria-label={t('trash.filter.project.label')}
- className={styles.trigger}
+ className={stylex.props(styles.trigger).className}
loading={!projects && isValidating}
options={options}
popupMatchSelectWidth={280}
prefix={FolderKanbanIcon}
size={'small'}
- style={{ maxWidth: 260, minWidth: 160 }}
+ style={{ maxWidth: 260, minHeight: controlHeight.middle, minWidth: 160 }}
// Not `virtual`: the virtual list counts the whole project group as one
// row and crashes once search shrinks the options; search is the way
// through a long list.
diff --git a/src/features/Settings/trash/features/TrashList.tsx b/src/features/Settings/trash/features/TrashList.tsx
index 82d0d36b844..fe693bb5670 100644
--- a/src/features/Settings/trash/features/TrashList.tsx
+++ b/src/features/Settings/trash/features/TrashList.tsx
@@ -14,6 +14,7 @@ import {
Center,
confirmModal,
controlHeight,
+ // oxlint-disable-next-line stylex-migration/no-emotion-styles -- LiteTable body rows and title cells take no className
createStaticStyles,
Empty,
Flexbox,
@@ -23,6 +24,8 @@ import {
Text,
toast,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { useSize } from 'ahooks';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
@@ -60,38 +63,52 @@ const EMPTY_COUNTS: TrashCountByType = {};
const NAME_ICON_SIZE = 28;
const NAME_ICON_GAP = 10;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- overflow: hidden;
- padding-block: 16px;
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorBgContainer};
- `,
- /**
- * Type chips on the small control height: with the track's 3px padding and
- * 1px border the whole Segmented is `controlHeight.middle` tall, level with
- * the side switch, the project picker and the empty button beside it.
- */
- filterItem: css`
- height: ${controlHeight.small}px;
- `,
- header: css`
- display: flex;
- flex-wrap: wrap;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- padding-block-end: 16px;
- padding-inline: 24px;
- `,
- muted: css`
- color: ${cssVar.colorTextSecondary};
- `,
- name: css`
- width: 100%;
- min-width: 0;
- `,
+const CARD_LAYOUT_QUERY = `@container (max-width: ${TRASH_LIST_BREAKPOINT}px)`;
+
+/**
+ * Type chips on the small control height: with the track's 3px padding and
+ * 1px border the whole Segmented is `controlHeight.middle` tall, level with
+ * the side switch, the project picker and the empty button beside it.
+ */
+const segmentedStyles = { item: { height: controlHeight.small } };
+
+const styles = stylex.create({
+ container: {
+ overflow: 'hidden',
+ paddingBlock: '16px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgContainer,
+ backgroundImage: 'none',
+ },
+ header: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '12px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingBlockEnd: '16px',
+ paddingInline: '24px',
+ },
+ muted: {
+ color: cssVar.colorTextSecondary,
+ },
+ name: {
+ width: '100%',
+ minWidth: 0,
+ },
+ title: {
+ overflow: 'hidden',
+ fontWeight: 500,
+ textOverflow: 'ellipsis',
+ whiteSpace: { default: 'nowrap', [CARD_LAYOUT_QUERY]: 'normal' },
+ display: { default: null, [CARD_LAYOUT_QUERY]: '-webkit-box' },
+ WebkitBoxOrient: { default: null, [CARD_LAYOUT_QUERY]: 'vertical' },
+ WebkitLineClamp: { default: null, [CARD_LAYOUT_QUERY]: '2' },
+ overflowWrap: { default: null, [CARD_LAYOUT_QUERY]: 'anywhere' },
+ },
+});
+
+const fallback = createStaticStyles(({ css }) => ({
table: css`
@container (max-width: ${TRASH_LIST_BREAKPOINT}px) {
tbody tr {
@@ -103,21 +120,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}
}
`,
- title: css`
- overflow: hidden;
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
-
- @container (max-width: ${TRASH_LIST_BREAKPOINT}px) {
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- overflow-wrap: anywhere;
- white-space: normal;
- }
- `,
}));
interface TrashListProps {
@@ -352,7 +354,12 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
const avatar = item.meta?.avatar;
const title = item.title || t('trash.untitled');
return (
- <Flexbox horizontal align={'center'} className={styles.name} gap={NAME_ICON_GAP}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.name).className}
+ gap={NAME_ICON_GAP}
+ >
{avatar ? (
<Avatar
avatar={avatar}
@@ -372,7 +379,7 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
<Flexbox flex={1} style={{ minWidth: 0 }}>
<Text
as={'span'}
- className={styles.title}
+ className={stylex.props(styles.title).className}
tabIndex={0}
ellipsis={{
rows: cardLayout ? 2 : undefined,
@@ -412,7 +419,10 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
{
key: 'deletedAt',
render: (item) => (
- <span className={styles.muted} title={dayjs(item.deletedAt).format('YYYY-MM-DD HH:mm')}>
+ <span
+ {...stylex.props(styles.muted)}
+ title={dayjs(item.deletedAt).format('YYYY-MM-DD HH:mm')}
+ >
{dayjs(item.deletedAt).fromNow()}
</span>
),
@@ -432,7 +442,7 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
: []),
{
key: 'expiresAt',
- render: (item) => <span className={styles.muted}>{expiresLabel(item.expiresAt)}</span>,
+ render: (item) => <span {...stylex.props(styles.muted)}>{expiresLabel(item.expiresAt)}</span>,
title: t('trash.columns.expiresIn'),
},
{
@@ -479,13 +489,13 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
};
return (
- <div className={styles.container} ref={containerRef}>
- <div className={styles.header}>
+ <div {...stylex.props(styles.container)} ref={containerRef}>
+ <div {...stylex.props(styles.header)}>
<Flexbox horizontal align={'center'} gap={8} style={{ flexWrap: 'wrap', minWidth: 0 }}>
{visibility && (
<Segmented
- classNames={{ item: styles.filterItem }}
size={'small'}
+ styles={segmentedStyles}
value={visibility}
options={[
{ label: t('trash.side.public'), value: 'public' },
@@ -498,10 +508,10 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
/>
)}
<Segmented
- classNames={{ item: styles.filterItem }}
options={typeOptions}
size={'small'}
style={{ flexWrap: 'wrap', maxWidth: '100%' }}
+ styles={segmentedStyles}
value={activeType ?? 'all'}
onChange={(value) =>
changeFilter({
@@ -539,7 +549,7 @@ const TrashList = ({ isWorkspace = false }: TrashListProps) => {
)}
</div>
<LiteTable
- className={styles.table}
+ className={fallback.table}
columns={columns}
dataSource={items}
listBreakpoint={TRASH_LIST_BREAKPOINT}
diff --git a/src/features/SettingsSearch/SearchResults.tsx b/src/features/SettingsSearch/SearchResults.tsx
index 5ee97d85f57..ab0a66b9fd2 100644
--- a/src/features/SettingsSearch/SearchResults.tsx
+++ b/src/features/SettingsSearch/SearchResults.tsx
@@ -1,6 +1,8 @@
'use client';
-import { createStaticStyles, cssVar, Flexbox, Spin, Text } from '@lobehub/ui';
+import { Flexbox, Spin, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,11 +13,7 @@ import { isModifierClick } from '@/utils/navigation';
import { useSettingsSearchAnalytics } from './analytics';
import type { SettingsSearchResult } from './useSettingsSearch';
-const styles = createStaticStyles(({ css }) => ({
- match: css`
- color: ${cssVar.colorPrimary};
- `,
-}));
+const styles = stylex.create({ match: { color: cssVar.colorPrimary } });
const HighlightMatch = memo<{ query: string; text: string }>(({ text, query }) => {
const index = text.toLowerCase().indexOf(query.toLowerCase());
@@ -24,7 +22,7 @@ const HighlightMatch = memo<{ query: string; text: string }>(({ text, query }) =
return (
<>
{text.slice(0, index)}
- <span className={styles.match}>{text.slice(index, index + query.length)}</span>
+ <span {...stylex.props(styles.match)}>{text.slice(index, index + query.length)}</span>
{text.slice(index + query.length)}
</>
);
diff --git a/src/features/SettingsSearch/anchor.tsx b/src/features/SettingsSearch/anchor.tsx
index 52fb570a656..484b3e39243 100644
--- a/src/features/SettingsSearch/anchor.tsx
+++ b/src/features/SettingsSearch/anchor.tsx
@@ -1,6 +1,7 @@
'use client';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo, type PropsWithChildren, useEffect } from 'react';
import { useLocation } from 'react-router';
@@ -19,34 +20,40 @@ const POLL_INTERVAL = 100;
// tab switch, which is still a correct result).
const POLL_TIMEOUT = 3000;
-const styles = createStaticStyles(({ css }) => ({
- anchor: css`
- scroll-margin-block-start: 80px;
- `,
- highlight: css`
- border-radius: ${cssVar.borderRadius};
- animation: settings-search-highlight 1.2s ease-in-out 2;
-
- @keyframes settings-search-highlight {
- 0%,
- 100% {
- background: transparent;
- }
-
- 50% {
- /* One step above colorPrimaryBg — plain Bg is barely visible in dark mode */
- background: ${cssVar.colorPrimaryBgHover};
- }
- }
-
- @media (prefers-reduced-motion: reduce) {
- /* Keep the locate cue, drop the flashing: a steady highlight that the
- removal timer clears */
- background: ${cssVar.colorPrimaryBgHover};
- animation: none;
- }
- `,
-}));
+const highlightKeyframes = stylex.keyframes({
+ '0%': { backgroundColor: 'transparent' },
+ // One step above colorPrimaryBg — plain Bg is barely visible in dark mode
+ '50%': { backgroundColor: cssVar.colorPrimaryBgHover },
+ '100%': { backgroundColor: 'transparent' },
+});
+
+const styles = stylex.create({
+ anchor: {
+ scrollMarginBlockStart: '80px',
+ },
+ highlight: {
+ borderRadius: cssVar.borderRadius,
+ animationName: {
+ 'default': highlightKeyframes,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ animationDuration: { 'default': '1.2s', '@media (prefers-reduced-motion: reduce)': '0s' },
+ animationTimingFunction: {
+ 'default': 'ease-in-out',
+ '@media (prefers-reduced-motion: reduce)': 'ease',
+ },
+ animationIterationCount: { 'default': 2, '@media (prefers-reduced-motion: reduce)': 1 },
+ // Keep the locate cue, drop the flashing: a steady highlight that the
+ // removal timer clears
+ backgroundColor: {
+ 'default': null,
+ '@media (prefers-reduced-motion: reduce)': cssVar.colorPrimaryBgHover,
+ },
+ backgroundImage: { 'default': null, '@media (prefers-reduced-motion: reduce)': 'none' },
+ },
+});
+
+const highlightClassNames = (stylex.props(styles.highlight).className ?? '').split(' ');
/**
* Marks a settings section / item as a search target. Wrap the group title or
@@ -54,7 +61,7 @@ const styles = createStaticStyles(({ css }) => ({
* must match a `SETTINGS_SEARCH_ITEMS` entry's `anchor`.
*/
export const SettingsSearchAnchor = memo<PropsWithChildren<{ id: string }>>(({ id, children }) => (
- <span className={styles.anchor} {...{ [SETTINGS_ANCHOR_ATTR]: id }}>
+ <span {...stylex.props(styles.anchor)} {...{ [SETTINGS_ANCHOR_ATTR]: id }}>
{children}
</span>
));
@@ -86,8 +93,8 @@ export const scrollToSettingsAnchor = (anchor: string) => {
// text so the flash is visible at a glance.
const target =
el.closest(`.ant-form-item, .ant-collapse-header, [${SETTINGS_ANCHOR_ROW_ATTR}]`) ?? el;
- target.classList.add(styles.highlight);
- setTimeout(() => target.classList.remove(styles.highlight), HIGHLIGHT_DURATION);
+ target.classList.add(...highlightClassNames);
+ setTimeout(() => target.classList.remove(...highlightClassNames), HIGHLIGHT_DURATION);
};
tryScroll();
diff --git a/src/features/ToolSetting/ChannelItem.tsx b/src/features/ToolSetting/ChannelItem.tsx
index fa11d3b4fc0..ebe744dd29c 100644
--- a/src/features/ToolSetting/ChannelItem.tsx
+++ b/src/features/ToolSetting/ChannelItem.tsx
@@ -1,13 +1,6 @@
-import {
- Center,
- createStaticStyles,
- cx,
- Flexbox,
- SortableList,
- Switch,
- Text,
- Tooltip,
-} from '@lobehub/ui';
+import { Center, Flexbox, SortableList, Switch, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,37 +8,26 @@ import { getChannelDisplayName, getChannelIcon } from './const';
const ICON_SIZE = 24;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- icon: css`
- flex: none;
- width: ${ICON_SIZE}px;
- height: ${ICON_SIZE}px;
- `,
- inactive: css`
- opacity: 0.45;
- `,
- item: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
- transition: background 0.2s ease-in-out;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- name: css`
- font-weight: 500;
- `,
- rank: css`
- min-width: 16px;
-
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextQuaternary};
- text-align: end;
- `,
-}));
+const styles = stylex.create({
+ icon: { flex: 'none', width: `${ICON_SIZE}px`, height: `${ICON_SIZE}px` },
+ inactive: { opacity: 0.45 },
+ item: {
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ transition: 'background 0.2s ease-in-out',
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+ name: { fontWeight: 500 },
+ rank: {
+ minWidth: '16px',
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ color: cssVar.colorTextQuaternary,
+ textAlign: 'end',
+ },
+});
interface ChannelItemProps {
enabled: boolean;
@@ -78,17 +60,24 @@ const ChannelItem = memo<ChannelItemProps>(({ id, enabled, locked, rank, onToggl
<SortableList.Item
horizontal
align={'center'}
- className={styles.item}
+ className={stylex.props(styles.item).className}
gap={8}
id={id}
justify={'space-between'}
>
<Flexbox horizontal align={'center'} gap={8}>
<SortableList.DragHandle />
- <span className={styles.rank}>{rank ?? ''}</span>
- <Flexbox horizontal align={'center'} className={cx(!enabled && styles.inactive)} gap={10}>
- <Center className={styles.icon}>{getChannelIcon(id, ICON_SIZE)}</Center>
- <Text className={styles.name}>{getChannelDisplayName(id)}</Text>
+ <span {...stylex.props(styles.rank)}>{rank ?? ''}</span>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(!enabled && styles.inactive).className}
+ gap={10}
+ >
+ <Center className={stylex.props(styles.icon).className}>
+ {getChannelIcon(id, ICON_SIZE)}
+ </Center>
+ <Text className={stylex.props(styles.name).className}>{getChannelDisplayName(id)}</Text>
</Flexbox>
</Flexbox>
{locked ? (
diff --git a/src/features/Work/CanvasWorkCard.tsx b/src/features/Work/CanvasWorkCard.tsx
index 1df73c3c576..5f81dec3d65 100644
--- a/src/features/Work/CanvasWorkCard.tsx
+++ b/src/features/Work/CanvasWorkCard.tsx
@@ -1,12 +1,14 @@
'use client';
import type { WorkSummaryItem } from '@lobechat/types';
-import { cx, Flexbox, Tag, Text } from '@lobehub/ui';
+import { Flexbox, Tag, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { sx } from '@/styles/sx';
+
const styles = stylex.create({
bar: {
backgroundColor: cssVar.colorFillSecondary,
@@ -76,19 +78,18 @@ interface CanvasWorkCardProps {
className?: string;
item: WorkSummaryItem;
onOpen?: () => void;
+ xstyle?: stylex.StyleXStyles;
}
-const CanvasWorkCard = memo<CanvasWorkCardProps>(({ className, item, onOpen }) => {
+const CanvasWorkCard = memo<CanvasWorkCardProps>(({ className, item, onOpen, xstyle }) => {
const { t } = useTranslation('chat');
const version = item.event.version;
const updatedAt = new Date(item.event.createdAt ?? item.updatedAt).toLocaleString();
- const cardProps = stylex.props(styles.card, onOpen && styles.clickable);
return (
<Flexbox
horizontal
- {...cardProps}
- className={cx(cardProps.className, className)}
+ {...sx(styles.card, onOpen && styles.clickable, xstyle, className)}
onClick={onOpen}
>
<Flexbox gap={5} {...stylex.props(styles.thumb)}>
diff --git a/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx b/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx
index 6307c1678c4..5871ac622c7 100644
--- a/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx
+++ b/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx
@@ -2,14 +2,14 @@ import { type AgentLabelListItem } from '@lobechat/types';
import {
Button,
createModal,
- createStaticStyles,
- cx,
Flexbox,
Input,
ModalFooter,
toast,
useModalContext,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { t as translate } from 'i18next';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,25 +19,20 @@ import { useHomeStore } from '@/store/home';
import { DEFAULT_LABEL_COLOR, isValidLabelColor, LABEL_COLOR_PRESETS } from './constants';
import { isDuplicateLabelNameError } from './errors';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- swatch: css`
- cursor: pointer;
-
- width: 20px;
- height: 20px;
- border: 2px solid transparent;
- border-radius: 50%;
-
- transition: transform 0.1s;
-
- &:hover {
- transform: scale(1.15);
- }
- `,
- swatchActive: css`
- border-color: ${cssVar.colorText};
- `,
-}));
+const styles = stylex.create({
+ swatch: {
+ cursor: 'pointer',
+ width: '20px',
+ height: '20px',
+ borderWidth: '2px',
+ borderStyle: 'solid',
+ borderColor: 'transparent',
+ borderRadius: '50%',
+ transition: 'transform 0.1s',
+ transform: { 'default': null, ':hover': 'scale(1.15)' },
+ },
+ swatchActive: { borderColor: cssVar.colorText },
+});
export interface LabelFormModalOptions {
/**
@@ -139,10 +134,12 @@ const LabelFormContent = memo<LabelFormModalOptions>(({ assignTo, label, restore
{LABEL_COLOR_PRESETS.map((preset) => (
<span
aria-label={preset}
- className={cx(styles.swatch, color === preset && styles.swatchActive)}
key={preset}
role={'button'}
style={{ background: preset }}
+ className={
+ stylex.props(styles.swatch, color === preset && styles.swatchActive).className
+ }
onClick={() => setColor(preset)}
/>
))}
diff --git a/src/features/WorkspaceSetting/Labels/index.tsx b/src/features/WorkspaceSetting/Labels/index.tsx
index 11402bf3021..93627b0b179 100644
--- a/src/features/WorkspaceSetting/Labels/index.tsx
+++ b/src/features/WorkspaceSetting/Labels/index.tsx
@@ -5,7 +5,6 @@ import {
ActionIcon,
Button,
confirmModal,
- createStaticStyles,
DropdownMenu,
Empty,
Flexbox,
@@ -15,6 +14,8 @@ import {
toast,
Tooltip,
} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import isEqual from 'fast-deep-equal';
import {
@@ -41,26 +42,23 @@ import { openDeleteLabelModal } from './DeleteLabelModal';
import { isDuplicateLabelNameError } from './errors';
import { openLabelFormModal } from './LabelFormModal';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- dot: css`
- flex: none;
-
- width: 10px;
- height: 10px;
- border-radius: 50%;
-
- background: ${cssVar.colorFill};
- `,
- row: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-radius: ${cssVar.borderRadius};
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = stylex.create({
+ dot: {
+ flex: 'none',
+ width: '10px',
+ height: '10px',
+ borderRadius: '50%',
+ backgroundColor: cssVar.colorFill,
+ backgroundImage: 'none',
+ },
+ row: {
+ paddingBlock: '10px',
+ paddingInline: '12px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ backgroundImage: { 'default': null, ':hover': 'none' },
+ },
+});
interface LabelRowProps {
canManage: boolean;
@@ -158,7 +156,7 @@ const LabelRow = memo<LabelRowProps>(
);
return (
- <Flexbox horizontal align={'center'} className={styles.row} gap={12}>
+ <Flexbox horizontal align={'center'} className={stylex.props(styles.row).className} gap={12}>
<Flexbox
horizontal
align={'center'}
@@ -167,7 +165,7 @@ const LabelRow = memo<LabelRowProps>(
style={{ width: NAME_COL_WIDTH }}
>
<span
- className={styles.dot}
+ className={stylex.props(styles.dot).className}
style={label.color ? { background: label.color } : undefined}
/>
<Text ellipsis weight={500}>
diff --git a/src/routes/(main)/community/(detail)/agent/features/Header.tsx b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
index 84d781b3e6a..944e9db6139 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
@@ -181,10 +181,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
author
)}
<Icon icon={DotIcon} />
- <PublishedTime
- className={stylex.props(styles.time).className}
- date={createdAt as string}
- />
+ <PublishedTime date={createdAt as string} xstyle={styles.time} />
<AgentForkTag />
{!!forkCount && forkCount > 0 && (
<Tag color="default" icon={<Icon icon={GitBranchIcon} />}>
diff --git a/src/routes/(main)/community/(detail)/features/ShareButton.module.css b/src/routes/(main)/community/(detail)/features/ShareButton.css
similarity index 54%
rename from src/routes/(main)/community/(detail)/features/ShareButton.module.css
rename to src/routes/(main)/community/(detail)/features/ShareButton.css
index 0b22ea8e5bb..74a64181c5d 100644
--- a/src/routes/(main)/community/(detail)/features/ShareButton.module.css
+++ b/src/routes/(main)/community/(detail)/features/ShareButton.css
@@ -1,15 +1,15 @@
-.icon {
+.lobe-share-button-4579d448-icon {
border: 1px solid var(--lobe-color-fill-secondary);
}
-.icon svg {
+.lobe-share-button-4579d448-icon svg {
fill: var(--lobe-color-text-secondary);
}
-.icon:hover {
+.lobe-share-button-4579d448-icon:hover {
border: 1px solid var(--lobe-color-border-secondary);
}
-.icon:hover svg {
+.lobe-share-button-4579d448-icon:hover svg {
fill: var(--lobe-color-text);
}
diff --git a/src/routes/(main)/community/(detail)/features/ShareButton.tsx b/src/routes/(main)/community/(detail)/features/ShareButton.tsx
index 3e94fa660ff..8084b5e1522 100644
--- a/src/routes/(main)/community/(detail)/features/ShareButton.tsx
+++ b/src/routes/(main)/community/(detail)/features/ShareButton.tsx
@@ -1,3 +1,5 @@
+import './ShareButton.css';
+
import {
ActionIcon,
Avatar,
@@ -23,7 +25,6 @@ import ImperativeModal from '@/components/ImperativeModal';
import { useShare } from '@/hooks/useShare';
import CardBanner from '../../components/CardBanner';
-import iconStyles from './ShareButton.module.css';
const styles = stylex.create({
banner: {
@@ -106,7 +107,7 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {
item.icon && (
<a href={item.link} key={item.title} rel="noreferrer" target="_blank">
<ActionIcon
- className={iconStyles.icon}
+ className={'lobe-share-button-4579d448-icon'}
icon={item.icon}
size={{ blockSize: 36, borderRadius: 18, size: 16 }}
title={item.title}
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
index 64b182d60fc..4202109e473 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
@@ -176,10 +176,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
);
})()}
<Icon icon={DotIcon} />
- <PublishedTime
- className={stylex.props(styles.time).className}
- date={createdAt as string}
- />
+ <PublishedTime date={createdAt as string} xstyle={styles.time} />
<GroupAgentForkTag />
{!!forkCount && forkCount > 0 && (
<Tag color="default" icon={<Icon icon={GitBranchIcon} />}>
diff --git a/src/routes/(main)/community/(detail)/model/features/Header.tsx b/src/routes/(main)/community/(detail)/model/features/Header.tsx
index 672309bf77a..1495db4d63e 100644
--- a/src/routes/(main)/community/(detail)/model/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/model/features/Header.tsx
@@ -77,10 +77,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
{...abilities}
/>
<Icon icon={DotIcon} />
- <PublishedTime
- className={stylex.props(styles.time).className}
- date={releasedAt as string}
- />
+ <PublishedTime date={releasedAt as string} xstyle={styles.time} />
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx
index 4a220027abf..41df5114c62 100644
--- a/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx
+++ b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx
@@ -58,7 +58,7 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {
<Center className={stylex.props(styles.bannerInner).className}>
{backgroundImage && (
<div
- {...sx(shouldBlur && styles.bannerAvatar, undefined, {
+ {...sx(shouldBlur && styles.bannerAvatar, {
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
diff --git a/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx
index aa4b814efde..c72e3c3507c 100644
--- a/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx
@@ -59,7 +59,7 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {
<Center className={stylex.props(styles.bannerInner).className}>
{backgroundImage && (
<div
- {...sx(shouldBlur && styles.bannerAvatar, undefined, {
+ {...sx(shouldBlur && styles.bannerAvatar, {
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
diff --git a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
index 077e844e37e..01a01e044ca 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx
@@ -371,10 +371,7 @@ const UserAgentCard = memo<UserAgentCardProps>(
>
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={ClockIcon} size={14} />
- <PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
- date={createdAt}
- />
+ <PublishedTime date={createdAt} xstyle={styles.secondaryDesc} />
</Flexbox>
{category && t(`category.assistant.${category}` as any)}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
index f730042aa1f..9a2e7e9c66f 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx
@@ -308,10 +308,7 @@ const UserGroupCard = memo<UserGroupCardProps>(
>
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={ClockIcon} size={14} />
- <PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
- date={createdAt}
- />
+ <PublishedTime date={createdAt} xstyle={styles.secondaryDesc} />
</Flexbox>
{category && t(`category.groupAgent.${category}` as any, { defaultValue: category })}
</Flexbox>
diff --git a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
index 7a1d8fd57f5..71c9d9d6030 100644
--- a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx
@@ -199,10 +199,7 @@ const UserSkillCard = memo<UserSkillCardProps>(
icon={ClockIcon}
size={14}
/>
- <PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
- date={updatedAt}
- />
+ <PublishedTime date={updatedAt} xstyle={styles.secondaryDesc} />
</Flexbox>
</Flexbox>
</Block>
diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx
index 4a220027abf..41df5114c62 100644
--- a/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx
+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx
@@ -58,7 +58,7 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {
<Center className={stylex.props(styles.bannerInner).className}>
{backgroundImage && (
<div
- {...sx(shouldBlur && styles.bannerAvatar, undefined, {
+ {...sx(shouldBlur && styles.bannerAvatar, {
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
diff --git a/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx b/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx
index 8dbb394beb6..c1b02f7c940 100644
--- a/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx
+++ b/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx
@@ -87,7 +87,7 @@ const CreatorRewardBanner = memo(() => {
</div>
</Flexbox>
<div
- {...sx(styles.symbols, undefined, {
+ {...sx(styles.symbols, {
// Runtime CDN URL, so it cannot live in stylex.create.
backgroundImage: `url(${imageUrl('banner_creator.png')})`,
})}
diff --git a/src/routes/(main)/community/(list)/_layout/Footer.tsx b/src/routes/(main)/community/(list)/_layout/Footer.tsx
index 1c7445d3082..cfe6e51e21f 100644
--- a/src/routes/(main)/community/(list)/_layout/Footer.tsx
+++ b/src/routes/(main)/community/(list)/_layout/Footer.tsx
@@ -41,7 +41,7 @@ const Footer = memo(() => {
align={'center'}
flex={'none'}
gap={4}
- {...sx(styles.footer, undefined, {
+ {...sx(styles.footer, {
// The image URL is resolved at runtime (CDN base), so it cannot live in stylex.create.
backgroundBlendMode: isDarkMode ? 'screen' : 'multiply',
backgroundImage: `url(${imageUrl(isDarkMode ? 'community_footer_dark.webp' : 'community_footer_light.webp')})`,
diff --git a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx b/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
index f56ada426a7..713a17b5faa 100644
--- a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/List/Item.tsx
@@ -176,11 +176,7 @@ const AssistantItem = memo<DiscoverAssistantItem>(
</Flexbox>
{author && (
<div
- {...sx(
- !!userName && styles.author,
- undefined,
- userName ? undefined : { color: 'inherit' },
- )}
+ {...sx(!!userName && styles.author, userName ? undefined : { color: 'inherit' })}
onClick={userName ? handleAuthorClick : undefined}
>
{author}
@@ -222,9 +218,9 @@ const AssistantItem = memo<DiscoverAssistantItem>(
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={ClockIcon} size={14} />
<PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
date={updatedAt || createdAt}
template={'MMM DD, YYYY'}
+ xstyle={styles.secondaryDesc}
/>
</Flexbox>
{t(`category.assistant.${category}` as any)}
diff --git a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
index dc88121cb4a..967b1ea2801 100644
--- a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx
@@ -193,10 +193,7 @@ const McpItem = memo<DiscoverMcpItem>(
>
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={ClockIcon} size={14} />
- <PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
- date={updatedAt}
- />
+ <PublishedTime date={updatedAt} xstyle={styles.secondaryDesc} />
</Flexbox>
<Flexbox horizontal align={'center'} gap={8}>
{t(`mcp.categories.${category}.name` as any)}
diff --git a/src/routes/(main)/community/(list)/model/features/List/Item.tsx b/src/routes/(main)/community/(list)/model/features/List/Item.tsx
index 74dfc9c9d32..a1a97c0d4d3 100644
--- a/src/routes/(main)/community/(list)/model/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/model/features/List/Item.tsx
@@ -145,8 +145,8 @@ const ModelItem = memo<DiscoverModelItem>(
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={ClockIcon} size={14} />
<PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
date={releasedAt || dayjs().toISOString()}
+ xstyle={styles.secondaryDesc}
/>
</Flexbox>
<Popover
diff --git a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx b/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
index 790b20bdd66..61b40f99be2 100644
--- a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
+++ b/src/routes/(main)/community/(list)/skill/features/List/Item.tsx
@@ -225,10 +225,7 @@ const SkillItem = memo<DiscoverSkillItem>(
icon={ClockIcon}
size={14}
/>
- <PublishedTime
- className={stylex.props(styles.secondaryDesc).className}
- date={updatedAt}
- />
+ <PublishedTime date={updatedAt} xstyle={styles.secondaryDesc} />
</Flexbox>
<MetaInfo
className={stylex.props(styles.secondaryDesc).className}
diff --git a/src/routes/(main)/community/components/CardBanner.tsx b/src/routes/(main)/community/components/CardBanner.tsx
index 05a41e23e4b..4927ebf228d 100644
--- a/src/routes/(main)/community/components/CardBanner.tsx
+++ b/src/routes/(main)/community/components/CardBanner.tsx
@@ -35,7 +35,7 @@ const CardBanner = memo<CardBannerProps>(
align={'center'}
justify={'center'}
width={'100%'}
- {...sx([styles.banner, !avatar && styles.bannerEmpty], className)}
+ {...sx(styles.banner, !avatar && styles.bannerEmpty, className)}
{...props}
>
{avatar && (
diff --git a/src/routes/(mobile)/_layout/NavBar.module.css b/src/routes/(mobile)/_layout/NavBar.css
similarity index 67%
rename from src/routes/(mobile)/_layout/NavBar.module.css
rename to src/routes/(mobile)/_layout/NavBar.css
index db3b7058736..caa23546e3e 100644
--- a/src/routes/(mobile)/_layout/NavBar.module.css
+++ b/src/routes/(mobile)/_layout/NavBar.css
@@ -1,3 +1,3 @@
-.active svg {
+.lobe-nav-bar-c7ad71e3-active svg {
fill: color-mix(in srgb, var(--lobe-color-primary) 33%, transparent);
}
diff --git a/src/routes/(mobile)/_layout/NavBar.tsx b/src/routes/(mobile)/_layout/NavBar.tsx
index c1bdead4198..090eedf45f8 100644
--- a/src/routes/(mobile)/_layout/NavBar.tsx
+++ b/src/routes/(mobile)/_layout/NavBar.tsx
@@ -1,5 +1,7 @@
'use client';
+import './NavBar.css';
+
import { Icon } from '@lobehub/ui';
import { type TabBarProps } from '@lobehub/ui/mobile';
import { TabBar } from '@lobehub/ui/mobile';
@@ -14,8 +16,6 @@ import { useMobileNavigation } from '@/hooks/useMobileNavigation';
import { SidebarTabKey } from '@/store/global/initialState';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import moduleStyles from './NavBar.module.css';
-
const styles = stylex.create({
container: {
position: 'fixed',
@@ -37,7 +37,10 @@ const NavBar = memo(() => {
[
{
icon: (active: boolean) => (
- <Icon className={active ? moduleStyles.active : undefined} icon={MessageSquare} />
+ <Icon
+ className={active ? 'lobe-nav-bar-c7ad71e3-active' : undefined}
+ icon={MessageSquare}
+ />
),
key: SidebarTabKey.Chat,
onClick: () => {
@@ -47,7 +50,7 @@ const NavBar = memo(() => {
},
showMarket && {
icon: (active: boolean) => (
- <Icon className={active ? moduleStyles.active : undefined} icon={Compass} />
+ <Icon className={active ? 'lobe-nav-bar-c7ad71e3-active' : undefined} icon={Compass} />
),
key: SidebarTabKey.Community,
onClick: () => {
@@ -57,7 +60,7 @@ const NavBar = memo(() => {
},
{
icon: (active: boolean) => (
- <Icon className={active ? moduleStyles.active : undefined} icon={User} />
+ <Icon className={active ? 'lobe-nav-bar-c7ad71e3-active' : undefined} icon={User} />
),
key: SidebarTabKey.Me,
onClick: () => {
diff --git a/src/routes/(popup)/_layout/TitleBar.tsx b/src/routes/(popup)/_layout/TitleBar.tsx
index 173628d7168..1441d1ce328 100644
--- a/src/routes/(popup)/_layout/TitleBar.tsx
+++ b/src/routes/(popup)/_layout/TitleBar.tsx
@@ -56,7 +56,7 @@ const PopupTitleBar = memo<PopupTitleBarProps>(({ title }) => {
<Flexbox
horizontal
align={'center'}
- className={sx([styles.container], electronStylish.draggable).className}
+ className={sx(styles.container, electronStylish.draggable).className}
flex={'none'}
gap={4}
height={TITLE_BAR_HEIGHT}
diff --git a/src/spa/BootShell/AppShellSkeleton.tsx b/src/spa/BootShell/AppShellSkeleton.tsx
index b4fbdc1edaa..2aa758c8285 100644
--- a/src/spa/BootShell/AppShellSkeleton.tsx
+++ b/src/spa/BootShell/AppShellSkeleton.tsx
@@ -135,7 +135,7 @@ const AppShellSkeleton = memo<AppShellSkeletonProps>(({ id }) => {
<div aria-hidden id={id} {...sx(styles.root, CSS_VAR_CLASS)}>
{isDesktop && (
<div
- {...sx([styles.dragRegion], electronStylish.draggable, { height: TITLE_BAR_HEIGHT })}
+ {...sx(styles.dragRegion, electronStylish.draggable, { height: TITLE_BAR_HEIGHT })}
/>
)}
<Flexbox
@@ -184,9 +184,7 @@ const AppShellSkeleton = memo<AppShellSkeletonProps>(({ id }) => {
return (
<div aria-hidden id={id} {...sx(styles.root, CSS_VAR_CLASS)}>
{isDesktop && (
- <div
- {...sx([styles.dragRegion], electronStylish.draggable, { height: TITLE_BAR_HEIGHT })}
- />
+ <div {...sx(styles.dragRegion, electronStylish.draggable, { height: TITLE_BAR_HEIGHT })} />
)}
<Flexbox
horizontal
diff --git a/src/styles/sx.test.ts b/src/styles/sx.test.ts
index 7755ac2f29c..3db2100b678 100644
--- a/src/styles/sx.test.ts
+++ b/src/styles/sx.test.ts
@@ -11,29 +11,46 @@ const styles = stylex.create({
describe('sx', () => {
it('keeps StyleX classes and appends the caller className', () => {
- const { className = '' } = sx([styles.root, styles.active], 'caller');
+ const { className = '' } = sx(styles.root, styles.active, 'caller');
expect(className).toContain('styles.root');
expect(className).toContain('styles.active');
expect(className.endsWith(' caller')).toBe(true);
});
- it('drops falsy styles', () => {
+ it('drops falsy styles and class names', () => {
const active = false;
- const props = sx([styles.root, active && styles.active]);
+ const props = sx(styles.root, active && styles.active, undefined, '');
expect(props.className).toContain('styles.root');
expect(props.className).not.toContain('styles.active');
+ expect(props.className?.endsWith(' ')).toBe(false);
});
- it('merges dynamic StyleX styles with the caller style', () => {
- const props = sx(styles.width(120), undefined, { opacity: 0.5 });
+ it('takes an inline style without a className placeholder', () => {
+ const props = sx(styles.width(120), { opacity: 0.5 });
expect(props.style).toMatchObject({ opacity: 0.5 });
expect(Object.values(props.style ?? {})).toContain('120px');
});
+ it('lets later inline styles win over earlier ones', () => {
+ const props = sx(styles.root, { opacity: 0.5 }, 'caller', { opacity: 1 });
+
+ expect(props.style).toEqual({ opacity: 1 });
+ expect(props.className?.endsWith(' caller')).toBe(true);
+ });
+
+ it('still accepts nested StyleX arrays such as an xstyle prop', () => {
+ const xstyle = [styles.root, [styles.active]];
+ const { className = '' } = sx(xstyle);
+
+ expect(className).toContain('styles.root');
+ expect(className).toContain('styles.active');
+ });
+
it('returns undefined for empty className and style', () => {
expect(sx(null)).toEqual({ className: undefined, style: undefined });
+ expect(sx()).toEqual({ className: undefined, style: undefined });
});
});
diff --git a/src/styles/sx.ts b/src/styles/sx.ts
index 7d2ca3fb1be..4513422990b 100644
--- a/src/styles/sx.ts
+++ b/src/styles/sx.ts
@@ -6,25 +6,41 @@ import { type CSSProperties } from 'react';
* stylex.props for elements that also forward a caller's className / style, which
* spreading stylex.props cannot do (@stylexjs/no-conflicting-props).
*
- * <div {...sx([styles.root, active && styles.active], className, style)} />
+ * <div {...sx(styles.root, active && styles.active, className, style)} />
*
- * The caller's className is appended, not merged: StyleX rules carry raised
- * specificity, so a plain class cannot override them. Components that let callers
- * restyle them take an `xstyle?: StyleXStyles` prop and pass it in `styles`.
+ * Strings are appended as class names and plain objects merge into the inline style,
+ * in argument order; everything else goes to stylex.props. A caller's className
+ * cannot override StyleX rules, which carry raised specificity: components that let
+ * callers restyle them take an `xstyle?: StyleXStyles` prop and pass it here.
*
- * Mirror props' exported argument types explicitly: StyleXStyles restricts CSS
- * properties and rejects compiled custom properties and marker symbols. Deriving
- * Parameters<typeof stylex.props> also resolves to never in Bun's checker.
+ * Argument types mirror props' exports explicitly: StyleXStyles restricts CSS
+ * properties and rejects compiled custom properties and marker symbols.
*/
-type SxArgument = StyleXArray<
+type SxStyle = StyleXArray<
CompiledStyles | boolean | null | undefined | Readonly<[CompiledStyles, InlineStyles]>
>;
-export const sx = (styles: SxArgument, className?: string, style?: CSSProperties) => {
+type SxArgument = SxStyle | string | CSSProperties;
+
+const isInlineStyle = (argument: SxArgument): argument is CSSProperties =>
+ typeof argument === 'object' &&
+ argument !== null &&
+ !Array.isArray(argument) &&
+ !('$$css' in argument);
+
+export const sx = (...args: SxArgument[]) => {
+ const styles: SxStyle[] = [];
+ const classNames: string[] = [];
+ let inline: CSSProperties | undefined;
+ for (const argument of args) {
+ if (typeof argument === 'string') classNames.push(argument);
+ else if (isInlineStyle(argument)) inline = { ...inline, ...argument };
+ else styles.push(argument);
+ }
const props = stylex.props(styles);
- const mergedClassName = [props.className, className].filter(Boolean).join(' ');
+ const className = [props.className, ...classNames].filter(Boolean).join(' ');
return {
- className: mergedClassName || undefined,
- style: props.style || style ? { ...props.style, ...style } : undefined,
+ className: className || undefined,
+ style: props.style || inline ? { ...props.style, ...inline } : undefined,
};
};