Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ src/utils/**/*.md
packages/plugin/skills/react-simplikit/SKILL.md
packages/plugin/skills/react-simplikit/references
packages/codemod/test/__fixtures__
codemods/*/tests
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
React utility hooks/components library. Two published packages and an agent plugin:

- `react-simplikit` (`packages/react-simplikit`) — React hooks, components and utils
- `react-simplikit-codemod` (`packages/codemod`) — bin-only CLI that runs upgrade codemods on consumer codebases (`mobile-to-root` today)
- `react-simplikit-codemod` (`packages/codemod`) — bin-only CLI that runs upgrade codemods on consumer codebases (`mobile-to-root` today). It is being retired: every codemod moves to a Codemod (jssg) workflow under the root `codemods/` workspace, which ships on npm as `@react-simplikit/codemod` and is tested by fixtures with `yarn test:codemod`. Do not add transforms to `packages/codemod`
- `packages/plugin` — agent skills for Claude Code, Codex and skills.sh. No `package.json`, so it is neither a workspace nor on npm. `yarn skill:gen` regenerates `skills/react-simplikit` from the public exports and `yarn test:skill` fails CI when the committed copy drifts; `skills/react-simplikit-codemod` is hand-written

## Architecture
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
React utility hooks/components library. Two published packages and an agent plugin:

- `react-simplikit` (`packages/react-simplikit`) — React hooks, components and utils
- `react-simplikit-codemod` (`packages/codemod`) — bin-only CLI that runs upgrade codemods on consumer codebases (`mobile-to-root` today). The rules below describe the library; the exceptions that apply to the CLI are called out where they differ
- `react-simplikit-codemod` (`packages/codemod`) — bin-only CLI that runs upgrade codemods on consumer codebases (`mobile-to-root` today). It is being retired: every codemod moves to a Codemod (jssg) workflow under the root `codemods/` workspace, which ships on npm as `@react-simplikit/codemod` and runs them with the Codemod CLI (`v0-to-v1` today, `mobile-to-root` next). Do not add transforms to `packages/codemod`; see `codemods/README.md`. The rules below describe the library; the exceptions that apply to the CLI are called out where they differ
- `packages/plugin` — agent skills for Claude Code (the root `.claude-plugin/marketplace.json` points here), Codex and skills.sh. No `package.json`, so it is neither a workspace nor on npm. `yarn skill:gen` regenerates `skills/react-simplikit` from the public exports and `yarn test:skill` fails CI when the committed copy drifts; `skills/react-simplikit-codemod` is hand-written

## Development Quick Start
Expand Down Expand Up @@ -101,7 +101,7 @@ Never initialize state with browser API calls (causes hydration mismatch).

## Testing

- **100% coverage mandatory** — Enforced by Vitest coverage threshold. The codemod excludes two files: `src/cli.ts`, because its e2e suite runs the built bin in a child process where v8 cannot attribute the lines back, and `src/constants.ts`, which holds no executable statements. An excluded file still needs its behaviour covered somewhere — `cli.ts`'s exit codes and `--debug` output are asserted by the e2e suite
- **100% coverage mandatory** — Enforced by Vitest coverage threshold. The codemod excludes two files: `src/cli.ts`, because its e2e suite runs the built bin in a child process where v8 cannot attribute the lines back, and `src/constants.ts`, which holds no executable statements. An excluded file still needs its behaviour covered somewhere — `cli.ts`'s exit codes and `--debug` output are asserted by the e2e suite. The jssg transforms under `codemods/` are outside v8 coverage; their `tests/` fixtures, run by `yarn test:codemod`, cover them instead
- **SSR tests required** — All hooks accessing browser APIs must have `.ssr.test.ts`
- **Test file name**: `<name>.test.ts`; older folders still use `<name>.spec.ts` — keep whichever the folder has
- **SSR pattern**:
Expand Down
58 changes: 58 additions & 0 deletions codemods/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Codemods

Each folder here is a [Codemod](https://docs.codemod.com) workflow of jssg (JavaScript ast-grep) transforms. ESLint ([eslint/codemods](https://github.com/eslint/codemods)) and Node.js ([nodejs/userland-migrations](https://github.com/nodejs/userland-migrations)) write their migrations the same way.

Every react-simplikit codemod lives here. The folder is one npm package, `@react-simplikit/codemod`: `cli.mjs` runs `<codemod>/workflow.yaml` with the Codemod CLI, so users run `npx @react-simplikit/codemod v0-to-v1`. It ships on npm rather than the Codemod registry because the registry only accepts a scope that a GitHub organization of the same name verifies, and there is no `react-simplikit` organization. The package stays `private` until its first release.

`mobile-to-root` predates this folder and still ships as the `react-simplikit-codemod` CLI in `packages/codemod`; it moves here next, and that package is retired after that.

## Layout

```
codemods/
├── package.json # @react-simplikit/codemod
├── cli.mjs # the bin: runs <codemod>/workflow.yaml
├── test.mjs # runs every transform against its fixtures
└── v0-to-v1/
├── workflow.yaml # one step per transform
├── README.md
├── scripts/<transform>.ts # one breaking change per script
├── utils/ # helpers shared by this codemod's scripts
└── tests/<language>/<transform>/<case>/
├── input.tsx # input.ts under tests/typescript
├── expected.tsx
└── metrics.json # only when the case reports something
```

## Adding a transform

1. Write `scripts/<transform>.ts`. Export a default `transform(root)` that returns the new source, or `null` when nothing changed.
2. Add fixtures under `tests/tsx/<transform>/`. Cover at least: the change itself, an aliased import, a same-named function from another module (left alone), a case that cannot be rewritten (left alone and reported), and already-migrated code (left alone). Cases only the `typescript` grammar can parse, such as `<T>value`, go under `tests/typescript/<transform>/` as `.ts` files.
3. Add the script to `workflow.yaml` twice, once with `language: tsx` and once with `language: typescript`. The `tsx` grammar handles JSX, the `typescript` grammar handles `<T>value` assertions, and neither parses both.
4. Run `node codemods/test.mjs`. It fails when `workflow.yaml` misses either step or points at a script that does not exist, and it dry-runs `cli.mjs` over the fixtures.

## Rules every transform follows

- **Only touch react-simplikit.** Resolve the local name through `utils/imports.ts` first, so an aliased import is handled and an unrelated function with the same name is not.
- **Leave what it cannot rewrite safely, and report it.** Increment the `manual-review` metric with `hook`, `reason`, `file: root.relativeFilename()` and `line`. Codemod prints it after the run, and the fixture's `metrics.json` pins it. Keep `useMetricAtom` in the script itself: Codemod finds metric names there, not in `utils/`.
- **Be idempotent.** A second run changes nothing.

## Testing

```bash
node codemods/test.mjs
```

`yarn test:codemod`, which CI runs, includes it.

Fixtures are compared byte for byte, so `.prettierignore` skips them. To regenerate `expected.tsx` and `metrics.json` after an intended change, run `npx codemod@1.18.6 jssg test -u -l <language> <script> <tests/language/transform>`, then review the diff.

The Codemod CLI is pinned in `test.mjs` and `cli.mjs` and run through `npx` instead of being a dependency: it ships a ~140MB native binary per platform, which the committed yarn cache cannot hold. Bump both pins together.

## Running a codemod from source

Commit or stash first; the CLI refuses to run on files Git does not track.

```bash
node codemods/cli.mjs v0-to-v1 -t path/to/project
```
27 changes: 27 additions & 0 deletions codemods/cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env node
// `npx @react-simplikit/codemod <codemod> [options]` runs `<codemod>/workflow.yaml` with the Codemod CLI on the
// current folder, passing the options through.
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

// Run through npx rather than a dependency, for the same reason as in test.mjs. Keep the two pins in sync.
const CODEMOD_CLI = 'codemod@1.18.6';

const [name, ...options] = process.argv.slice(2);
const workflow = fileURLToPath(new URL(`${name}/workflow.yaml`, import.meta.url));

if (name === undefined || name.startsWith('-') || !existsSync(workflow)) {
console.error('Usage: npx @react-simplikit/codemod v0-to-v1 [--dry-run] [-t <path>] [--no-interactive]');
process.exit(1);
}

// shortcut: Windows needs a shell to run npx, so an option containing a space breaks there; quote options if it matters.
const isWindows = process.platform === 'win32';
const { status } = spawnSync(
'npx',
['--yes', CODEMOD_CLI, 'workflow', 'run', '-w', isWindows ? `"${workflow}"` : workflow, ...options],
{ stdio: 'inherit', shell: isWindows }
);

process.exitCode = status ?? 1;
35 changes: 35 additions & 0 deletions codemods/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@react-simplikit/codemod",
"version": "0.0.0",
"private": true,
"description": "Codemods for upgrading react-simplikit, run with the Codemod CLI",
"type": "module",
"bin": {
"react-simplikit-codemod": "./cli.mjs"
},
"keywords": [
"react-simplikit",
"codemod",
"migration",
"upgrade"
],
"homepage": "https://react-simplikit.slash.page",
"bugs": "https://github.com/toss/react-simplikit/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/toss/react-simplikit.git",
"directory": "codemods"
},
"license": "MIT",
"files": [
"cli.mjs",
"*/README.md",
"*/workflow.yaml",
"*/scripts",
"*/utils"
],
"preferUnplugged": true,
"publishConfig": {
"access": "public"
}
}
78 changes: 78 additions & 0 deletions codemods/test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Runs every jssg transform against its fixtures: `<codemod>/scripts/<name>.ts` is tested with
// `<codemod>/tests/<language>/<name>/<case>/{input,expected}.*` (plus `metrics.json` when it reports),
// once per grammar `workflow.yaml` runs it with.
import { spawnSync } from 'node:child_process';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

// Pinned and run through npx rather than a devDependency: the CLI ships a ~140MB native binary per
// platform, which the committed yarn cache cannot hold (GitHub rejects files over 100MB).
const CODEMOD_CLI = 'codemod@1.18.6';

// `tsx` parses JSX and `typescript` parses `<T>value`; workflow.yaml runs every script with both.
const LANGUAGES = ['tsx', 'typescript'];

const root = path.dirname(fileURLToPath(import.meta.url));
let failed = false;

const fail = message => {
console.error(message);
failed = true;
};

for (const codemod of readdirSync(root, { withFileTypes: true })) {
if (!codemod.isDirectory()) {
continue;
}

const dir = path.join(root, codemod.name);
const workflow = readFileSync(path.join(dir, 'workflow.yaml'), 'utf8');

// `codemod workflow validate` passes a missing js_file, so check both directions here.
for (const [, jsFile] of workflow.matchAll(/js_file:\s*(\S+)/g)) {
if (!existsSync(path.join(dir, jsFile))) {
fail(`${codemod.name}/workflow.yaml points at ${jsFile}, which does not exist`);
}
}

for (const script of readdirSync(path.join(dir, 'scripts'))) {
const name = path.basename(script, '.ts');

for (const language of LANGUAGES) {
if (!new RegExp(`js_file: scripts/${script}\\s+language: ${language}\\b`).test(workflow)) {
fail(`${codemod.name}/workflow.yaml does not run scripts/${script} with language: ${language}`);
}
}

if (!existsSync(path.join(dir, 'tests', 'tsx', name))) {
fail(`${codemod.name}/scripts/${script} has no fixtures at ${codemod.name}/tests/tsx/${name}`);
}

for (const language of LANGUAGES) {
// npx runs from the package root, so every path is absolute.
const tests = path.join(dir, 'tests', language, name);

if (!existsSync(tests)) {
continue;
}

const args = ['--yes', CODEMOD_CLI, 'jssg', 'test', '-l', language, '--disable-analytics'];
const result = spawnSync('npx', [...args, path.join(dir, 'scripts', script), tests], { stdio: 'inherit' });

failed ||= result.status !== 0;
}
}
}

// The published entry point: a dry run over the fixtures has to find the workflow and report.
const cliArgs = ['v0-to-v1', '--dry-run', '--no-interactive', '--allow-dirty', '--disable-analytics'];
const cli = spawnSync(process.execPath, [path.join(root, 'cli.mjs'), ...cliArgs, '-t', path.join(root, 'v0-to-v1')], {
encoding: 'utf8',
});

if (cli.status !== 0 || !cli.stdout.includes('manual-review')) {
fail(`cli.mjs v0-to-v1 --dry-run failed:\n${cli.stdout}${cli.stderr}`);
}

process.exitCode = failed ? 1 : 0;
49 changes: 49 additions & 0 deletions codemods/v0-to-v1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# react-simplikit v0 to v1

Rewrites react-simplikit call sites for the breaking changes in [v1.0.0](https://github.com/toss/react-simplikit/issues/533).

> [!NOTE]
> Work in progress. Only the transforms listed below are implemented; the rest of the roadmap lands one transform at a time. It is not on npm yet: until then, run `node codemods/cli.mjs v0-to-v1 -t <your project>` from a clone of this repository.

## Usage

Commit or stash first, then run from your project root:

```bash
npx @react-simplikit/codemod v0-to-v1
```

Options after `v0-to-v1` go to the Codemod CLI. Useful ones:

- `--dry-run` shows what would change without writing files.
- `-t <path>` runs on another folder instead of the current one.
- `--no-interactive` skips prompts, for CI and coding agents.
- `--disable-analytics` (or `DISABLE_ANALYTICS=1`) turns off the CLI's usage analytics.

## What it changes

| Breaking change | Before | After |
| ------------------------------------------------------------------ | ----------------------------------------------- | ----------------------------------------------------- |
| [#535](https://github.com/toss/react-simplikit/issues/535) options | `useDoubleClick({ click, doubleClick, delay })` | `useDoubleClick({ onClick, onDoubleClick, delayMs })` |

Only calls that resolve to an import from `react-simplikit` are rewritten, including aliased (`import { useDoubleClick as useDbl }`) and namespace (`simplikit.useDoubleClick`) imports.

## What it reports instead of changing

Code it cannot rewrite safely is left as is and listed under `manual-review` in the metrics printed after the run, with its `file` and `line`:

| `reason` | Example |
| ---------------------- | ------------------------------------------------------------ |
| `options-not-inline` | `useDoubleClick(options)` |
| `options-spread` | `useDoubleClick({ ...base, doubleClick })` (the spread part) |
| `options-computed-key` | `useDoubleClick({ [key]: select })` |
| `require-not-followed` | `const { useDoubleClick } = require('react-simplikit')` |
| `re-exported` | `export { useDoubleClick } from 'react-simplikit'` |

A spread is reported on every run, because the codemod cannot tell whether it still holds an old key.

## After running

1. Review the diff, and run your formatter if the edits do not match your style.
2. Fix each `manual-review` entry by hand. Copy the list before closing the terminal; it is not saved anywhere.
3. Upgrade `react-simplikit` to v1.
18 changes: 18 additions & 0 deletions codemods/v0-to-v1/scripts/use-double-click-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { SgRoot } from 'codemod:ast-grep';
import type TSX from 'codemod:ast-grep/langs/tsx';
import { useMetricAtom } from 'codemod:metrics';

import { renameOptionKeys } from '../utils/options.ts';

const manualReview = useMetricAtom('manual-review');

// #535: useDoubleClick({ click, doubleClick, delay }) → useDoubleClick({ onClick, onDoubleClick, delayMs })
export default function transform(root: SgRoot<TSX>): string | null {
const edits = renameOptionKeys(root, manualReview, 'useDoubleClick', 0, {
click: 'onClick',
doubleClick: 'onDoubleClick',
delay: 'delayMs',
});

return edits.length === 0 ? null : root.root().commitEdits(edits);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useToggle, useDoubleClick as useDbl } from "react-simplikit";

function Card({ click, zoom }) {
const handleClick = useDbl({ onClick: click, onDoubleClick: zoom });
return <div onClick={handleClick} />;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useToggle, useDoubleClick as useDbl } from "react-simplikit";

function Card({ click, zoom }) {
const handleClick = useDbl({ click, doubleClick: zoom });
return <div onClick={handleClick} />;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useDoubleClick } from 'react-simplikit';

const handleClick = useDoubleClick({ onClick: select, onDoubleClick: zoom, delayMs: 300 });
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useDoubleClick } from 'react-simplikit';

const handleClick = useDoubleClick({ onClick: select, onDoubleClick: zoom, delayMs: 300 });
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useDoubleClick } from 'react-simplikit';

const handleClick = useDoubleClick({ [key]: select, onDoubleClick: zoom });
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useDoubleClick } from 'react-simplikit';

const handleClick = useDoubleClick({ [key]: select, doubleClick: zoom });
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"manual-review": [
{
"cardinality": {
"file": "input.tsx",
"hook": "useDoubleClick",
"line": "3",
"reason": "options-computed-key"
},
"count": 1
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { useDoubleClick } from 'react-simplikit';

const handleClick = useDoubleClick({
onClick() {
select();
},
onDoubleClick: zoom,
});
Loading
Loading