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

Addon-actions: Add Storybook Args support #10029

Merged
merged 18 commits into from Mar 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
85 changes: 53 additions & 32 deletions addons/actions/README.md
Expand Up @@ -18,10 +18,45 @@ Then, add following content to `.storybook/main.js`

```js
module.exports = {
addons: ['@storybook/addon-actions']
}
addons: ['@storybook/addon-actions'],
};
```

## Actions args

Starting in SB6.0, we recommend using story parameters to specify actions which get passed into your story as [Args](https://docs.google.com/document/d/1Mhp1UFRCKCsN8pjlfPdz8ZdisgjNXeMXpXvGoALjxYM/edit?usp=sharing) (passed as the first argument when `passArgsFirst` is set to `true`).

The first option is to specify `argTypes` for your story with an `action` field. Take the following example:

```js
import Button from './button';

export default {
title: 'Button',
argTypes: { onClick: { action: 'clicked' } },
};

export const Basic = ({ onClick }) => <Button onClick={onClick}>Hello World!</Button>;
```

Alternatively, suppose you have a naming convention, like `onX` for event handlers. The following configuration automatically creates actions for each `onX` `argType` (which you can either specify manually or generate automatically using [Storybook Docs](https://www.npmjs.com/package/@storybook/addon-docs).

```js
import Button from './button';

export default {
title: 'Button',
component: Button,
parameters: { actions: { argTypesRegex: '^on.*' } },
};

export const Basic = ({ onClick }) => <Button onClick={onClick}>Hello World!</Button>;
```

> **NOTE:** If you're generating `argTypes` in using another addon (like Docs, which is the common behavior) you'll need to make sure that the actions addon loads **AFTER** the other addon. You can do this by listing it later in the `addons` registration code in `.storybook/main.js`.

## Manually-specified actions

Import the `action` function and use it to create actions handlers. When creating action handlers, provide a **name** to make it easier to identify.

> _Note: Make sure NOT to use reserved words as function names. [issues#29](https://github.com/storybookjs/storybook-addon-actions/issues/29#issuecomment-288274794)_
Expand All @@ -35,9 +70,7 @@ export default {
component: Button,
};

export const defaultView = () => (
<Button onClick={action('button-click')}>Hello World!</Button>
);
export const defaultView = () => <Button onClick={action('button-click')}>Hello World!</Button>;
```

## Multiple actions
Expand All @@ -59,13 +92,9 @@ const eventsFromNames = actions('onClick', 'onMouseOver');
// This will lead to { onClick: action('clicked'), ... }
const eventsFromObject = actions({ onClick: 'clicked', onMouseOver: 'hovered' });

export const first = () => (
<Button {...eventsFromNames}>Hello World!</Button>
);
export const first = () => <Button {...eventsFromNames}>Hello World!</Button>;

export const second = () => (
<Button {...eventsFromObject}>Hello World!</Button>
);
export const second = () => <Button {...eventsFromObject}>Hello World!</Button>;
```

## Action Decorators
Expand All @@ -85,22 +114,16 @@ export default {

const firstArg = decorate([args => args.slice(0, 1)]);

export const first = () => (
<Button onClick={firstArg.action('button-click')}>Hello World!</Button>
);
export const first = () => <Button onClick={firstArg.action('button-click')}>Hello World!</Button>;
```

## Configuration

Arguments which are passed to the action call will have to be serialized while be "transferred"
over the channel.
Arguments which are passed to the action call will have to be serialized while be "transferred" over the channel.

This is not very optimal and can cause lag when large objects are being logged, for this reason it is possible
to configure a maximum depth.
This is not very optimal and can cause lag when large objects are being logged, for this reason it is possible to configure a maximum depth.

The action logger, by default, will log all actions fired during the lifetime of the story. After a while
this can make the storybook laggy. As a workaround, you can configure an upper limit to how many actions should
be logged.
The action logger, by default, will log all actions fired during the lifetime of the story. After a while this can make the storybook laggy. As a workaround, you can configure an upper limit to how many actions should be logged.

To apply the configuration globally use the `configureActions` function in your `preview.js` file.

Expand All @@ -115,6 +138,7 @@ configureActions({
```

To apply the configuration per action use:

```js
action('my-action', {
depth: 5,
Expand All @@ -123,27 +147,24 @@ action('my-action', {

### Available Options

|Name|Type|Description|Default|
|---|---|---|---|
|`depth`|Number|Configures the transferred depth of any logged objects.|`10`|
|`clearOnStoryChange`|Boolean|Flag whether to clear the action logger when switching away from the current story.|`true`|
|`limit`|Number|Limits the number of items logged in the action logger|`50`|
| Name | Type | Description | Default |
| -------------------- | ------- | ----------------------------------------------------------------------------------- | ------- |
| `depth` | Number | Configures the transferred depth of any logged objects. | `10` |
| `clearOnStoryChange` | Boolean | Flag whether to clear the action logger when switching away from the current story. | `true` |
| `limit` | Number | Limits the number of items logged in the action logger | `50` |

## withActions decorator

You can define action handles in a declarative way using `withActions` decorators. It accepts the same arguments as [`actions`](#multiple-actions)
Keys have `'<eventName> <selector>'` format, e.g. `'click .btn'`. Selector is optional. This can be used with any framework but is especially useful for `@storybook/html`.
You can define action handles in a declarative way using `withActions` decorators. It accepts the same arguments as [`actions`](#multiple-actions). Keys have `'<eventName> <selector>'` format, e.g. `'click .btn'`. Selector is optional. This can be used with any framework but is especially useful for `@storybook/html`.

```js
import { withActions } from '@storybook/addon-actions';
import Button from './button';

export default {
title: 'Button',
decorators: [withActions('mouseover', 'click .btn')]
decorators: [withActions('mouseover', 'click .btn')],
};

export const first = () => (
<Button className="btn">Hello World!</Button>
);
export const first = () => <Button className="btn">Hello World!</Button>;
```
1 change: 1 addition & 0 deletions addons/actions/preset.js
@@ -0,0 +1 @@
module.exports = require('./dist/preset');
67 changes: 67 additions & 0 deletions addons/actions/src/preset/addArgs.test.ts
@@ -0,0 +1,67 @@
import { StoryContext } from '@storybook/addons';
import { inferActionsFromArgTypesRegex, addActionsFromArgTypes } from './addArgs';

describe('actions parameter enhancers', () => {
describe('actions.argTypesRegex parameter', () => {
const baseParameters = {
argTypes: { onClick: {}, onFocus: {}, somethingElse: {} },
actions: { argTypesRegex: '^on.*' },
};

it('should add actions that match a pattern', () => {
const parameters = baseParameters;
const { args } = inferActionsFromArgTypesRegex({ parameters } as StoryContext);
expect(Object.keys(args)).toEqual(['onClick', 'onFocus']);
});

it('should prioritize pre-existing args', () => {
const parameters = {
...baseParameters,
args: { onClick: 'pre-existing arg' },
};
const { args } = inferActionsFromArgTypesRegex({ parameters } as StoryContext);
expect(Object.keys(args)).toEqual(['onClick', 'onFocus']);
expect(args.onClick).toEqual('pre-existing arg');
});

it('should do nothing if actions are disabled', () => {
const parameters = {
...baseParameters,
actions: { ...baseParameters.actions, disable: true },
};
const result = inferActionsFromArgTypesRegex({ parameters } as StoryContext);
expect(result).toBeFalsy();
});
});

describe('argTypes.action parameter', () => {
const baseParameters = {
argTypes: {
onClick: { action: 'clicked!' },
onBlur: { action: 'blurred!' },
},
};

it('should add actions based on action.args', () => {
const parameters = baseParameters;
const { args } = addActionsFromArgTypes({ parameters } as StoryContext);
expect(Object.keys(args)).toEqual(['onClick', 'onBlur']);
});

it('should prioritize pre-existing args', () => {
const parameters = {
...baseParameters,
args: { onClick: 'pre-existing arg' },
};
const { args } = addActionsFromArgTypes({ parameters } as StoryContext);
expect(Object.keys(args)).toEqual(['onClick', 'onBlur']);
expect(args.onClick).toEqual('pre-existing arg');
});

it('should do nothing if actions are disabled', () => {
const parameters = { ...baseParameters, actions: { disable: true } };
const result = addActionsFromArgTypes({ parameters } as StoryContext);
expect(result).toBeFalsy();
});
});
});
57 changes: 57 additions & 0 deletions addons/actions/src/preset/addArgs.ts
@@ -0,0 +1,57 @@
import { ParameterEnhancer, combineParameters } from '@storybook/client-api';
import { Args, ArgType } from '@storybook/addons';

import { action } from '../index';

// interface ActionsParameter {
// disable?: boolean;
// argTypesRegex?: RegExp;
// }

/**
* Automatically add action args for argTypes whose name
* matches a regex, such as `^on.*` for react-style `onClick` etc.
*/
export const inferActionsFromArgTypesRegex: ParameterEnhancer = context => {
const { args, actions, argTypes } = context.parameters;
if (!actions || actions.disable || !actions.argTypesRegex || !argTypes) {
shilman marked this conversation as resolved.
Show resolved Hide resolved
return null;
}

const argTypesRegex = new RegExp(actions.argTypesRegex);
const actionArgs = Object.keys(argTypes).reduce((acc, name) => {
if (argTypesRegex.test(name)) {
acc[name] = action(name);
}
return acc;
}, {} as Args);

return {
args: combineParameters(actionArgs, args),
tmeasday marked this conversation as resolved.
Show resolved Hide resolved
};
};

/**
* Add action args for list of strings.
*/
export const addActionsFromArgTypes: ParameterEnhancer = context => {
const { args, argTypes, actions } = context.parameters;
if (actions?.disable || !argTypes) {
return null;
}

const actionArgs = Object.keys(argTypes).reduce((acc, argName) => {
const argType: ArgType = argTypes[argName];
if (argType.action) {
const message = typeof argType.action === 'string' ? argType.action : argName;
acc[argName] = action(message);
}
return acc;
}, {} as Args);

return {
args: combineParameters(actionArgs, args),
};
};

export const parameterEnhancers = [addActionsFromArgTypes, inferActionsFromArgTypesRegex];
7 changes: 7 additions & 0 deletions addons/actions/src/preset/index.ts
@@ -0,0 +1,7 @@
export function managerEntries(entry: any[] = [], options: any) {
return [...entry, require.resolve('../../register')];
}

export function config(entry: any[] = []) {
return [...entry, require.resolve('./addArgs')];
}
10 changes: 3 additions & 7 deletions addons/actions/tsconfig.json
Expand Up @@ -2,12 +2,8 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"types": ["webpack-env"]
"types": ["webpack-env", "jest"]
},
"include": [
"src/**/*"
],
"exclude": [
"src/__tests__/**/*"
]
"include": ["src/**/*"],
"exclude": ["src/__tests__/**/*", "src/**/*.test.ts"]
}
27 changes: 27 additions & 0 deletions examples/official-storybook/stories/addon-actions.stories.js
@@ -1,3 +1,4 @@
/* eslint-disable react/prop-types */
import { window, File } from 'global';
import React, { Fragment } from 'react';
import { action, actions, configureActions, decorate } from '@storybook/addon-actions';
Expand All @@ -10,12 +11,38 @@ const pickNative = decorate([args => [args[0].nativeEvent]]);
export default {
title: 'Addons/Actions',
parameters: {
passArgsFirst: true,
options: {
selectedPanel: 'storybook/actions/panel',
},
},
};

export const ArgTypesExample = ({ onClick, onFocus }) => (
<Button {...{ onClick, onFocus }}>Hello World</Button>
);

ArgTypesExample.story = {
argTypes: {
onClick: { action: 'clicked!' },
onFocus: { action: true },
},
};

export const ArgTypesRegexExample = (args, context) => {
const { someFunction, onClick, onFocus } = args;
return (
<Button onMouseOver={someFunction} {...{ onClick, onFocus }}>
Hello World
</Button>
);
};

ArgTypesRegexExample.story = {
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: { someFunction: {}, onClick: {}, onFocus: {} },
};

export const BasicExample = () => <Button onClick={action('hello-world')}>Hello World</Button>;

BasicExample.story = {
Expand Down
11 changes: 11 additions & 0 deletions lib/addons/src/types.ts
Expand Up @@ -33,6 +33,17 @@ export interface Args {
[key: string]: any;
}

export interface ArgType {
name?: string;
description?: string;
defaultValue?: any;
[key: string]: any;
}

export interface ArgTypes {
[key: string]: ArgType;
}

export interface StoryIdentifier {
id: StoryId;
kind: StoryKind;
Expand Down
2 changes: 2 additions & 0 deletions lib/client-api/src/index.ts
@@ -1,5 +1,6 @@
import ClientApi, { addDecorator, addParameters, addParameterEnhancer } from './client_api';
import { defaultDecorateStory } from './decorators';
import { combineParameters } from './parameters';
import StoryStore from './story_store';
import ConfigApi from './config_api';
import pathToId from './pathToId';
Expand All @@ -15,6 +16,7 @@ export {
addDecorator,
addParameters,
addParameterEnhancer,
combineParameters,
StoryStore,
ConfigApi,
defaultDecorateStory,
Expand Down