Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Components: Update TypeScript-related tips in Contributing Guide #57267

Merged
merged 1 commit into from
Dec 21, 2023
Merged
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
162 changes: 57 additions & 105 deletions packages/components/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ For an example of a component that follows these requirements, take a look at [`
- [Documentation](#documentation)
- [README example](#README-example)
- [Folder structure](#folder-structure)
- [TypeScript migration guide](#refactoring-a-component-to-typescript)
- [Using Radix UI primitives](#using-radix-ui-primitives)

## Introducing new components
Expand Down Expand Up @@ -239,7 +238,63 @@ TDB -->

## TypeScript

We strongly encourage using TypeScript for all new components. Components should be typed using the `WordPressComponent` type.
We strongly encourage using TypeScript for all new components.

Extend existing components’ props if possible, especially when a component internally forwards its props to another component in the package:

```ts
type NumberControlProps = Omit<
InputControlProps,
'isDragEnabled' | 'min' | 'max'
> & {
/* Additional props specific to NumberControl */
};
```

Use JSDocs syntax for each TypeScript property that is part of the public API of a component. The docs used here should be aligned with the component’s README. Add `@default` values where appropriate:

```ts
/**
* Renders with elevation styles (box shadow).
*
* @default false
* @deprecated
*/
isElevated?: boolean;
```

Prefer `unknown` to `any`, and in general avoid it when possible.

If the component forwards its `...restProps` to an underlying element/component, you should use the `WordPressComponentProps` type for the component's props:

```ts
import type { WordPressComponentProps } from '../context';
import type { ComponentOwnProps } from './types';

function UnconnectedMyComponent(
// The resulting type will include:
// - all props defined in `ComponentOwnProps`
// - all HTML props/attributes from the component specified as the second
// parameter (`div` in this example)
// - the special `as` prop (which marks the component as polymorphic),
// unless the third parameter is `false`
props: WordPressComponentProps< ComponentOwnProps, 'div', true >
) { /* ... */ }
```

### Considerations for the docgen

Make sure you have a **named** export for the component, not just the default export ([example](https://github.com/WordPress/gutenberg/blob/trunk/packages/components/src/divider/component.tsx)). This ensures that the docgen can properly extract the types data. The naming should be so that the connected/forwarded component has the plain component name (`MyComponent`), and the raw component is prefixed (`UnconnectedMyComponent` or `UnforwardedMyComponent`). This makes the component's `displayName` look nicer in React devtools and in the autogenerated Storybook code snippets.

```js
function UnconnectedMyComponent() { /* ... */ }

// 👇 Without this named export, the docgen will not work!
export const MyComponent = contextConnect( UnconnectedMyComponent, 'MyComponent' );
export default MyComponent;
```

On the component's main named export, add a JSDoc comment that includes the main description and the example code snippet from the README ([example](https://github.com/WordPress/gutenberg/blob/43d9c82922619c1d1ff6b454f86f75c3157d3de6/packages/components/src/date-time/date-time/index.tsx#L193-L217)). _At the time of writing, the `@example` JSDoc keyword is not recognized by StoryBook's docgen, so please avoid using it_.

<!-- TODO: add to the previous paragraph once the composision section gets added to this document.
(more details about polymorphism can be found above in the "Components composition" section). -->
Expand Down Expand Up @@ -538,109 +593,6 @@ component-family-name/
└── utils.ts
```

## Refactoring a component to TypeScript

*Note: This section assumes that the local developer environment is set up correctly, including TypeScript linting. We also strongly recommend using an IDE that supports TypeScript.*

Given a component folder (e.g. `packages/components/src/unit-control`):

1. Remove the folder from the exclude list in `tsconfig.json`, if it isn’t already.
2. Remove any `// @ts-nocheck` comments in the folder, if any.
3. Rename `*.js{x}` files to `*.ts{x}` (except stories and unit tests).
4. Run `npm run dev` and take note of all the errors (your IDE should also flag them).
5. Since we want to focus on one component’s folder at the time, if any errors are coming from files outside of the folder that is being refactored, there are two potential approaches:
1. Following those same guidelines, refactor those dependencies first.
1. Ideally, start from the “leaf” of the dependency tree and slowly work your way up the chain.
2. Resume work on this component once all dependencies have been refactored.
2. Alternatively:
1. For each of those files, add `// @ts-nocheck` at the start of the file.
2. If the components in the ignored files are destructuring props directly from the function's arguments, move the props destructuring to the function's body (this is to avoid TypeScript errors from trying to infer the props type):

```jsx
// Before:
function MyComponent( { myProp1, myProp2, ...restProps } ) { /* ... */ }

// After:
function MyComponent( props ) {
const { myProp1, myProp2, ...restProps } = props;

/* ... */
}
```

3. Remove the folders from the exclude list in the `tsconfig.json` file.
4. If you’re still getting errors about a component’s props, the easiest way is to slightly refactor this component and perform the props destructuring inside the component’s body (as opposed as in the function signature) — this is to prevent TypeScript from inferring the types of these props.
5. Continue with the refactor of the current component (and take care of the refactor of the dependent components at a later stage).
6. Create a new `types.ts` file.
7. Slowly work your way through fixing the TypeScript errors in the folder:
1. Try to avoid introducing any runtime changes, if possible. The aim of this refactor is to simply rewrite the component to TypeScript.
2. Extract props to `types.ts`, and use them to type components. The README can be of help when determining a prop’s type.
3. Use existing HTML types when possible? (e.g. `required` for an input field?)
4. Use the `CSSProperties` type where it makes sense.
5. Extend existing components’ props if possible, especially when a component internally forwards its props to another component in the package.
6. If the component forwards its `...restProps` to an underlying element/component, you should use the `WordPressComponentProps` type for the component's props:

```tsx
import type { WordPressComponentProps } from '../context';
import type { ComponentOwnProps } from './types';

function UnconnectedMyComponent(
// The resulting type will include:
// - all props defined in `ComponentOwnProps`
// - all HTML props/attributes from the component specified as the second
// parameter (`div` in this example)
// - the special `as` prop (which marks the component as polymorphic),
// unless the third parameter is `false`
props: WordPressComponentProps< ComponentOwnProps, 'div', true >
) { /* ... */ }
```

7. As shown in the previous examples, make sure you have a **named** export for the component, not just the default export ([example](https://github.com/WordPress/gutenberg/blob/trunk/packages/components/src/divider/component.tsx)). This ensures that the docgen can properly extract the types data. The naming should be so that the connected/forwarded component has the plain component name (`MyComponent`), and the raw component is prefixed (`UnconnectedMyComponent` or `UnforwardedMyComponent`). This makes the component's `displayName` look nicer in React devtools and in the autogenerated Storybook code snippets.

```jsx
function UnconnectedMyComponent() { /* ... */ }

// 👇 Without this named export, the docgen will not work!
export const MyComponent = contextConnect( UnconnectedMyComponent, 'MyComponent' );
export default MyComponent;
```

8. Use JSDocs syntax for each TypeScript property that is part of the public API of a component. The docs used here should be aligned with the component’s README. Add `@default` values where appropriate.
9. Prefer `unknown` to `any`, and in general avoid it when possible.
8. On the component's main named export, add a JSDoc comment that includes the main description and the example code snippet from the README ([example](https://github.com/WordPress/gutenberg/blob/43d9c82922619c1d1ff6b454f86f75c3157d3de6/packages/components/src/date-time/date-time/index.tsx#L193-L217)). _At the time of writing, the `@example` JSDoc keyword is not recognized by StoryBook's docgen, so please avoid using it_.
9. Make sure that:
1. tests still pass;
2. storybook examples work as expected.
3. the component still works as expected in its usage in Gutenberg;
4. the JSDocs comments on `types.ts` and README docs are aligned.
10. Convert Storybook examples to TypeScript (and from knobs to controls, if necessary) ([example](https://github.com/WordPress/gutenberg/pull/39320)).
1. Update all consumers of the component to potentially extend the newly added types (e.g. make `UnitControl` props extend `NumberControl` props after `NumberControl` types are made available).
2. Rename Story extension from `.js` to `.tsx`.
3. Rewrite the `meta` story object, and export it as default. In particular, make sure you add the following settings under the `parameters` key:

```tsx
const meta: Meta< typeof MyComponent > = {
parameters: {
controls: { expanded: true },
docs: { canvas: { sourceState: 'shown' } },
},
};
```

These options will display prop descriptions in the `Canvas ▸ Controls` tab, and expand code snippets in the `Docs` tab.

4. Go to the component in Storybook and check the props table in the Docs tab. If there are props that shouldn't be there, check that your types are correct, or consider `Omit`-ing props that shouldn't be exposed.
1. Use the `parameters.controls.exclude` property on the `meta` object to hide props from the docs.
2. Use the `argTypes` prop on the `meta` object to customize how each prop in the docs can be interactively controlled by the user (tip: use `control: { type: null }` to remove the interactive controls from a prop, without hiding the prop from the docs).
3. See the [official docs](https://storybook.js.org/docs/react/essentials/controls) for more details.
5. Comment out all existing stories.
6. Create a default template, where the component is being used in the most “vanilla” way possible.
7. Use the template for the `Default` story, which will serve as an interactive doc playground.
8. Add more focused stories as you see fit. These non-default stories should illustrate specific scenarios and usages of the component. A developer looking at the Docs tab should be able to understand what each story is demonstrating. Add JSDoc comments to stories when necessary.
11. Convert unit tests.
1. Rename test file extensions from `.js` to `.tsx`.
2. Fix all TypeScript errors.

## Using Radix UI primitives

Useful links:
Expand Down
Loading