Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): add theme selector codemod (#2818)

Cindy Zhangd4d7ade76871
diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjs
index ff4e4ee9a8..bc1fd609b3 100644
--- a/packages/cli/src/codemods/runner.mjs
+++ b/packages/cli/src/codemods/runner.mjs
@@ -17,8 +17,14 @@ import {humanLog} from '../lib/json.mjs';
// Known corruption patterns that indicate a broken transform.
// Each entry: [regex, human-readable description]
const CORRUPTION_PATTERNS = [
- [/\[native code\]/g, '[native code] injection (prototype pollution in identifier map)'],
- [/function \w+\(\) \{ \[native code\] \}/g, 'native function toString() leak'],
+ [
+ /\[native code\]/g,
+ '[native code] injection (prototype pollution in identifier map)',
+ ],
+ [
+ /function \w+\(\) \{ \[native code\] \}/g,
+ 'native function toString() leak',
+ ],
];
/**
@@ -36,10 +42,7 @@ const CORRUPTION_PATTERNS = [
* @returns {string}
*/
export function fixDirectiveCorruption(code) {
- return code.replace(
- /^(['"]use (client|server|strict)['"]);\s*;/gm,
- '$1;',
- );
+ return code.replace(/^(['"]use (client|server|strict)['"]);\s*;/gm, '$1;');
}
/**
@@ -49,7 +52,18 @@ export function fixDirectiveCorruption(code) {
*/
function findSourceFiles(dir) {
const results = [];
- const extensions = new Set(['.tsx', '.ts', '.jsx', '.js']);
+ const extensions = new Set([
+ '.tsx',
+ '.ts',
+ '.jsx',
+ '.js',
+ '.mjs',
+ '.cjs',
+ '.css',
+ '.scss',
+ '.sass',
+ '.less',
+ ]);
function walk(currentDir) {
let entries;
@@ -84,7 +98,7 @@ async function formatChangedFiles(files, silent = false) {
if (files.length === 0) return;
const {execSync} = await import('node:child_process');
- const fileArgs = files.map((f) => `"${f}"`).join(' ');
+ const fileArgs = files.map(f => `"${f}"`).join(' ');
const prefix = getRunPrefix();
const formatters = [
@@ -95,7 +109,10 @@ async function formatChangedFiles(files, silent = false) {
for (const {name, cmd} of formatters) {
try {
execSync(cmd, {stdio: 'pipe', timeout: 30000});
- if (!silent) p.log.info(`Formatted ${files.length} file${files.length === 1 ? '' : 's'} with ${name}`);
+ if (!silent)
+ p.log.info(
+ `Formatted ${files.length} file${files.length === 1 ? '' : 's'} with ${name}`,
+ );
return;
} catch {
// Formatter not available or failed — try next
@@ -115,15 +132,17 @@ async function formatChangedFiles(files, silent = false) {
* @param {Function} j - jscodeshift instance (with parser configured)
* @returns {{ valid: boolean, reason?: string }}
*/
-export function validateOutput(result, source, j) {
+export function validateOutput(result, source, j, {parse = true} = {}) {
// Check 1: Re-parse the output — catches syntax-breaking corruption
- try {
- j(result);
- } catch (parseError) {
- return {
- valid: false,
- reason: `transform produced unparseable output: ${parseError.message}`,
- };
+ if (parse) {
+ try {
+ j(result);
+ } catch (parseError) {
+ return {
+ valid: false,
+ reason: `transform produced unparseable output: ${parseError.message}`,
+ };
+ }
}
// Check 2: Known corruption patterns (only flag new ones, not pre-existing)
@@ -153,13 +172,18 @@ export function validateOutput(result, source, j) {
* @param {string|undefined} options.codemod - Run only this specific transform
* @param {boolean} [options.silent] - Suppress all human-facing output (for --json)
*/
-export async function runCodemods(versionManifests, {apply, path: srcPath, codemod, silent = false}) {
+export async function runCodemods(
+ versionManifests,
+ {apply, path: srcPath, codemod, silent = false},
+) {
// No-op stub object so silent mode skips clack stdout entirely without
// littering the body with `if (!silent)` guards.
const log = silent
? {step() {}, info() {}, success() {}, warn() {}, error() {}, message() {}}
: p.log;
- const writeBlank = () => { if (!silent) humanLog(''); };
+ const writeBlank = () => {
+ if (!silent) humanLog('');
+ };
const resolvedPath = path.resolve(srcPath);
@@ -173,7 +197,14 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
if (files.length === 0) {
log.warn('No source files found.');
- return {ok: true, totalFilesChanged: 0, totalTransformsApplied: 0, errors: [], writtenFiles: [], skippedOptional: []};
+ return {
+ ok: true,
+ totalFilesChanged: 0,
+ totalTransformsApplied: 0,
+ errors: [],
+ writtenFiles: [],
+ skippedOptional: [],
+ };
}
log.info(`Found ${files.length} source file${files.length === 1 ? '' : 's'}`);
@@ -196,6 +227,9 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
if (codemod && transformEntry.name !== codemod) continue;
const {name, transform, meta, optional} = transformEntry;
+ const transformExtensions = new Set(
+ meta.fileExtensions ?? ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs'],
+ );
// Skip optional codemods unless explicitly requested via --codemod
if (optional && !codemod) {
@@ -211,10 +245,14 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
const relativePath = path.relative(process.cwd(), filePath);
try {
+ const ext = path.extname(filePath);
+ if (!transformExtensions.has(ext)) {
+ continue;
+ }
+
const source = fs.readFileSync(filePath, 'utf-8');
// Configure parser based on file extension
- const ext = path.extname(filePath);
- const parser = (ext === '.tsx' || ext === '.ts') ? 'tsx' : 'babel';
+ const parser = ext === '.tsx' || ext === '.ts' ? 'tsx' : 'babel';
const j = jscodeshift.withParser(parser);
const api = {
jscodeshift: j,
@@ -230,11 +268,19 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
result = fixDirectiveCorruption(result);
// Validate output before writing
- const validation = validateOutput(result, source, j);
+ const validation = validateOutput(result, source, j, {
+ parse: ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs'].includes(
+ ext,
+ ),
+ });
if (!validation.valid) {
totalValidationBlocked++;
log.error(` ✗ ${relativePath} — ${validation.reason}`);
- errors.push({file: relativePath, codemod: name, error: validation.reason});
+ errors.push({
+ file: relativePath,
+ codemod: name,
+ error: validation.reason,
+ });
continue;
}
@@ -258,7 +304,9 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
if (filesChanged > 0) {
const verb = apply ? 'Updated' : 'Would update';
- log.info(` ${verb} ${filesChanged} file${filesChanged === 1 ? '' : 's'}`);
+ log.info(
+ ` ${verb} ${filesChanged} file${filesChanged === 1 ? '' : 's'}`,
+ );
}
}
}
@@ -322,5 +370,11 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
}
}
- return {totalFilesChanged, totalTransformsApplied, totalValidationBlocked, errors, skippedOptional};
+ return {
+ totalFilesChanged,
+ totalTransformsApplied,
+ totalValidationBlocked,
+ errors,
+ skippedOptional,
+ };
}
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/__tests__/migrate-theme-selectors-to-data-attrs.test.mjs b/packages/cli/src/codemods/transforms/v0.0.15/__tests__/migrate-theme-selectors-to-data-attrs.test.mjs
new file mode 100644
index 0000000000..e48d9ff5c0
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.15/__tests__/migrate-theme-selectors-to-data-attrs.test.mjs
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, test} from 'vitest';
+import transform from '../migrate-theme-selectors-to-data-attrs.mjs';
+
+function apply(source) {
+ return transform({source}, {}) ?? '';
+}
+
+describe('migrate-theme-selectors-to-data-attrs', () => {
+ test('converts button variant and size selectors', () => {
+ expect(apply('.xds-button.primary.sm:hover { color: red; }')).toBe(
+ '.xds-button[data-variant="primary"][data-size="sm"]:hover { color: red; }',
+ );
+ });
+
+ test('converts heading level and color selectors', () => {
+ expect(apply('.xds-heading.level-2.secondary { margin: 0; }')).toBe(
+ '.xds-heading[data-level="2"][data-color="secondary"] { margin: 0; }',
+ );
+ });
+
+ test('converts text type and color selectors', () => {
+ expect(apply('.xds-text.body.primary { color: black; }')).toBe(
+ '.xds-text[data-type="body"][data-color="primary"] { color: black; }',
+ );
+ });
+
+ test('converts selectors inside TS string literals', () => {
+ expect(
+ apply("const selector = '.xds-card.muted > .xds-button.ghost';"),
+ ).toBe(
+ 'const selector = \'.xds-card[data-variant="muted"] > .xds-button[data-variant="ghost"]\';',
+ );
+ });
+
+ test('leaves unknown components unchanged', () => {
+ expect(apply('.xds-made-up.primary { color: red; }')).toBe('');
+ });
+
+ test('leaves selectors with additional xds classes unchanged', () => {
+ expect(apply('.xds-table-row.xds-row-selected { color: red; }')).toBe('');
+ });
+});
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs b/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
index ebbc312982..a306468f96 100644
--- a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
+++ b/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
@@ -26,6 +26,10 @@ import migrateItemChildrenToEndContent, {
meta as migrateItemChildrenToEndContentMeta,
} from './migrate-item-children-to-endcontent.mjs';
+import migrateThemeSelectorsToDataAttrs, {
+ meta as migrateThemeSelectorsToDataAttrsMeta,
+} from './migrate-theme-selectors-to-data-attrs.mjs';
+
export default [
{
name: 'rename-date-picker-to-input',
@@ -52,4 +56,10 @@ export default [
transform: migrateItemChildrenToEndContent,
meta: migrateItemChildrenToEndContentMeta,
},
+ {
+ name: 'migrate-theme-selectors-to-data-attrs',
+ transform: migrateThemeSelectorsToDataAttrs,
+ meta: migrateThemeSelectorsToDataAttrsMeta,
+ optional: true,
+ },
];
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs b/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs
new file mode 100644
index 0000000000..282f1fc73a
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs
@@ -0,0 +1,235 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: migrate legacy bare XDS theme selectors to data attributes.
+ *
+ * Converts selectors like:
+ * .xds-button.primary.sm:hover
+ * to:
+ * .xds-button[data-variant="primary"][data-size="sm"]:hover
+ *
+ * The transform is intentionally conservative: it only rewrites component/value
+ * pairs where the prop/state axis is known. Unknown component classes and
+ * ambiguous values are left unchanged.
+ */
+
+export const meta = {
+ title: 'Migrate XDS theme selectors to data attributes',
+ description:
+ 'Rewrites legacy bare prop/state class selectors such as `.xds-button.primary` ' +
+ 'to preferred data-attribute selectors such as `.xds-button[data-variant="primary"]`.',
+ fileExtensions: [
+ '.css',
+ '.scss',
+ '.sass',
+ '.less',
+ '.ts',
+ '.tsx',
+ '.js',
+ '.jsx',
+ '.mjs',
+ '.cjs',
+ ],
+};
+
+const COLOR_VALUES = new Set([
+ 'primary',
+ 'secondary',
+ 'disabled',
+ 'placeholder',
+ 'active',
+ 'accent',
+ 'success',
+ 'warning',
+ 'error',
+ 'info',
+ 'neutral',
+ 'red',
+ 'orange',
+ 'yellow',
+ 'green',
+ 'teal',
+ 'cyan',
+ 'blue',
+ 'purple',
+ 'pink',
+ 'gray',
+]);
+
+const STATE_VALUES = new Set([
+ 'active',
+ 'checked',
+ 'disabled',
+ 'expanded',
+ 'focused',
+ 'hidden',
+ 'indeterminate',
+ 'invalid',
+ 'open',
+ 'pressed',
+ 'selected',
+ 'today',
+ 'visible',
+]);
+
+const STATUS_VALUES = new Set([
+ 'info',
+ 'neutral',
+ 'success',
+ 'warning',
+ 'error',
+]);
+const SIZE_VALUES = new Set([
+ 'xs',
+ 'sm',
+ 'md',
+ 'lg',
+ 'xl',
+ 'small',
+ 'medium',
+ 'large',
+]);
+const TEXT_TYPES = new Set([
+ 'body',
+ 'large',
+ 'label',
+ 'code',
+ 'supporting',
+ 'display-1',
+ 'display-2',
+ 'display-3',
+]);
+const APP_SHELL_VARIANTS = new Set(['wash', 'surface', 'section', 'elevated']);
+const SECTION_VARIANTS = new Set(['section', 'transparent', 'muted']);
+const DIVIDER_VARIANTS = new Set(['subtle', 'strong']);
+const ORIENTATIONS = new Set(['horizontal', 'vertical']);
+
+function attr(name, value) {
+ return `[data-${name}="${value}"]`;
+}
+
+function valueToAttr(component, value) {
+ // Numeric-prefixed classes emitted as prop-value (level-2, gap-4, cols-3).
+ let match = value.match(/^level-(\d+)$/);
+ if (match) return attr('level', match[1]);
+
+ match = value.match(/^gap-(\d+(?:-\d+)?)$/);
+ if (match) return attr('gap', match[1].replace('-', '.'));
+
+ match = value.match(/^(?:columns|cols)-(\d+)$/);
+ if (match) return attr('columns', match[1]);
+
+ switch (component) {
+ case 'xds-button':
+ if (SIZE_VALUES.has(value)) return attr('size', value);
+ // Button variants are extensible, so unknown non-size values are most
+ // likely custom variants.
+ return attr('variant', value);
+
+ case 'xds-badge':
+ case 'xds-statusdot':
+ case 'xds-avatar-status-dot':
+ case 'xds-card':
+ case 'xds-clickable-card':
+ return attr('variant', value);
+
+ case 'xds-app-shell':
+ case 'xds-app-shell-header':
+ case 'xds-app-shell-sidenav':
+ if (APP_SHELL_VARIANTS.has(value)) return attr('variant', value);
+ return null;
+
+ case 'xds-section':
+ if (SECTION_VARIANTS.has(value)) return attr('variant', value);
+ return null;
+
+ case 'xds-heading':
+ if (TEXT_TYPES.has(value)) return attr('type', value);
+ if (COLOR_VALUES.has(value)) return attr('color', value);
+ return null;
+
+ case 'xds-text':
+ if (TEXT_TYPES.has(value)) return attr('type', value);
+ if (COLOR_VALUES.has(value)) return attr('color', value);
+ return null;
+
+ case 'xds-link':
+ if (COLOR_VALUES.has(value)) return attr('color', value);
+ return null;
+
+ case 'xds-icon':
+ if (SIZE_VALUES.has(value)) return attr('size', value);
+ if (COLOR_VALUES.has(value)) return attr('color', value);
+ return null;
+
+ case 'xds-divider':
+ if (DIVIDER_VARIANTS.has(value)) return attr('variant', value);
+ if (ORIENTATIONS.has(value)) return attr('orientation', value);
+ return null;
+
+ case 'xds-stack':
+ if (ORIENTATIONS.has(value)) return attr('direction', value);
+ if (value === 'wrap' || value === 'nowrap') return attr('wrap', value);
+ return null;
+
+ case 'xds-grid':
+ if (['start', 'center', 'end', 'stretch'].includes(value))
+ return attr('align', value);
+ return null;
+
+ case 'xds-banner':
+ case 'xds-banner-icon':
+ case 'xds-banner-content':
+ if (STATUS_VALUES.has(value)) return attr('status', value);
+ if (['card', 'inline'].includes(value)) return attr('container', value);
+ return null;
+
+ case 'xds-spinner':
+ if (SIZE_VALUES.has(value)) return attr('size', value);
+ if (['default', 'onMedia', 'subtle'].includes(value))
+ return attr('shade', value);
+ return null;
+
+ case 'xds-progressbar':
+ case 'xds-progressbar-fill':
+ if (STATUS_VALUES.has(value) || value === 'accent')
+ return attr('variant', value);
+ return null;
+
+ case 'xds-tab':
+ case 'xds-side-nav-item':
+ case 'xds-segmented-control-item':
+ case 'xds-switch':
+ if (STATE_VALUES.has(value)) return attr(value, value);
+ return null;
+
+ default:
+ if (STATE_VALUES.has(value)) return attr(value, value);
+ return null;
+ }
+}
+
+const SELECTOR_RE = /\.((?:xds-[a-z0-9-]+))(\.(?:-?[_a-zA-Z][_a-zA-Z0-9-]*))+/g;
+
+export function migrateThemeSelectors(source) {
+ return source.replace(SELECTOR_RE, (full, component) => {
+ const classChain = full.slice(component.length + 1);
+ const values = classChain.split('.').filter(Boolean);
+
+ const attrs = [];
+ for (const value of values) {
+ // Preserve additional xds-* classes; those are not bare variant/state values.
+ if (value.startsWith('xds-')) return full;
+ const converted = valueToAttr(component, value);
+ if (!converted) return full;
+ attrs.push(converted);
+ }
+
+ return `.${component}${attrs.join('')}`;
+ });
+}
+
+export default function transformer(file) {
+ const result = migrateThemeSelectors(file.source);
+ return result === file.source ? undefined : result;
+}