🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔨 chore(dev): add a computed-style snapshot helper for StyleX migrations (#21329)
Inneid0843c6d531d
diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdindex 3f6c227763c..fc94cf16185 100644--- a/.agents/skills/react/SKILL.md+++ b/.agents/skills/react/SKILL.md@@ -22,6 +22,8 @@ user-invocable: false- 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`.- 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`.+- Check a migration in dev with the DevDock snapshot helper: on the migrated page run `__lobeStyleSnapshot.capture('<name>', '<root selector>')`, swap the files back (`git stash push -- <path>`), reload, run `__lobeStyleSnapshot.compare('<name>')`, then `git stash pop`. 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).## Component Prioritydiff --git a/src/features/DevDock/index.tsx b/src/features/DevDock/index.tsxindex 99e5f56a4f7..24907262fbb 100644--- a/src/features/DevDock/index.tsx+++ b/src/features/DevDock/index.tsx@@ -10,6 +10,7 @@ import PanelHost from './PanelHost';import ReactScanController from './ReactScanController';import { registerBuiltinDevDockItems } from './registerBuiltinItems';import { useDevDockStore } from './store';+import { installStyleSnapshot } from './styleSnapshot';const Mesurer = lazy(() => import('mesurer').then((module) => ({ default: module.Mesurer })));@@ -33,6 +34,7 @@ const MesurerPortal = () => {registerBuiltinDevDockItems();registerBusinessDevDockItems();+installStyleSnapshot();const DevDock = () => {const mesurer = useDevDockStore((state) => state.mesurer);diff --git a/src/features/DevDock/styleSnapshot/index.test.ts b/src/features/DevDock/styleSnapshot/index.test.tsnew file mode 100644index 00000000000..46f81d71bce--- /dev/null+++ b/src/features/DevDock/styleSnapshot/index.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, it } from 'vitest';++import { createStyleSnapshotApi } from '.';++afterEach(() => {+ document.body.innerHTML = '';+ localStorage.clear();+});++describe('createStyleSnapshotApi', () => {+ it('compares the current page against a snapshot saved before a reload', () => {+ document.body.innerHTML = '<main><p style="color: red">a</p></main><aside>noise</aside>';+ expect(createStyleSnapshotApi().capture('list', 'main')).toBe(1);++ document.body.innerHTML = '<main><p style="color: blue">a</p></main>';+ expect(createStyleSnapshotApi().compare('list')).toEqual([+ { changed: { color: ['red', 'blue'] }, key: '0', label: 'P:a' },+ ]);+ });++ it('clears only its own entries', () => {+ localStorage.setItem('other', '1');+ document.body.innerHTML = '<main></main>';+ const api = createStyleSnapshotApi();+ api.capture('list', 'main');+ api.clear();++ expect(() => api.compare('list')).toThrow('no snapshot named list');+ expect(localStorage.getItem('other')).toBe('1');+ });++ it('names the selector that matched nothing', () => {+ expect(() => createStyleSnapshotApi().capture('x', '#missing')).toThrow('#missing');+ });++ it('refuses to compare across viewport sizes', () => {+ document.body.innerHTML = '<main></main>';+ createStyleSnapshotApi().capture('list', 'main');+ const width = window.innerWidth;+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: width + 100 });++ try {+ expect(() => createStyleSnapshotApi().compare('list')).toThrow('viewport');+ } finally {+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: width });+ }+ });++ it('reads storage only when used, so blocked storage does not break DevDock', () => {+ const api = createStyleSnapshotApi(() => {+ throw new Error('storage blocked');+ });++ expect(() => api.capture('x', 'body')).toThrow('storage blocked');+ });+});diff --git a/src/features/DevDock/styleSnapshot/index.ts b/src/features/DevDock/styleSnapshot/index.tsnew file mode 100644index 00000000000..3b963274a79--- /dev/null+++ b/src/features/DevDock/styleSnapshot/index.ts@@ -0,0 +1,79 @@+import {+ captureStyles,+ diffStyleSnapshots,+ type PackedSnapshot,+ packSnapshot,+ type StyleSnapshotDiff,+ unpackSnapshot,+} from './snapshot';++const STORAGE_PREFIX = 'lobe-style-snapshot:';++interface StoredSnapshot {+ selector: string;+ snapshot: PackedSnapshot;+ viewport: string;+}++const viewport = () => `${window.innerWidth}x${window.innerHeight}`;++export interface StyleSnapshotApi {+ capture: (name: string, selector?: string) => number;+ clear: () => void;+ compare: (name: string, selector?: string) => StyleSnapshotDiff[];+}++declare global {+ interface Window {+ __lobeStyleSnapshot?: StyleSnapshotApi;+ }+}++const findRoot = (selector: string) => {+ const root = document.querySelector(selector);+ if (!root) throw new Error(`[styleSnapshot] no element matches ${selector}`);+ return root;+};++// Storage is read on use: a privacy-restricted browser throws on access, which+// at install time would take the whole DevDock chunk down with it.+export const createStyleSnapshotApi = (+ getStorage: () => Storage = () => localStorage,+): StyleSnapshotApi => ({+ capture: (name, selector = 'body') => {+ const entries = captureStyles(findRoot(selector));+ getStorage().setItem(+ STORAGE_PREFIX + name,+ JSON.stringify({+ selector,+ snapshot: packSnapshot(entries),+ viewport: viewport(),+ } satisfies StoredSnapshot),+ );+ return entries.length;+ },+ clear: () => {+ const storage = getStorage();+ const keys = Array.from({ length: storage.length }, (_, index) => storage.key(index));+ for (const key of keys) {+ if (key?.startsWith(STORAGE_PREFIX)) storage.removeItem(key);+ }+ },+ compare: (name, selector) => {+ const raw = getStorage().getItem(STORAGE_PREFIX + name);+ if (!raw) throw new Error(`[styleSnapshot] no snapshot named ${name}`);+ const saved = JSON.parse(raw) as StoredSnapshot;+ if (saved.viewport !== viewport())+ throw new Error(+ `[styleSnapshot] viewport changed from ${saved.viewport} to ${viewport()}; resize back before comparing`,+ );+ return diffStyleSnapshots(+ unpackSnapshot(saved.snapshot),+ captureStyles(findRoot(selector ?? saved.selector)),+ );+ },+});++export const installStyleSnapshot = () => {+ window.__lobeStyleSnapshot = createStyleSnapshotApi();+};diff --git a/src/features/DevDock/styleSnapshot/snapshot.test.ts b/src/features/DevDock/styleSnapshot/snapshot.test.tsnew file mode 100644index 00000000000..a0e02f2c8b5--- /dev/null+++ b/src/features/DevDock/styleSnapshot/snapshot.test.ts@@ -0,0 +1,131 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { captureStyles, diffStyleSnapshots, packSnapshot, unpackSnapshot } from './snapshot';++const mount = (html: string) => {+ const root = document.createElement('div');+ root.innerHTML = html;+ document.body.append(root);+ return root;+};++afterEach(() => {+ document.body.innerHTML = '';+ vi.restoreAllMocks();+});++describe('captureStyles', () => {+ it('keys elements by their path under the root and labels them by tag and text', () => {+ const root = mount('<section><span>Hello world</span></section><p>Bye</p>');+ const keys = captureStyles(root).map(({ key, label }) => [key, label]);++ expect(keys).toEqual([+ ['0', 'SECTION:Hello world'],+ ['0.0', 'SPAN:Hello world'],+ ['1', 'P:Bye'],+ ]);+ });++ it('skips subtrees that are not rendered', () => {+ const root = mount('<div style="display: none"><span>hidden</span></div><p>shown</p>');++ expect(captureStyles(root).map(({ label }) => label)).toEqual(['P:shown']);+ });+ it('does not record boxes inside a running animation', () => {+ const root = mount('<div><span>spin</span></div><p>still</p>');+ const spinner = root.firstElementChild as HTMLElement;+ spinner.getAnimations = () => [{ playState: 'running' } as Animation];++ const entries = captureStyles(root);+ expect(entries.map(({ box, label }) => [label, box])).toEqual([+ ['DIV:spin', 'animated'],+ ['SPAN:spin', 'animated'],+ ['P:still', '0,0,0,0'],+ ]);+ expect(entries[0].style.opacity).toBe('animated');+ });++ it('records ::before and ::after that render content', () => {+ const root = mount('<p>a</p>');+ const real = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => {+ const style = real(element);+ if (pseudo !== '::before') return style;+ return new Proxy(style, {+ get: (target, prop) =>+ prop === 'content' ? '"*"' : prop === 'color' ? 'red' : Reflect.get(target, prop),+ });+ });++ const entries = captureStyles(root);+ expect(entries.map(({ key, label }) => [key, label])).toEqual([+ ['0', 'P:a'],+ ['0::before', 'P::before:"*"'],+ ]);+ expect(entries[1].style.color).toBe('red');+ });++ it('refuses to capture while something under the root is scrolled', () => {+ const root = mount('<div><p>a</p></div>');+ Object.defineProperty(root.firstElementChild, 'scrollTop', { value: 120 });++ expect(() => captureStyles(root)).toThrow('0 DIV:a is scrolled');+ });+});++describe('diffStyleSnapshots', () => {+ it('reports changed properties and boxes per element', () => {+ const root = mount('<div style="color: red; width: 10px">a</div>');+ const before = captureStyles(root);+ (root.firstElementChild as HTMLElement).style.color = 'blue';+ const after = captureStyles(root);++ expect(diffStyleSnapshots(before, after)).toEqual([+ { changed: { color: ['red', 'blue'] }, key: '0', label: 'DIV:a' },+ ]);+ });++ it('reports text that changed, which explains layout shifts', () => {+ const root = mount('<p>7 minutes ago</p>');+ const before = captureStyles(root);+ root.firstElementChild!.textContent = '10 minutes ago';++ expect(diffStyleSnapshots(before, captureStyles(root))).toEqual([+ { key: '0', label: 'P:7 minutes ago', text: ['P:7 minutes ago', 'P:10 minutes ago'] },+ ]);+ });++ it('reports elements that only exist on one side', () => {+ const before = captureStyles(mount('<p>a</p>'));+ document.body.innerHTML = '';+ const after = captureStyles(mount('<p>a</p><b>b</b>'));++ expect(diffStyleSnapshots(before, after)).toEqual([{ added: true, key: '1', label: 'B:b' }]);+ expect(diffStyleSnapshots(after, before)).toEqual([{ key: '1', label: 'B:b', removed: true }]);+ });++ it('tracks transforms, which do not change a square box', () => {+ const root = mount('<div style="width: 10px; height: 10px">a</div>');+ const before = captureStyles(root);+ (root.firstElementChild as HTMLElement).style.transform = 'rotate(90deg)';++ expect(diffStyleSnapshots(before, captureStyles(root))[0].changed).toHaveProperty('transform');+ });++ it('returns nothing for identical snapshots', () => {+ const root = mount('<div style="padding: 4px"><span>x</span></div>');++ expect(diffStyleSnapshots(captureStyles(root), captureStyles(root))).toEqual([]);+ });+});++describe('packSnapshot', () => {+ it('stores each distinct style once and restores the entries', () => {+ const root = mount('<p style="color: red">a</p><p style="color: red">b</p><p>c</p>');+ const entries = captureStyles(root);+ const packed = packSnapshot(entries);++ expect(packed.styles).toHaveLength(2);+ expect(unpackSnapshot(packed)).toEqual(entries);+ });+});diff --git a/src/features/DevDock/styleSnapshot/snapshot.ts b/src/features/DevDock/styleSnapshot/snapshot.tsnew file mode 100644index 00000000000..92758f45fc0--- /dev/null+++ b/src/features/DevDock/styleSnapshot/snapshot.ts@@ -0,0 +1,221 @@+const STYLE_PROPS = [+ 'display',+ 'position',+ 'zIndex',+ 'visibility',+ 'flexDirection',+ 'flexWrap',+ 'alignItems',+ 'justifyContent',+ 'gap',+ 'gridTemplateColumns',+ 'overflow',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'marginTop',+ 'marginRight',+ 'marginBottom',+ 'marginLeft',+ 'width',+ 'height',+ 'minWidth',+ 'maxWidth',+ 'transform',+ 'color',+ 'backgroundColor',+ 'backgroundImage',+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'lineHeight',+ 'letterSpacing',+ 'textAlign',+ 'textDecorationLine',+ 'textOverflow',+ 'whiteSpace',+ 'borderTopWidth',+ 'borderRightWidth',+ 'borderBottomWidth',+ 'borderLeftWidth',+ 'borderTopStyle',+ 'borderRightStyle',+ 'borderBottomStyle',+ 'borderLeftStyle',+ 'borderTopColor',+ 'borderRightColor',+ 'borderBottomColor',+ 'borderLeftColor',+ 'borderTopLeftRadius',+ 'borderTopRightRadius',+ 'borderBottomRightRadius',+ 'borderBottomLeftRadius',+ 'outlineStyle',+ 'outlineWidth',+ 'outlineColor',+ 'boxShadow',+ 'opacity',+ 'cursor',+ 'pointerEvents',+ 'transition',+ 'animationName',+] as const;++type StyleProp = (typeof STYLE_PROPS)[number];++export interface StyleSnapshotEntry {+ box: string;+ key: string;+ label: string;+ style: Record<StyleProp, string>;+}++export interface StyleSnapshotDiff {+ added?: true;+ box?: [string, string];+ changed?: Partial<Record<StyleProp, [string, string]>>;+ key: string;+ label: string;+ removed?: true;+ text?: [string, string];+}++const ANIMATED = 'animated';+const PSEUDO_ELEMENTS = ['::before', '::after'] as const;++const isAnimating = (element: Element) =>+ element.getAnimations?.().some((animation) => animation.playState === 'running') ?? false;++const pickStyle = (computed: CSSStyleDeclaration, animated: boolean) =>+ Object.fromEntries(+ STYLE_PROPS.map((prop) => [prop, animated ? ANIMATED : computed[prop]]),+ ) as Record<StyleProp, string>;++// Boxes are relative to the root so a recentered modal or a scrolled page does+// not register as a change; a scrolled container inside the root would, so+// capture refuses it. Elements under a running animation (spinners, pulses)+// change every frame, so neither their boxes nor their styles are recorded.+export const captureStyles = (root: Element): StyleSnapshotEntry[] => {+ const origin = root.getBoundingClientRect();+ const entries: StyleSnapshotEntry[] = [];++ const assertNotScrolled = (element: Element, key: string) => {+ if (element.scrollTop || element.scrollLeft)+ throw new Error(+ `[styleSnapshot] ${key} ${element.tagName}:${(element.textContent ?? '').trim().slice(0, 24)} is scrolled; scroll it back to the start, or narrow the root selector`,+ );+ };++ const visit = (element: Element, key: string, insideAnimation: boolean) => {+ const computed = getComputedStyle(element);+ if (computed.display === 'none') return;+ assertNotScrolled(element, key);++ const animated = insideAnimation || isAnimating(element);+ const rect = element.getBoundingClientRect();+ entries.push({+ box: animated+ ? ANIMATED+ : [rect.x - origin.x, rect.y - origin.y, rect.width, rect.height]+ .map((n) => Math.round(n))+ .join(','),+ key,+ label: `${element.tagName}:${(element.textContent ?? '').trim().slice(0, 24)}`,+ style: pickStyle(computed, animated),+ });++ for (const pseudo of PSEUDO_ELEMENTS) {+ const pseudoStyle = getComputedStyle(element, pseudo);+ if (['', 'none', 'normal'].includes(pseudoStyle.content)) continue;+ entries.push({+ box: 'pseudo',+ key: `${key}${pseudo}`,+ label: `${element.tagName}${pseudo}:${pseudoStyle.content.slice(0, 24)}`,+ style: pickStyle(pseudoStyle, animated),+ });+ }++ [...element.children].forEach((child, index) => visit(child, `${key}.${index}`, animated));+ };++ assertNotScrolled(root, 'root');+ [...root.children].forEach((child, index) => visit(child, String(index), false));+ return entries;+};++export const diffStyleSnapshots = (+ before: StyleSnapshotEntry[],+ after: StyleSnapshotEntry[],+): StyleSnapshotDiff[] => {+ const afterByKey = new Map(after.map((entry) => [entry.key, entry]));+ const beforeKeys = new Set(before.map((entry) => entry.key));+ const diffs: StyleSnapshotDiff[] = [];++ for (const prev of before) {+ const next = afterByKey.get(prev.key);+ if (!next) {+ diffs.push({ key: prev.key, label: prev.label, removed: true });+ continue;+ }+ const changed: StyleSnapshotDiff['changed'] = {};+ for (const prop of STYLE_PROPS) {+ if (prev.style[prop] !== next.style[prop])+ changed[prop] = [prev.style[prop], next.style[prop]];+ }+ const boxChanged = prev.box !== next.box;+ const textChanged = prev.label !== next.label;+ if (boxChanged || textChanged || Object.keys(changed).length > 0)+ diffs.push({+ ...(boxChanged && { box: [prev.box, next.box] as [string, string] }),+ ...(Object.keys(changed).length > 0 && { changed }),+ key: prev.key,+ label: prev.label,+ ...(textChanged && { text: [prev.label, next.label] as [string, string] }),+ });+ }++ for (const next of after) {+ if (!beforeKeys.has(next.key)) diffs.push({ added: true, key: next.key, label: next.label });+ }++ return diffs;+};++export interface PackedSnapshot {+ rows: [key: string, label: string, box: string, style: number][];+ styles: string[];+}++const STYLE_SEPARATOR = '\u0001';++// localStorage holds ~5 MB per origin; most elements share one computed style.+export const packSnapshot = (entries: StyleSnapshotEntry[]): PackedSnapshot => {+ const styles: string[] = [];+ const ids = new Map<string, number>();+ const rows = entries.map(({ box, key, label, style }): PackedSnapshot['rows'][number] => {+ const packed = STYLE_PROPS.map((prop) => style[prop]).join(STYLE_SEPARATOR);+ let id = ids.get(packed);+ if (id === undefined) {+ id = styles.length;+ styles.push(packed);+ ids.set(packed, id);+ }+ return [key, label, box, id];+ });+ return { rows, styles };+};++export const unpackSnapshot = ({ rows, styles }: PackedSnapshot): StyleSnapshotEntry[] =>+ rows.map(([key, label, box, id]) => {+ const values = styles[id].split(STYLE_SEPARATOR);+ return {+ box,+ key,+ label,+ style: Object.fromEntries(STYLE_PROPS.map((prop, index) => [prop, values[index]])) as Record<+ StyleProp,+ string+ >,+ };+ });