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
37 changes: 27 additions & 10 deletions codemods/v0-to-v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,40 @@ Options after `v0-to-v1` go to the Codemod CLI. Useful ones:

## 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 })` |
| Breaking change | Before | After |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| [#535](https://github.com/toss/react-simplikit/issues/535) options | `useDoubleClick({ click, doubleClick, delay })` | `useDoubleClick({ onClick, onDoubleClick, delayMs })` |
| [#536](https://github.com/toss/react-simplikit/issues/536) time options | `useDebouncedCallback({ timeThreshold })` | `useDebouncedCallback({ debounceMs })` |
| | `useThrottledCallback({ timeThreshold })` | `useThrottledCallback({ throttleMs })` |
| | `useImpressionRef({ timeThreshold })`, `<ImpressionArea timeThreshold>` | `useImpressionRef({ timeThresholdMs })`, `<ImpressionArea timeThresholdMs>` |
| | `useLongPress(fn, { delay })` | `useLongPress(fn, { delayMs })` |
| | `useAvoidKeyboard({ transitionDuration })` | `useAvoidKeyboard({ transitionDurationMs })` |
| [#527](https://github.com/toss/react-simplikit/issues/527) timer hooks | `useInterval(fn, 1000)`, `useInterval(fn, { delay: 1000 })` | `useInterval({ onTick: fn, delayMs: 1000 })` |
| | `useTimeout(fn, 1000)` | `useTimeout({ onTimeout: fn, delayMs: 1000 })` |
| [#534](https://github.com/toss/react-simplikit/issues/534) throttle edges | `useThrottle(fn, 100, { edges: ['leading'] })` | `useThrottle(fn, 100, { leading: true, trailing: false })` |
| | `useThrottledCallback({ edges: ['trailing'] })` | `useThrottledCallback({ leading: false, trailing: true })` |
| [#528](https://github.com/toss/react-simplikit/issues/528) state hook returns | `const [open, setTrue, setFalse, toggle] = useBooleanState()` | `const [open, { setTrue, setFalse, toggle }] = useBooleanState()` |
| | `const [token, setToken, refresh] = useStorageState('token')` | `const [token, { setValue: setToken, refresh }] = useStorageState('token')` |
| | `const { count, increment } = useCounter(0)` | `const [count, { increment }] = useCounter(0)` |

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'` |
| `reason` | Example |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `options-not-inline` | `useDoubleClick(options)` |
| `options-spread` | `useDoubleClick({ ...base, doubleClick })` (the spread part) |
| `options-computed-key` | `useDoubleClick({ [key]: select })` |
| `props-spread` | `<ImpressionArea {...props} />` |
| `delay-not-inline` | `useInterval(fn, POLL_MS)` with `POLL_MS` imported from another file, which may be a number or v0's options object |
| `edges-not-inline` | `useThrottle(fn, 100, { edges })` |
| `return-not-destructured` | `const counter = useCounter(0)`, `<Child state={useBooleanState()} />` |
| `return-pattern-not-simple` | `const [open, ...actions] = useBooleanState()`, `const { count = 0 } = useCounter()` |
| `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.

Expand Down
124 changes: 124 additions & 0 deletions codemods/v0-to-v1/scripts/state-hook-returns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import type { Edit, SgNode, SgRoot } from 'codemod:ast-grep';
import type TSX from 'codemod:ast-grep/langs/tsx';
import { useMetricAtom } from 'codemod:metrics';

import { createReport, findCalls, type Report } from '../utils/options.ts';

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

// #528: state hooks return [value, actions].
// const [open, setTrue, setFalse, toggle] = useBooleanState() → const [open, { setTrue, setFalse, toggle }] = useBooleanState()
// const [token, setToken, refresh] = useStorageState('token') → const [token, { setValue: setToken, refresh }] = …
// const { count, increment } = useCounter(0) → const [count, { increment }] = useCounter(0)
const TUPLE_HOOKS: Array<[hook: string, actions: string[]]> = [
['useBooleanState', ['setTrue', 'setFalse', 'toggle']],
['useStorageState', ['setValue', 'refresh']],
];

export default function transform(root: SgRoot<TSX>): string | null {
const edits: Edit[] = [];

for (const [hook, actions] of TUPLE_HOOKS) {
const report = createReport(root, manualReview, hook);

for (const pattern of destructuredPatterns(root, hook, report)) {
if (pattern.kind() === 'array_pattern') {
edits.push(...fromTuple(pattern, actions, report));
} else {
report(pattern, 'return-not-destructured');
}
}
}

const report = createReport(root, manualReview, 'useCounter');

for (const pattern of destructuredPatterns(root, 'useCounter', report)) {
if (pattern.kind() === 'object_pattern') {
edits.push(...fromObject(pattern, report));
} else if (pattern.kind() !== 'array_pattern') {
report(pattern, 'return-not-destructured');
}
}

return edits.length === 0 ? null : root.root().commitEdits(edits);
}

/** The left side of each `const <pattern> = hook()`; a call used any other way is reported. */
function destructuredPatterns(root: SgRoot<TSX>, hook: string, report: Report): SgNode<TSX>[] {
return findCalls(root, hook, report).flatMap(call => {
const declarator = call.parent();

if (declarator?.kind() !== 'variable_declarator' || declarator.field('value')?.id() !== call.id()) {
report(call, 'return-not-destructured');
return [];
}

return [declarator.field('name')!];
});
}

/** `[value, a, , c]` → `[value, { a, c }]`, naming each action by its position. */
function fromTuple(pattern: SgNode<TSX>, actions: string[], report: Report): Edit[] {
const elements: Array<SgNode<TSX> | undefined> = [];
let index = 0;

for (const child of pattern.children()) {
if (child.text() === ',') {
index += 1;
} else if (child.isNamed() && child.kind() !== 'comment') {
elements[index] = child;
}
}

const [value, ...rest] = elements;

// `[value]` needs no change, and `[value, { … }]` is the v1 shape already.
if (rest.every(element => element === undefined) || (rest.length === 1 && rest[0]?.kind() === 'object_pattern')) {
return [];
}

if (elements.some(element => element?.kind() === 'rest_pattern' || element?.kind() === 'assignment_pattern')) {
report(pattern, 'return-pattern-not-simple');
return [];
}

const properties = rest.flatMap((element, i) => {
const action = actions[i];

if (element === undefined || action === undefined) {
return [];
}

return [element.text() === action ? action : `${action}: ${element.text()}`];
});

return [pattern.replace(`[${value?.text() ?? ''}, { ${properties.join(', ')} }]`)];
}

/** `{ count, increment: inc }` → `[count, { increment: inc }]`. */
function fromObject(pattern: SgNode<TSX>, report: Report): Edit[] {
let value = '';
const actions: string[] = [];

for (const property of pattern.children().filter(node => node.isNamed() && node.kind() !== 'comment')) {
if (property.kind() === 'shorthand_property_identifier_pattern') {
if (property.text() === 'count') {
value = 'count';
} else {
actions.push(property.text());
}
} else if (property.kind() === 'pair_pattern' && property.field('key')?.kind() === 'property_identifier') {
if (property.field('key')!.text() === 'count') {
value = property.field('value')!.text();
} else {
actions.push(property.text());
}
} else {
// A default, a rest element or a computed key.
report(pattern, 'return-pattern-not-simple');
return [];
}
}

return [pattern.replace(actions.length === 0 ? `[${value}]` : `[${value}, { ${actions.join(', ')} }]`)];
}
62 changes: 62 additions & 0 deletions codemods/v0-to-v1/scripts/throttle-edges.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { SgRoot } from 'codemod:ast-grep';
import type TSX from 'codemod:ast-grep/langs/tsx';
import { useMetricAtom } from 'codemod:metrics';

import { callArguments, createReport, findCalls, propertyKey, propertyName } from '../utils/options.ts';

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

// #534: { edges: ['leading'] } → { leading: true, trailing: false }
const HOOKS: Array<[hook: string, argument: number]> = [
['useThrottle', 2],
['useThrottledCallback', 0],
];

export default function transform(root: SgRoot<TSX>): string | null {
const edits = HOOKS.flatMap(([hook, argument]) => {
const report = createReport(root, manualReview, hook);

return findCalls(root, hook, report).flatMap(call => {
const options = callArguments(call)[argument];

if (options === undefined) {
return [];
}

if (options.kind() !== 'object') {
report(call, 'options-not-inline');
return [];
}

return options.children().flatMap(property => {
if (property.kind() === 'spread_element') {
report(property, 'options-spread');
return [];
}

const isEdges =
property.kind() === 'shorthand_property_identifier'
? property.text() === 'edges'
: propertyName(propertyKey(property)) === 'edges';

if (!isEdges) {
return [];
}

const value = property.field('value');
const items = value?.kind() === 'array' ? value.children().filter(node => node.isNamed()) : [];
const edges = items.map(item => (item.kind() === 'string' ? item.text().slice(1, -1) : null));

if (value?.kind() !== 'array' || edges.some(edge => edge !== 'leading' && edge !== 'trailing')) {
// `{ edges }` or `{ edges: getEdges() }` is only known at runtime.
report(property, 'edges-not-inline');
return [];
}

return [property.replace(`leading: ${edges.includes('leading')}, trailing: ${edges.includes('trailing')}`)];
});
});
});

return edits.length === 0 ? null : root.root().commitEdits(edits);
}
56 changes: 56 additions & 0 deletions codemods/v0-to-v1/scripts/time-option-names.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import type { Edit, SgRoot } from 'codemod:ast-grep';
import type TSX from 'codemod:ast-grep/langs/tsx';
import { useMetricAtom } from 'codemod:metrics';

import { findImportedBinding } from '../utils/imports.ts';
import { createReport, isBinding, renameOptionKeys } from '../utils/options.ts';

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

// #536: time options carry their unit, as in `{ timeThreshold }` → `{ debounceMs }`.
const HOOKS: Array<[hook: string, argument: number, keys: Record<string, string>]> = [
['useDebouncedCallback', 0, { timeThreshold: 'debounceMs' }],
['useThrottledCallback', 0, { timeThreshold: 'throttleMs' }],
['useImpressionRef', 0, { timeThreshold: 'timeThresholdMs' }],
['useLongPress', 1, { delay: 'delayMs' }],
['useAvoidKeyboard', 0, { transitionDuration: 'transitionDurationMs' }],
];

export default function transform(root: SgRoot<TSX>): string | null {
const edits: Edit[] = HOOKS.flatMap(([hook, argument, keys]) =>
renameOptionKeys(root, manualReview, hook, argument, keys)
);

// <ImpressionArea timeThreshold={500}> → <ImpressionArea timeThresholdMs={500}>
const report = createReport(root, manualReview, 'ImpressionArea');
const { locals, namespaces, requires, reexports } = findImportedBinding(root, 'ImpressionArea');

requires.forEach(node => report(node, 'require-not-followed'));
reexports.forEach(node => report(node, 're-exported'));

// The `typescript` grammar that parses .ts files has no JSX node kinds and throws on them.
const elements = /\.[cm]?ts$/.test(root.filename())
? []
: root.root().findAll({ rule: { any: [{ kind: 'jsx_opening_element' }, { kind: 'jsx_self_closing_element' }] } });

for (const element of elements) {
if (!isBinding(element.field('name'), 'ImpressionArea', locals, namespaces)) {
continue;
}

for (const attribute of element.children()) {
if (attribute.kind() === 'jsx_expression') {
// `{...props}` may hold `timeThreshold`.
report(attribute, 'props-spread');
}

const name = attribute.kind() === 'jsx_attribute' ? attribute.child(0) : null;

if (name?.text() === 'timeThreshold') {
edits.push(name.replace('timeThresholdMs'));
}
}
}

return edits.length === 0 ? null : root.root().commitEdits(edits);
}
89 changes: 89 additions & 0 deletions codemods/v0-to-v1/scripts/timer-hook-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { SgNode, SgRoot } from 'codemod:ast-grep';
import type TSX from 'codemod:ast-grep/langs/tsx';
import { useMetricAtom } from 'codemod:metrics';

import { callArguments, createReport, findCalls, renameObjectKeys } from '../utils/options.ts';

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

// useInterval(fn, 1000) → useInterval({ onTick: fn, delayMs: 1000 })
// useInterval(fn, { delay: 1000, … }) → useInterval({ onTick: fn, delayMs: 1000, … })
// useTimeout(fn, 1000) → useTimeout({ onTimeout: fn, delayMs: 1000 })
export default function transform(root: SgRoot<TSX>): string | null {
const edits = [
...wrapArguments(root, 'useInterval', 'onTick', true),
...wrapArguments(root, 'useTimeout', 'onTimeout', false),
];

return edits.length === 0 ? null : root.root().commitEdits(edits);
}

function wrapArguments(root: SgRoot<TSX>, hook: string, callbackKey: string, delayRequired: boolean) {
const report = createReport(root, manualReview, hook);

return findCalls(root, hook, report).flatMap(call => {
const [callback, delay, ...rest] = callArguments(call);

// A single object is the v1 shape already.
if (
callback === undefined ||
callback.kind() === 'object' ||
rest.length > 0 ||
(delayRequired && delay === undefined)
) {
return [];
}

const callbackProperty = `${callbackKey}: ${callback.text()}`;
const args = call.field('arguments')!;

if (delay === undefined) {
return [args.replace(`({ ${callbackProperty} })`)];
}

if (delay.kind() === 'object' && delayRequired) {
const object = delay.commitEdits(renameObjectKeys(delay, { delay: 'delayMs' }, report));
const first = delay.child(1)!;
// Keep a multi-line object multi-line, indented like its first property.
const separator =
first.range().start.line === delay.range().start.line
? ' '
: `\n${root.root().text().split('\n')[first.range().start.line].match(/^\s*/)![0]}`;

return [args.replace(`({${separator}${callbackProperty},${object.slice(1)})`)];
}

if (isNumber(root, delay)) {
return [args.replace(`({ ${callbackProperty}, delayMs: ${delay.text()} })`)];
}

// A variable may hold either a number or v0's options object.
report(delay, 'delay-not-inline');
return [];
});
}

const ARITHMETIC = ['+', '-', '*', '/', '%', '**'];

/** Whether `node` is a number: a literal, arithmetic on numbers, or a constant in this file holding one. */
function isNumber(root: SgRoot<TSX>, node: SgNode<TSX>): boolean {
switch (node.kind()) {
case 'number':
return true;
case 'parenthesized_expression':
return node.child(1) !== null && isNumber(root, node.child(1)!);
case 'unary_expression':
case 'binary_expression':
return ARITHMETIC.includes(node.field('operator')?.text() ?? '');
case 'identifier': {
const declarator = root.root().find({
rule: { kind: 'variable_declarator', has: { field: 'name', regex: `^${node.text()}$` } },
});
const value = declarator?.field('value');

return value !== null && value !== undefined && isNumber(root, value);
}
default:
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as simplikit from 'react-simplikit';
import { useBooleanState as useFlag } from 'react-simplikit';

export function Panel() {
const [visible, { setTrue: show, setFalse: hide }] = useFlag();
const [count, { increment }] = simplikit.useCounter(0);

return null;
}
Loading
Loading