An open source design system that's fully customizable and agent ready
TypeScript
feat(core): rename Switch labelSpacing "default" to "hug", keep deprecated alias (#3881)
Jiun Shin12abceb805c2
diff --git a/.changeset/cli-switch-labelspacing-codemod.md b/.changeset/cli-switch-labelspacing-codemod.mdnew file mode 100644index 0000000000..995c30de1d--- /dev/null+++ b/.changeset/cli-switch-labelspacing-codemod.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] Add a v0.1.5 upgrade codemod that renames `labelSpacing="default"` to `labelSpacing="hug"` on Switch. (#2889)+@jiunshinndiff --git a/.changeset/switch-labelspacing-hug.md b/.changeset/switch-labelspacing-hug.mdnew file mode 100644index 0000000000..648374fef4--- /dev/null+++ b/.changeset/switch-labelspacing-hug.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Switch: rename the labelSpacing `"default"` value to `"hug"`; `"default"` keeps working as a deprecated alias. Run `astryx upgrade` to migrate call sites automatically. (#2889)+@jiunshinndiff --git a/apps/storybook/stories/Switch.stories.tsx b/apps/storybook/stories/Switch.stories.tsxindex d513a114da..704d0c04f0 100644--- a/apps/storybook/stories/Switch.stories.tsx+++ b/apps/storybook/stories/Switch.stories.tsx@@ -56,7 +56,7 @@ const meta: Meta<typeof Switch> = {},labelSpacing: {control: 'select',- options: ['default', 'spread'],+ options: ['hug', 'spread'],description: 'Spacing behavior between label and switch',},},diff --git a/packages/cli/src/codemods/__tests__/registry.test.mjs b/packages/cli/src/codemods/__tests__/registry.test.mjsindex 485f1dccb2..a4d3b54e87 100644--- a/packages/cli/src/codemods/__tests__/registry.test.mjs+++ b/packages/cli/src/codemods/__tests__/registry.test.mjs@@ -19,6 +19,7 @@ describe('registry', () => {'0.1.0','0.1.2','0.1.3',+ '0.1.5',]);});});diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjsindex ffc143751a..038be8b525 100644--- a/packages/cli/src/codemods/registry.mjs+++ b/packages/cli/src/codemods/registry.mjs@@ -20,6 +20,7 @@ const registry = new Map([['0.1.0', () => import('./transforms/v0.1.0/index.mjs')],['0.1.2', () => import('./transforms/v0.1.2/index.mjs')],['0.1.3', () => import('./transforms/v0.1.3/index.mjs')],+ ['0.1.5', () => import('./transforms/v0.1.5/index.mjs')],]);// Re-export from the shared utility so registry callers and other consumersdiff --git a/packages/cli/src/codemods/transforms/v0.1.5/__tests__/rename-switch-label-spacing-default-to-hug.test.mjs b/packages/cli/src/codemods/transforms/v0.1.5/__tests__/rename-switch-label-spacing-default-to-hug.test.mjsnew file mode 100644index 0000000000..02e3c0f7f1--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.5/__tests__/rename-switch-label-spacing-default-to-hug.test.mjs@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';++async function applyTransform(source) {+ const {default: transform} =+ await import('../rename-switch-label-spacing-default-to-hug.mjs');+ const jscodeshift = (await import('jscodeshift')).default;+ const j = jscodeshift.withParser('tsx');+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};+ const file = {source, path: 'test.tsx'};+ const result = transform(file, api);+ return result ?? source;+}++describe('rename-switch-label-spacing-default-to-hug', () => {+ it('renames Switch labelSpacing="default" to labelSpacing="hug"', async () => {+ const input = `<Switch label="Notify" value={on} labelSpacing="default" />`;+ const output = await applyTransform(input);+ expect(output).toContain("'hug'");+ expect(output).not.toContain('default');+ });++ it("renames expression-container labelSpacing={'default'}", async () => {+ const input = `<Switch label="Notify" value={on} labelSpacing={'default'} />`;+ const output = await applyTransform(input);+ expect(output).toContain("'hug'");+ expect(output).not.toContain("'default'");+ });++ it('renames default inside a ternary labelSpacing expression', async () => {+ const input = `<Switch label="Notify" value={on} labelSpacing={isRow ? 'spread' : 'default'} />`;+ const output = await applyTransform(input);+ expect(output).toContain("'hug'");+ expect(output).toContain("'spread'");+ expect(output).not.toContain("'default'");+ });++ it('does not change labelSpacing="spread"', async () => {+ const input = `<Switch label="Notify" value={on} labelSpacing="spread" />`;+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('does not touch labelSpacing="default" on non-Switch components', async () => {+ const input = `<LegacyToggle labelSpacing="default" />`;+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('does not touch other props with a "default" value on Switch', async () => {+ const input = `<Switch label="Notify" value={on} data-variant="default" />`;+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('does not touch unrelated "default" string literals', async () => {+ const input = `const theme = {mode: 'default', label: 'Default Mode'};`;+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('renames object labelSpacing prop in files importing Switch', async () => {+ const input = `import {Switch} from '@astryxdesign/core/Switch';+const cfg = {labelSpacing: 'default'};`;+ const output = await applyTransform(input);+ expect(output).toContain("labelSpacing: 'hug'");+ expect(output).not.toContain("'default'");+ });++ it("renames labelSpacing: 'default' as const in files importing Switch", async () => {+ const input = `import {Switch} from '@astryxdesign/core/Switch';+const ROWS = [{labelSpacing: 'default' as const, label: 'Adjacent'}];`;+ const output = await applyTransform(input);+ expect(output).toContain("'hug' as const");+ expect(output).not.toContain("'default'");+ });++ it('does not rename object labelSpacing prop when Switch is not imported', async () => {+ const input = `const cfg = {labelSpacing: 'default'};`;+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('renames Storybook argTypes options in files importing Switch', async () => {+ const input = `import {Switch} from '@astryxdesign/core/Switch';+const meta = {argTypes: {labelSpacing: {control: 'select', options: ['default', 'spread']}}};`;+ const output = await applyTransform(input);+ expect(output).toContain("'hug'");+ expect(output).toContain("'spread'");+ expect(output).not.toContain("'default'");+ });+});diff --git a/packages/cli/src/codemods/transforms/v0.1.5/index.mjs b/packages/cli/src/codemods/transforms/v0.1.5/index.mjsnew file mode 100644index 0000000000..43dab2a530--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.5/index.mjs@@ -0,0 +1,19 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file v0.1.5 transform manifest+ *+ * Lists all codemods for the v0.1.5 release in the order they should run.+ */++import renameSwitchLabelSpacingDefaultToHug, {+ meta as renameSwitchLabelSpacingDefaultToHugMeta,+} from './rename-switch-label-spacing-default-to-hug.mjs';++export default [+ {+ name: 'rename-switch-label-spacing-default-to-hug',+ transform: renameSwitchLabelSpacingDefaultToHug,+ meta: renameSwitchLabelSpacingDefaultToHugMeta,+ },+];diff --git a/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs b/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjsnew file mode 100644index 0000000000..3a2241bfc1--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs@@ -0,0 +1,140 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Codemod: Rename Switch labelSpacing "default" to "hug"+ * @see https://github.com/facebook/astryx/issues/2889+ *+ * The `labelSpacing="default"` value is renamed to `labelSpacing="hug"` so+ * the name describes the behavior (label and switch hug each other), matching+ * the behavioral register of the sibling `spread` value and the existing+ * `hug`/`fill` layout vocabulary on TabList and SegmentedControl. The old+ * `default` value keeps working as a deprecated alias, so this codemod is a+ * cleanup, not a build fix.+ *+ * Transforms (scoped to Switch):+ * - <Switch labelSpacing="default" /> → <Switch labelSpacing="hug" />+ * - <Switch labelSpacing={'default'} /> → <Switch labelSpacing={'hug'} />+ * - <Switch labelSpacing={cond ? 'default' : x}> → <Switch labelSpacing={cond ? 'hug' : x}>+ * - Storybook argTypes: labelSpacing: { options: [..., 'default', ...] }+ * → replaces 'default' with 'hug' (files importing Switch)+ * - Object properties: { labelSpacing: 'default' } / { labelSpacing: 'default' as const }+ * → { labelSpacing: 'hug' } (files importing Switch)+ *+ * The transform deliberately does NOT touch bare `'default'` strings that are+ * not a `labelSpacing` value (an extremely common string otherwise), so it is+ * safe to run across an entire codebase.+ */++export const meta = {+ title: 'Rename Switch labelSpacing "default" to "hug"',+ description:+ 'Renames the `labelSpacing="default"` value to `labelSpacing="hug"` on ' ++ 'Switch. The old value keeps working as a deprecated alias. Also updates ' ++ 'Storybook labelSpacing argTypes options and object-literal `labelSpacing` ' ++ 'props in files that import Switch.',+ pr: '#2889',+};++const OLD_VALUE = 'default';+const NEW_VALUE = 'hug';++/** Prop whose value is being renamed. */+const TARGET_PROP = 'labelSpacing';++/** Components whose `labelSpacing` prop accepts a SwitchLabelSpacing value. */+const TARGET_COMPONENTS = new Set(['Switch']);++export default function transformer(file, api) {+ const j = api.jscodeshift;+ const root = j(file.source);+ let hasChanges = false;++ /** Rewrite a string-literal node when it equals the old value. */+ function renameStringLiteral(node) {+ if (!node) return false;+ if (+ (node.type === 'StringLiteral' || node.type === 'Literal') &&+ node.value === OLD_VALUE+ ) {+ node.value = NEW_VALUE;+ if (node.raw) node.raw = `'${NEW_VALUE}'`;+ return true;+ }+ return false;+ }++ /** Recursively rewrite the old value inside ternary/logical expressions. */+ function renameInExpression(node) {+ if (!node) return false;+ let changed = false;+ if (node.type === 'StringLiteral' || node.type === 'Literal') {+ changed = renameStringLiteral(node) || changed;+ } else if (node.type === 'ConditionalExpression') {+ changed = renameInExpression(node.consequent) || changed;+ changed = renameInExpression(node.alternate) || changed;+ } else if (node.type === 'LogicalExpression') {+ changed = renameInExpression(node.left) || changed;+ changed = renameInExpression(node.right) || changed;+ } else if (node.type === 'TSAsExpression') {+ // `'default' as const` → rewrite the inner expression+ changed = renameInExpression(node.expression) || changed;+ }+ return changed;+ }++ // --- 1. JSX attribute: labelSpacing="default" / labelSpacing={'default'} on Switch ---+ root.find(j.JSXOpeningElement).forEach(path => {+ const name = path.node.name;+ const componentName = name.type === 'JSXIdentifier' ? name.name : null;+ if (!componentName || !TARGET_COMPONENTS.has(componentName)) return;++ path.node.attributes.forEach(attr => {+ if (attr.type !== 'JSXAttribute') return;+ if (!attr.name || attr.name.name !== TARGET_PROP) return;++ const value = attr.value;+ if (!value) return;++ if (value.type === 'StringLiteral' || value.type === 'Literal') {+ if (renameStringLiteral(value)) hasChanges = true;+ } else if (value.type === 'JSXExpressionContainer') {+ if (renameInExpression(value.expression)) hasChanges = true;+ }+ });+ });++ // Object-property / argTypes transforms only run in files that use a target+ // component — keeps unrelated `{ labelSpacing: 'default' }` strings safe.+ const importsTarget =+ root+ .find(j.ImportSpecifier)+ .filter(p => TARGET_COMPONENTS.has(p.node.imported?.name))+ .size() > 0;++ if (importsTarget) {+ const PropertyType = j.ObjectProperty ?? j.Property;++ // --- 2. Object property: { labelSpacing: 'default' } / 'default' as const ---+ root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach(path => {+ if (renameInExpression(path.node.value)) hasChanges = true;+ });++ // --- 3. Storybook argTypes: labelSpacing: { options: [..., 'default', ...] } ---+ root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach(path => {+ const value = path.node.value;+ if (!value || value.type !== 'ObjectExpression') return;++ const optionsProp = value.properties.find(+ p => p.key && (p.key.name === 'options' || p.key.value === 'options'),+ );+ if (optionsProp && optionsProp.value.type === 'ArrayExpression') {+ optionsProp.value.elements.forEach(el => {+ if (renameStringLiteral(el)) hasChanges = true;+ });+ }+ });+ }++ if (!hasChanges) return undefined;+ return root.toSource({quote: 'single'});+}diff --git a/packages/core/src/Switch/Switch.doc.mjs b/packages/core/src/Switch/Switch.doc.mjsindex bb5a143c28..3ff5649ec1 100644--- a/packages/core/src/Switch/Switch.doc.mjs+++ b/packages/core/src/Switch/Switch.doc.mjs@@ -124,10 +124,10 @@ export const docs = {},{name: 'labelSpacing',- type: "'default' | 'spread'",+ type: "'hug' | 'spread'",description:- 'Spacing behavior between label and switch. "spread" pushes them to opposite ends of the container (full width).',- default: "'default'",+ 'Spacing behavior between label and switch. "hug" places them next to each other; "spread" pushes them to opposite ends of the container (full width). "default" is a deprecated alias for "hug".',+ default: "'hug'",},],theming: {@@ -270,10 +270,10 @@ export const docsZh = {},{name: 'labelSpacing',- type: "'default' | 'spread'",+ type: "'hug' | 'spread'",description:- '标签和开关之间的间距行为。"spread" 将它们推到容器的两端(全宽)。',- default: "'default'",+ '标签和开关之间的间距行为。"hug" 将它们并排放置;"spread" 将它们推到容器的两端(全宽)。"default" 是 "hug" 的已弃用别名。',+ default: "'hug'",},],theming: {@@ -329,6 +329,6 @@ export const docsDense = {labelIcon: 'Icon before label text.',labelTooltip: 'Tooltip text in info icon at label end.',labelPosition: 'Which side label appears; "start" places before switch.',- labelSpacing: 'Spacing behavior; "spread" pushes to opposite ends (full width).',+ labelSpacing: 'Spacing behavior; "hug" places next to each other, "spread" pushes to opposite ends (full width). "default" is deprecated alias for "hug".',},};\ No newline at end of filediff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsxindex cd52c92f45..61ea5246fc 100644--- a/packages/core/src/Switch/Switch.test.tsx+++ b/packages/core/src/Switch/Switch.test.tsx@@ -470,11 +470,84 @@ describe('Switch', () => {expect(screen.getByRole('switch')).toBeDisabled();});});+ describe('labelSpacing', () => {+ const getField = (container: HTMLElement) =>+ container.querySelector<HTMLElement>('.astryx-switch-field')!;++ it('omits the data attribute for the default hug spacing', () => {+ const {container} = render(+ <Switch label="Notify" value={false} onChange={() => {}} />,+ );+ expect(getField(container)).not.toHaveAttribute('data-label-spacing');+ });++ it('reflects spread spacing as a data attribute and variant class', () => {+ const {container} = render(+ <Switch+ label="Notify"+ value={false}+ onChange={() => {}}+ labelSpacing="spread"+ />,+ );+ expect(getField(container)).toHaveAttribute(+ 'data-label-spacing',+ 'spread',+ );+ expect(getField(container).className).toContain('spread');+ });++ it('renders explicit hug the same as the default', () => {+ const {container: implicit} = render(+ <Switch label="Notify" value={false} onChange={() => {}} />,+ );+ const {container: explicit} = render(+ <Switch+ label="Notify"+ value={false}+ onChange={() => {}}+ labelSpacing="hug"+ />,+ );+ expect(getField(explicit)).not.toHaveAttribute('data-label-spacing');+ expect(getField(explicit).className).toBe(getField(implicit).className);+ });++ it("treats the deprecated 'default' value as an alias for hug", () => {+ const {container: hug} = render(+ <Switch+ label="Notify"+ value={false}+ onChange={() => {}}+ labelSpacing="hug"+ />,+ );+ const {container: deprecated} = render(+ <Switch+ label="Notify"+ value={false}+ onChange={() => {}}+ labelSpacing="default"+ />,+ );+ expect(getField(deprecated)).not.toHaveAttribute('data-label-spacing');+ expect(getField(deprecated).className).toBe(getField(hug).className);+ // The switch row keeps the hug layout, not the spread justification.+ expect(getField(deprecated).firstElementChild?.className).toBe(+ getField(hug).firstElementChild?.className,+ );+ });+ });describe('form participation', () => {it('submits under htmlName when on', () => {const {container} = render(<form>- <Switch label="Notify" htmlName="notify" value={true} onChange={() => {}} />+ <Switch+ label="Notify"+ htmlName="notify"+ value={true}+ onChange={() => {}}+ /></form>,);const data = new FormData(container.querySelector('form')!);@@ -494,13 +567,20 @@ describe('Switch', () => {/></form>,);- expect([...new FormData(container.querySelector('form')!).keys()]).toEqual([]);+ expect([+ ...new FormData(container.querySelector('form')!).keys(),+ ]).toEqual([]);});it('submits nothing when off or when htmlName is omitted', () => {const {container} = render(<form>- <Switch label="Off" htmlName="off" value={false} onChange={() => {}} />+ <Switch+ label="Off"+ htmlName="off"+ value={false}+ onChange={() => {}}+ /><Switch label="Unnamed" value={true} onChange={() => {}} /></form>,);diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex 42de1457df..c5aac725c2 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -185,7 +185,11 @@ const styles = stylex.create({export type SwitchLabelPosition = 'start' | 'end';-export type SwitchLabelSpacing = 'default' | 'spread';+export type SwitchLabelSpacing =+ | 'hug'+ | 'spread'+ /** @deprecated Use `'hug'` instead. */+ | 'default';export interface SwitchProps extends Omit<BaseProps, 'onChange'> {/** Ref forwarded to the root element */@@ -297,9 +301,11 @@ export interface SwitchProps extends Omit<BaseProps, 'onChange'> {labelPosition?: SwitchLabelPosition;/*** Spacing behavior between label and switch.- * - 'default': Label and switch are positioned next to each other+ * - 'hug': Label and switch are positioned next to each other* - 'spread': Label and switch are pushed to opposite ends- * @default 'default'+ *+ * 'default' is a deprecated alias for 'hug'.+ * @default 'hug'*/labelSpacing?: SwitchLabelSpacing;/**@@ -350,7 +356,7 @@ export function Switch({labelIcon,labelTooltip,labelPosition = 'end',- labelSpacing = 'default',+ labelSpacing = 'hug',status,width,xstyle,@@ -368,6 +374,10 @@ export function Switch({const isOn = optimisticValue === true;+ // 'default' is a deprecated alias for 'hug' (#2889).+ const resolvedLabelSpacing: SwitchLabelSpacing =+ labelSpacing === 'default' ? 'hug' : labelSpacing;+// Disabled-reason tooltip. Disabled controls swallow pointer events, so the// tooltip listeners attach to the switch row (which already exists) and the// native checkbox stays perceivable via aria-disabled instead of the disabled@@ -487,7 +497,8 @@ export function Switch({{...mergeProps(themeProps('switch-field', {labelPosition: labelPosition !== 'end' ? labelPosition : undefined,- labelSpacing: labelSpacing !== 'default' ? labelSpacing : undefined,+ labelSpacing:+ resolvedLabelSpacing !== 'hug' ? resolvedLabelSpacing : undefined,}),stylex.props(width != null && dynamicWidthStyles.width(width), xstyle),className,@@ -505,7 +516,7 @@ export function Switch({}}{...stylex.props(styles.container,- labelSpacing === 'spread' && styles.containerSpread,+ resolvedLabelSpacing === 'spread' && styles.containerSpread,!isDisabled && switchScope,)}>{' '}