Skip to content

Commit 23790e5

Browse files
authored
feat(v3)!: data-state codemod, and change details on Dialog and Popover open (#2915)
1 parent 4a501fc commit 23790e5

26 files changed

Lines changed: 1196 additions & 76 deletions

‎.github/workflows/build.yaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ jobs:
4949
- name: Test (with coverage)
5050
run: pnpm --filter reka-ui test:coverage
5151

52+
- name: Test codemod
53+
run: pnpm --filter @reka-ui/codemod test
54+
5255
- name: Upload coverage report
5356
if: always()
5457
uses: actions/upload-artifact@v7

‎docs/content/docs/guides/migration-v3.md‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Parts that were already on `open` / `closed` or `checked` / `unchecked` / `indet
3434
The rewrites are mechanical. In Tailwind variants:
3535

3636
- `data-[state=on]:` → `data-[state=checked]:`, `data-[state=off]:` → `data-[state=unchecked]:`
37-
- `data-[state=active]:` → `data-[state=checked]:`, `data-[state=inactive]:` → `data-[state=unchecked]:` — for **Tabs and TagsInput only**. Stepper keeps `active` / `inactive` / `completed`, so leave selectors on `StepperItem` alone.
37+
- `data-[state=active]:` → `data-[state=checked]:`, `data-[state=inactive]:` → `data-[state=unchecked]:` — for **Tabs, TagsInput and Rating only**. Stepper keeps `active` / `inactive` / `completed`, so leave selectors on `StepperItem` alone.
3838
- `data-[state=visible]:` → `data-[state=open]:`, `data-[state=hidden]:` → `data-[state=closed]:`
3939
- `data-[state=expanded]:` → `data-[state=open]:`, `data-[state=collapsed]:` → `data-[state=closed]:`
4040
- `data-[state=delayed-open]:` → `data-[state=open]:data-[delayed]:`
@@ -43,7 +43,7 @@ The rewrites are mechanical. In Tailwind variants:
4343
In plain CSS the same rewrites apply to attribute selectors:
4444

4545
- `[data-state='on']` → `[data-state='checked']`, `[data-state='off']` → `[data-state='unchecked']`
46-
- `[data-state='active']` → `[data-state='checked']`, `[data-state='inactive']` → `[data-state='unchecked']` — Tabs and TagsInput only, not Stepper.
46+
- `[data-state='active']` → `[data-state='checked']`, `[data-state='inactive']` → `[data-state='unchecked']` — Tabs, TagsInput and Rating only, not Stepper.
4747
- `[data-state='visible']` → `[data-state='open']`, `[data-state='hidden']` → `[data-state='closed']`
4848
- `[data-state='expanded']` → `[data-state='open']`, `[data-state='collapsed']` → `[data-state='closed']`
4949
- `[data-state='delayed-open']` → `[data-state='open'][data-delayed]`
@@ -67,3 +67,39 @@ Because both values are now always emitted, any styles that relied on the attrib
6767
animation-name: slideDownAndFade;
6868
}
6969
```
70+
71+
### Codemod
72+
73+
The `@reka-ui/codemod` package automates the mechanical part: `npx @reka-ui/codemod data-state ./src` applies the mapping above to Tailwind variants and CSS attribute selectors in every `.vue`, `.css`, `.scss`, `.ts`, `.tsx`, `.js`, `.jsx`, `.html` and `.md` file under the given paths. It is deliberately conservative—`active` / `inactive` selectors are only rewritten in files that clearly belong to Tabs, TagsInput or Rating rather than Stepper or Splitter, and presence-only selectors such as `:not([data-state])` are never touched; both cases are left as they are and reported as a `file:line` warning for you to resolve by hand. Run it with `--dry-run` first to review the changes it would make before letting it write to disk.
74+
75+
## Change events carry details
76+
77+
`update:*` events on stateful roots now receive a second argument, a `ChangeEventDetails` object, and a cancellable `beforeUpdate:*` event fires before every change. `v-model` keeps working unchanged. The details tell you *why* the state changed (`details.reason`) and which native event caused it (`details.event`), and `details.cancel()` inside `beforeUpdate:*` keeps the current state.
78+
79+
Converted so far: `SwitchRoot`, `TabsRoot` (`modelValue`), `MenuRoot`, `ContextMenuRoot`, `DialogRoot`, `AlertDialogRoot`, `PopoverRoot`, `DatePickerRoot` and `DateRangePickerRoot` (`open`). The remaining families follow as they move to their headless composables.
80+
81+
Each family exports its reason union, for example `DialogOpenChangeReason` (`'trigger-press' | 'close-press' | 'escape-key' | 'outside-press' | 'focus-outside'`); every family also reports `'imperative-action'` for programmatic changes such as the slot's `close()`.
82+
83+
What to check in your code:
84+
85+
- Explicit `@update:open` / `@update:model-value` listeners receive an extra argument. Handlers that only read the first argument keep working; handlers typed with a single-parameter signature still type-check.
86+
- Wrappers that re-declare the emit types need the new tuple shape:
87+
88+
```ts
89+
'update:open': [value: boolean] // [!code --]
90+
'update:open': [value: boolean, details: ChangeEventDetails<DialogOpenChangeReason>] // [!code ++]
91+
```
92+
93+
- Uncontrolled components emit synchronously from the interaction instead of from a watcher on the next tick. Code that relied on the old timing may observe the difference.
94+
- A component that mounts uncontrolled and later receives a defined model value becomes controlled at that point and stays controlled, even if the model is later cleared to `undefined`.
95+
96+
```vue
97+
<DialogRoot
98+
v-model:open="open"
99+
@before-update:open="(value, details) => {
100+
// keep the dialog open while the form is dirty, but let the close button through
101+
if (!value && isDirty && details.reason !== 'close-press')
102+
details.cancel()
103+
}"
104+
/>
105+
```

‎eslint.config.mjs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ export default antfu(
5050
'unused-imports/no-unused-vars': 'off',
5151
},
5252
},
53+
{
54+
// The codemod package is dependency-free and runs its tests with `node --test`.
55+
files: ['packages/codemod/test/**/*.mjs'],
56+
rules: {
57+
'test/no-import-node-test': 'off',
58+
},
59+
},
5360
{
5461
files: ['**/package.json'],
5562
rules: {

‎packages/codemod/README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# @reka-ui/codemod
2+
3+
Best-effort codemods for migrating a codebase between Reka UI major versions.
4+
5+
```sh
6+
npx @reka-ui/codemod data-state ./src
7+
```
8+
9+
Run with `--dry-run` first to see what would change without writing anything, and use `--ext` to change the file extensions that are processed (default: `vue,css,scss,ts,tsx,js,jsx,html,md`). `node_modules`, `dist`, `.git`, `.nuxt`, `.output` and `coverage` are always skipped, including when a supplied path is or sits inside one of them.
10+
11+
```sh
12+
npx @reka-ui/codemod data-state ./src --dry-run
13+
npx @reka-ui/codemod data-state ./src ./docs --ext vue,css
14+
```
15+
16+
## `data-state`
17+
18+
Rewrites the v2 `data-state` values to the [v3 vocabulary](https://reka-ui.com/docs/guides/migration-v3) in Tailwind variants (`data-[state=…]:`, `group-data-[state=…]:`, `peer-data-[state=…]:`) and CSS attribute selectors (`[data-state=…]`, `[data-state='…']`, `[data-state="…"]`):
19+
20+
| v2 | v3 |
21+
| --- | --- |
22+
| `on` / `off` | `checked` / `unchecked` |
23+
| `visible` / `hidden` | `open` / `closed` |
24+
| `expanded` / `collapsed` | `open` / `closed` |
25+
| `instant-open` | `open` |
26+
| `delayed-open` | `open` + `data-delayed` (`data-[state=open]:data-[delayed]:` / `[data-state=open][data-delayed]`) |
27+
| `active` / `inactive` | `checked` / `unchecked` — only when the file is clearly about Tabs, TagsInput or Rating |
28+
29+
Everything else — `data-[side=…]`, `data-orientation`, values already on `open` / `closed` / `checked` / `unchecked` — is left as is, and running the codemod twice makes no further changes.
30+
31+
### Warnings
32+
33+
Two situations cannot be decided mechanically. The codemod leaves the source untouched and prints a `file:line: message` warning for each so you can finish the migration by hand:
34+
35+
- `ambiguous data-state "active": rewrite to "checked" for Tabs/TagsInput/Rating, keep for Stepper/Splitter` — Tabs, TagsInput and Rating moved from `active` / `inactive` to `checked` / `unchecked`, but Stepper still emits `active` / `inactive` / `completed` and the Splitter resize handle still emits `inactive`. The decision is made per file from the component names it mentions: a file that mentions `Tabs`, `TagsInput` or `Rating` (and not `Stepper` or `SplitterResizeHandle`) is rewritten, a file that only mentions `Stepper` or `SplitterResizeHandle` is kept, and a file that mentions both or neither gets this warning.
36+
- `"[data-state]" is now always present, so a presence-only selector matches every part; target the explicit value instead` — a bare `[data-state]` or `:not([data-state])` selector relied on the attribute being present or absent (for example a `RatingItemIndicator` that was active, or a non-collapsible `SplitterPanel`). In v3 both values are always emitted, so `[data-state]` matches every part and `:not([data-state])` matches nothing; target `checked` / `unchecked` or `open` / `closed` instead.
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
#!/usr/bin/env node
2+
import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
3+
import { extname, join, relative } from 'node:path'
4+
import process from 'node:process'
5+
import { transformDataState } from '../src/data-state.mjs'
6+
7+
const DEFAULT_EXTENSIONS = ['vue', 'css', 'scss', 'ts', 'tsx', 'js', 'jsx', 'html', 'md']
8+
const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', '.git', '.nuxt', '.output', 'coverage'])
9+
10+
const TRANSFORMS = {
11+
'data-state': transformDataState,
12+
}
13+
14+
const USAGE = `Usage: reka-ui-codemod <transform> [paths...] [--dry-run] [--ext vue,css,scss,ts,tsx,js,jsx,html,md]
15+
16+
Transforms:
17+
data-state Rewrite v2 data-state values (on/off, active/inactive, visible/hidden,
18+
expanded/collapsed, delayed-open/instant-open) to the v3 vocabulary
19+
in Tailwind variants and CSS attribute selectors.
20+
21+
Options:
22+
--dry-run Report what would change without writing any file.
23+
--ext Comma-separated list of file extensions to process.
24+
-h, --help Show this message.
25+
`
26+
27+
function print(message) {
28+
process.stdout.write(`${message}\n`)
29+
}
30+
31+
function parseArgs(argv) {
32+
const options = { transform: undefined, paths: [], dryRun: false, extensions: DEFAULT_EXTENSIONS, help: false }
33+
for (let i = 0; i < argv.length; i++) {
34+
const arg = argv[i]
35+
if (arg === '--dry-run') {
36+
options.dryRun = true
37+
}
38+
else if (arg === '-h' || arg === '--help') {
39+
options.help = true
40+
}
41+
else if (arg === '--ext') {
42+
options.extensions = parseExtensions(argv[++i])
43+
}
44+
else if (arg.startsWith('--ext=')) {
45+
options.extensions = parseExtensions(arg.slice('--ext='.length))
46+
}
47+
else if (arg.startsWith('-')) {
48+
throw new Error(`Unknown option: ${arg}`)
49+
}
50+
else if (options.transform === undefined) {
51+
options.transform = arg
52+
}
53+
else {
54+
options.paths.push(arg)
55+
}
56+
}
57+
if (options.paths.length === 0)
58+
options.paths.push('.')
59+
return options
60+
}
61+
62+
function parseExtensions(value = '') {
63+
const extensions = value
64+
.split(',')
65+
.map(ext => ext.trim().replace(/^\./, ''))
66+
.filter(Boolean)
67+
if (extensions.length === 0)
68+
throw new Error('--ext expects a comma-separated list of extensions')
69+
return extensions
70+
}
71+
72+
function* walk(path, extensions) {
73+
// A supplied root that is, or sits inside, an always-skipped directory is
74+
// skipped too, so the documented contract holds for explicit paths as well.
75+
if (path.split(/[\\/]/).some(segment => SKIPPED_DIRECTORIES.has(segment)))
76+
return
77+
const stats = statSync(path)
78+
if (stats.isFile()) {
79+
if (extensions.has(extname(path).slice(1)))
80+
yield path
81+
return
82+
}
83+
if (!stats.isDirectory())
84+
return
85+
const entries = readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
86+
for (const entry of entries) {
87+
if (entry.isDirectory()) {
88+
if (!SKIPPED_DIRECTORIES.has(entry.name))
89+
yield* walk(join(path, entry.name), extensions)
90+
}
91+
else if (entry.isFile() && extensions.has(extname(entry.name).slice(1))) {
92+
yield join(path, entry.name)
93+
}
94+
}
95+
}
96+
97+
function run(argv) {
98+
const options = parseArgs(argv)
99+
if (options.help || options.transform === undefined) {
100+
print(USAGE)
101+
return options.help ? 0 : 1
102+
}
103+
104+
const transform = TRANSFORMS[options.transform]
105+
if (!transform) {
106+
print(`Unknown transform "${options.transform}".\n`)
107+
print(USAGE)
108+
return 1
109+
}
110+
111+
const extensions = new Set(options.extensions)
112+
let changedFiles = 0
113+
let warningCount = 0
114+
115+
for (const root of options.paths) {
116+
for (const file of walk(root, extensions)) {
117+
const source = readFileSync(file, 'utf8')
118+
const { code, changed, warnings } = transform(source, { filename: file })
119+
const displayPath = relative(process.cwd(), file) || file
120+
121+
if (changed) {
122+
changedFiles++
123+
if (!options.dryRun)
124+
writeFileSync(file, code)
125+
print(`${options.dryRun ? 'would change' : 'changed'} ${displayPath}`)
126+
}
127+
for (const warning of warnings) {
128+
warningCount++
129+
print(`${displayPath}:${warning.line}: ${warning.message}`)
130+
}
131+
}
132+
}
133+
134+
const suffix = options.dryRun ? ' (dry run, nothing written)' : ''
135+
print(`${changedFiles} files changed, ${warningCount} warnings${suffix}`)
136+
return 0
137+
}
138+
139+
try {
140+
process.exitCode = run(process.argv.slice(2))
141+
}
142+
catch (error) {
143+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
144+
process.exitCode = 1
145+
}

‎packages/codemod/package.json‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"name": "@reka-ui/codemod",
3+
"type": "module",
4+
"version": "3.0.0-alpha.0",
5+
"description": "Codemods for migrating a codebase between Reka UI major versions.",
6+
"author": "UnoVue Contributors (https://github.com/unovue)",
7+
"license": "MIT",
8+
"funding": {
9+
"type": "github",
10+
"url": "https://github.com/sponsors/zernonia"
11+
},
12+
"homepage": "https://github.com/unovue/reka-ui",
13+
"repository": {
14+
"type": "git",
15+
"url": "git+https://github.com/unovue/reka-ui.git",
16+
"directory": "packages/codemod"
17+
},
18+
"bugs": {
19+
"url": "https://github.com/unovue/reka-ui/issues"
20+
},
21+
"keywords": [
22+
"reka-ui",
23+
"codemod",
24+
"migration",
25+
"vue"
26+
],
27+
"bin": {
28+
"reka-ui-codemod": "./bin/reka-ui-codemod.mjs"
29+
},
30+
"files": [
31+
"bin",
32+
"src"
33+
],
34+
"engines": {
35+
"node": ">=22"
36+
},
37+
"scripts": {
38+
"test": "node --test"
39+
}
40+
}

0 commit comments

Comments
 (0)