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 12 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
74 changes: 49 additions & 25 deletions addons/actions/README.md
Expand Up @@ -18,10 +18,43 @@ 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 the `actions` story parameter to specify actions. There are two relevant options `actions.args` and `actions.argTypesRegex` which the actions addon uses to inject actions into your story functions as Storybook Args.

The following example uses the `actions.args` array to generate actions that are passed into the story (when `passArgsFirst` is set to `true`):

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

export default {
title: 'Button',
parameters: { actions: { args: ['onClick'] } },
};

export const defaultView = ({ 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).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add an example of how you'd provide an argType to the story? Or is that sort of pointless?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Waiting on this until the argTypes design is finalized


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

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

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

## 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 +68,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 +90,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,21 +112,19 @@ 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.

This is not very optimal and can cause lag when large objects are being logged, for this reason it is possible
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
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 +140,7 @@ configureActions({
```

To apply the configuration per action use:

```js
action('my-action', {
depth: 5,
Expand All @@ -123,11 +149,11 @@ 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

Expand All @@ -140,10 +166,8 @@ 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');
64 changes: 64 additions & 0 deletions addons/actions/src/preset/addArgs.test.ts
@@ -0,0 +1,64 @@
import { StoryContext } from '@storybook/addons';
import { inferActionsFromArgTypes, addActionsFromArgs } from './addArgs';

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

it('should add actions that match a pattern', () => {
const parameters = baseParameters;
const { args } = inferActionsFromArgTypes({ 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 } = inferActionsFromArgTypes({ 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 = inferActionsFromArgTypes({ parameters } as StoryContext);
expect(result).toBeFalsy();
});
});

describe('args option', () => {
const baseParameters = {
actions: { args: ['onClick', 'onBlur'] },
};

it('should add actions based on action.args', () => {
const parameters = baseParameters;
const { args } = addActionsFromArgs({ 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 } = addActionsFromArgs({ 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 = { actions: { ...baseParameters.actions, disable: true } };
const result = addActionsFromArgs({ parameters } as StoryContext);
expect(result).toBeFalsy();
});
});
});
54 changes: 54 additions & 0 deletions addons/actions/src/preset/addArgs.ts
@@ -0,0 +1,54 @@
import { ParameterEnhancer, combineParameters } from '@storybook/client-api';
import { Args } from '@storybook/addons';

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

// interface ActionsParameter {
// disable?: boolean;
// args?: string[];
// argTypesRegex?: RegExp;
// }

/**
* Automatically add action args for argTypes whose name
* matches a regex, such as `^on.*` for react-style `onClick` etc.
*/
export const inferActionsFromArgTypes: 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 addActionsFromArgs: ParameterEnhancer = context => {
const { args, actions } = context.parameters;
if (!actions || actions.disable || !actions.args) {
return null;
}

const actionArgs = (actions.args as string[]).reduce((acc, name) => {
acc[name] = action(name);
return acc;
}, {} as Args);

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

export const parameterEnhancers = [addActionsFromArgs, inferActionsFromArgTypes];
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
Expand Up @@ -10,12 +10,39 @@ const pickNative = decorate([args => [args[0].nativeEvent]]);
export default {
title: 'Addons/Actions',
parameters: {
passArgsFirst: true,
options: {
selectedPanel: 'storybook/actions/panel',
},
},
};

export const ArgsExample = args => {
const { onClick } = args;
return <Button onClick={onClick}>Hello World</Button>;
};

ArgsExample.story = {
parameters: { actions: { args: ['onClick'] } },
};

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

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

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

BasicExample.story = {
Expand Down
1 change: 0 additions & 1 deletion lib/api/src/index.tsx
Expand Up @@ -450,6 +450,5 @@ export function useGlobalArgs() {
state: { globalArgs },
api: { setGlobalArgs },
} = useContext(ManagerContext);

return [globalArgs, setGlobalArgs];
}
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 @@ -14,6 +15,7 @@ export {
addDecorator,
addParameters,
addParameterEnhancer,
combineParameters,
StoryStore,
ConfigApi,
defaultDecorateStory,
Expand Down