1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-22 09:23:21 +01:00

Docs/12367 Adding storybook essentials addons (#12393)

* Adding storybook essentials and documentation contribution guidelines

* Deprecation updates

* Update ui/2.DOCUMENTATION.stories.mdx

Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>

* Updating spelling and adding label to i18n-party plugin in toolbar

Co-authored-by: kumavis <kumavis@users.noreply.github.com>
Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>
This commit is contained in:
George Marshall 2021-10-29 10:22:07 -07:00 committed by GitHub
parent 487080bd16
commit d72f7295a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 2913 additions and 1343 deletions

View File

@ -1,49 +1,48 @@
# things that *are* used, that depcheck is wrong about
ignores:
#
#
# webapp deps
#
#
- "@babel/runtime"
- "@fortawesome/fontawesome-free"
- "punycode"
#
- '@babel/runtime'
- '@fortawesome/fontawesome-free'
- 'punycode'
#
# dev deps
#
# safety fallback for npm lifecycle scripts, not used normally
- "@lavamoat/preinstall-always-fail"
- '@lavamoat/preinstall-always-fail'
# used in testing + ci
- "@metamask/auto-changelog" # invoked as `auto-changelog`
- "@metamask/forwarder"
- "@metamask/test-dapp"
- "@sentry/cli" # invoked as `sentry-cli`
- "chromedriver"
- "depcheck" # ooo meta
- "ganache-cli"
- "geckodriver"
- "jest"
- "lavamoat-viz"
- "prettier-plugin-sort-json" # automatically imported by prettier
- "source-map-explorer"
- '@metamask/auto-changelog' # invoked as `auto-changelog`
- '@metamask/forwarder'
- '@metamask/test-dapp'
- '@sentry/cli' # invoked as `sentry-cli`
- 'chromedriver'
- 'depcheck' # ooo meta
- 'ganache-cli'
- 'geckodriver'
- 'jest'
- 'lavamoat-viz'
- 'prettier-plugin-sort-json' # automatically imported by prettier
- 'source-map-explorer'
# development tool
- "yarn-deduplicate"
- "improved-yarn-audit"
- 'yarn-deduplicate'
- 'improved-yarn-audit'
# storybook
- "@storybook/core"
- "@storybook/addon-backgrounds"
- "@storybook/addon-toolbars"
- "style-loader"
- "css-loader"
- "sass-loader"
- "resolve-url-loader"
- '@storybook/core'
- '@storybook/addon-essentials'
- '@storybook/addon-a11y'
- 'style-loader'
- 'css-loader'
- 'sass-loader'
- 'resolve-url-loader'
# files depcheck should not parse
# files depcheck should not parse
ignorePatterns:
# seems to incorrectly parse scss @include pragmas?
- "**/*.scss"
- '**/*.scss'
# self-contained bundle used for testing
- "**/send-eth-with-private-key-test/web3js.js"
- "**/send-eth-with-private-key-test/ethereumjs-tx.js"
- '**/send-eth-with-private-key-test/web3js.js'
- '**/send-eth-with-private-key-test/ethereumjs-tx.js'

View File

@ -1,37 +1,41 @@
// import { useGlobals } from '@storybook/api';
const { useGlobals } = require('@storybook/api')
const React = require("react")
const { addons, types } = require("@storybook/addons")
const { Icons, IconButton } = require('@storybook/components')
const localeList = require('../../app/_locales/index.json')
const { useEffect } = React
const { useGlobals } = require('@storybook/api');
const React = require('react');
const { addons, types } = require('@storybook/addons');
const { Icons, IconButton } = require('@storybook/components');
const localeList = require('../../app/_locales/index.json');
const { useEffect } = React;
addons.register("i18n-party", () => {
addons.add("i18n-party", {
title: "rotates through every i18n locale",
addons.register('i18n-party', () => {
addons.add('i18n-party', {
title: 'rotates through every i18n locale',
//👇 Sets the type of UI element in Storybook
type: types.TOOL,
match: () => true,
render: (...args) => {
// https://github.com/storybookjs/storybook/blob/6490a0d646dbaa293b76bbde477daca615efe789/addons/toolbars/src/components/MenuToolbar.tsx#L2
const [globals, updateGlobals] = useGlobals()
const [globals, updateGlobals] = useGlobals();
useEffect(() => {
if (!globals.localeParty) return
if (!globals.localeParty) return;
const interval = setInterval((...args) => {
const currentIndex = localeList.findIndex(({ code }) => code === globals.locale)
const nextIndex = (currentIndex + 1) % localeList.length
const nextLocale = localeList[nextIndex].code
updateGlobals({ locale: nextLocale })
}, 2000)
return () => clearInterval(interval)
})
const currentIndex = localeList.findIndex(
({ code }) => code === globals.locale,
);
const nextIndex = (currentIndex + 1) % localeList.length;
const nextLocale = localeList[nextIndex].code;
updateGlobals({ locale: nextLocale });
}, 2000);
return () => clearInterval(interval);
});
return (
<IconButton onClick={() => updateGlobals({ localeParty: !globals.localeParty })}>
<Icons icon={globals.localeParty ? 'star' : 'starhollow'}/>
<IconButton
onClick={() => updateGlobals({ localeParty: !globals.localeParty })}
>
<Icons icon={globals.localeParty ? 'star' : 'starhollow'} />
<span>&nbsp;Shuffle i18n locale</span>
</IconButton>
)
);
},
})
})
});
});

View File

@ -3,19 +3,21 @@ const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
stories: ['../ui/**/*.stories.js'],
stories: ['../ui/**/*.stories.js', '../ui/**/*.stories.mdx'],
addons: [
'@storybook/addon-knobs',
'@storybook/addon-essentials',
'@storybook/addon-actions',
'@storybook/addon-backgrounds',
'@storybook/addon-toolbars',
'@storybook/addon-a11y',
'@storybook/addon-knobs',
'./i18n-party-addon/register.js',
],
// Uses babel.config.js settings and prevents "Missing class properties transform" error
babel: async (options) => ({ overrides: options.overrides }),
webpackFinal: async (config) => {
config.context = process.cwd()
config.context = process.cwd();
config.node = {
__filename: true
}
__filename: true,
};
config.module.strictExportPresence = true;
config.module.rules.push({
test: /\.scss$/,

View File

@ -8,11 +8,11 @@ import '../ui/css/index.scss';
import localeList from '../app/_locales/index.json';
import * as allLocales from './locales';
import { I18nProvider, LegacyI18nProvider } from './i18n';
import MetaMetricsProviderStorybook from './metametrics'
import MetaMetricsProviderStorybook from './metametrics';
import testData from './test-data.js';
import { Router } from "react-router-dom";
import { createBrowserHistory } from "history";
import { _setBackgroundConnection } from '../ui/store/actions'
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import { _setBackgroundConnection } from '../ui/store/actions';
addParameters({
backgrounds: {
@ -38,28 +38,24 @@ export const globalTypes = {
},
};
const styles = {
height: '100vh',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
};
export const getNewState = (state, props) => {
return Object.assign(state, props);
}
};
export const store = configureStore(testData);
const history = createBrowserHistory();
const proxiedBackground = new Proxy({}, {
const proxiedBackground = new Proxy(
{},
{
get(_, method) {
return function() {
action(`Background call: ${method}`)()
return new Promise(() => {})
}
}
})
_setBackgroundConnection(proxiedBackground)
return function () {
action(`Background call: ${method}`)();
return new Promise(() => {});
};
},
},
);
_setBackgroundConnection(proxiedBackground);
const metamaskDecorator = (story, context) => {
const currentLocale = context.globals.locale;
@ -73,9 +69,7 @@ const metamaskDecorator = (story, context) => {
current={current}
en={allLocales.en}
>
<LegacyI18nProvider>
<div style={styles}>{story()}</div>
</LegacyI18nProvider>
<LegacyI18nProvider>{story()}</LegacyI18nProvider>
</I18nProvider>
</MetaMetricsProviderStorybook>
</Router>

View File

@ -228,16 +228,18 @@
"@metamask/forwarder": "^1.1.0",
"@metamask/test-dapp": "^4.0.1",
"@sentry/cli": "^1.58.0",
"@storybook/addon-actions": "^6.1.17",
"@storybook/addon-backgrounds": "^6.1.17",
"@storybook/addon-knobs": "^6.1.17",
"@storybook/addon-toolbars": "^6.1.17",
"@storybook/addons": "^6.1.7",
"@storybook/api": "^6.1.7",
"@storybook/components": "^6.1.7",
"@storybook/core": "^6.1.17",
"@storybook/react": "^6.1.17",
"@storybook/storybook-deployer": "^2.8.7",
"@storybook/addon-a11y": "^6.3.12",
"@storybook/addon-actions": "^6.3.12",
"@storybook/addon-essentials": "^6.3.12",
"@storybook/addon-knobs": "^6.3.1",
"@storybook/addons": "^6.3.12",
"@storybook/api": "^6.3.12",
"@storybook/components": "^6.3.12",
"@storybook/core": "^6.3.12",
"@storybook/core-events": "^6.3.0",
"@storybook/react": "^6.3.12",
"@storybook/storybook-deployer": "^2.8.10",
"@storybook/theming": "^6.3.0",
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^10.4.8",
"@testing-library/react-hooks": "^3.2.1",

View File

@ -0,0 +1,15 @@
import { Meta } from '@storybook/addon-docs';
<Meta title="Getting Started / Introduction" />
# Introduction
Welcome to the MetaMask Browser Extension Storybook.
## Building locally and Contributing
This document is currently only specific to storybook best practices and component documentation guidelines. This may change in future but for now if you are looking to get a local build of Metamask up and running or contribute to the extension codebase please read the Metamask [README.md](https://github.com/MetaMask/metamask-extension)
## Documentation Guidelines
If you're here to improve our storybook documentation you're in the right place! Please head over to the [Documentation Guidelines](./?path=/story/getting-started-documentation-guidelines--page) for contributing to component documentation in storybook.

View File

@ -0,0 +1,182 @@
import { Meta } from '@storybook/addon-docs';
<Meta title="Getting Started / Documentation Guidelines" />
# Documentation Guidelines
> 💡 To improve the quality of our component documentation we are currently in the process of updating our storybook to use Storyboook's [controls](https://storybook.js.org/addons/@storybook/addon-controls/), [a11y](https://storybook.js.org/addons/@storybook/addon-a11y/) and [docs](https://storybook.js.org/addons/@storybook/addon-docs/) plugins. You will find most components currently without documentation and use knobs for their primary interactivity. These will eventually be updated.
## General Guidelines
Thorough documentation makes it much easier for a component to be found, adapted and reused. It also provides space for explanation and reasoning for a component. This is useful as components become more complex.
Some general documentation best practices to follow:
- Put yourself in the shoes of another developer trying to use the component you just created for the first time
- Write a brief description of the component and what it's used for in the `README.mdx` file
- Display the component's api using the `<ArgsTable of={YourComponent} />` component from storybook docs
- Use the [controls](https://storybook.js.org/addons/@storybook/addon-controls/) api over knobs
- Use the updated `argType` [actions](https://storybook.js.org/docs/react/essentials/actions) api over importing the actions plugin directly
- Check the accessibility of the component using the **Accessibility** tab
See the [Button](https://metamask.github.io/metamask-storybook/index.html?path=/story/ui-components-ui-button-button-stories-js--default-story)(`ui/components/ui/button/button.stories.js`) component for reference
## Creating a Story
[Component Story Format (CSF)](https://storybook.js.org/docs/react/api/csf) is the recommended way to write stories. It's an open standard based on ES6 modules. The below example is of the Button component and it explains how we should write our stories.
```jsx
// Button component example story
import React from 'react';
import BuyIcon from '../icon/overview-buy-icon.component';
// The mdx file to document component api and usage
import README from './README.mdx';
import Button from '.';
// The default storybook component export should always follow the same template
export default {
title: 'Button', // The `title` effects the components tile and location in storybook
id: __filename, // The file name id is used to track what storybook files have changed in CI
component: Button, // The component you are documenting
parameters: {
docs: {
page: README, // Reference to the mdx file docs page
},
},
// the controls plugin argTypes are used for the interactivity of the component
argTypes: {
children: { control: 'text' },
disabled: { control: 'boolean' },
// use the updated action api to log actions in the actions tab
onClick: { action: 'clicked' },
type: {
control: {
type: 'select',
},
options: [
'default',
'primary',
'secondary',
'warning',
'danger',
'danger-primary',
'link',
],
},
submit: { control: 'boolean' },
large: { control: 'boolean' },
className: { control: 'text' },
icon: {
control: {
type: 'select',
},
options: ['BuyIcon'],
mapping: {
BuyIcon: <BuyIcon />,
},
},
},
};
// First story component should always be called "DefaultStory"
// The `DefaultStory` should include argTypes and controls where appropriate
export const DefaultStory = (args) => (
<Button {...args}>{args.children}</Button>
);
// The name of the DefaultStory component can be renamed to simply "Default"
DefaultStory.storyName = 'Default';
// More stories should be added for different usage examples
// You can add as many stories as you think appropriate to comprehensively document the component
export const Types = (args) => (
<>
<Button {...args} type="default">
{args.children || 'Default'}
</Button>
<Button {...args} type="primary">
{args.children || 'Primary'}
</Button>
<Button {...args} type="secondary">
{args.children || 'Secondary'}
</Button>
<Button {...args} type="warning">
{args.children || 'Warning'}
</Button>
<Button {...args} type="danger">
{args.children || 'Danger'}
</Button>
<Button {...args} type="danger-primary">
{args.children || 'Danger primary'}
</Button>
<Button {...args} type="link">
{args.children || 'Link'}
</Button>
</>
);
```
## Writing MDX Documentation
Now the storybook components are complete, the `README.mdx` documentation should explain the component in detail. [MDX](https://mdxjs.com/) format lets you seamlessly use `JSX` in your markdown documents. You can import react components and stories into your documentation to enhance the developer experience.
```md
<!-- import the necessary blocks from storybook docs -->
import { Story, Canvas, ArgsTable } from '@storybook/addon-docs';
<!-- import the component to use for the ArgsTable under ## Component API -->
import Button from '.';
<!-- Title of the component -->
# Button
<!-- Brief description of the component -->
Buttons communicate actions that users can take.
<!-- Embed the DefaultStory using the storybook url -->
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--default-story" />
</Canvas>
## Component API
<!-- Display the component api using the ArgsTable -->
<ArgsTable of={Button} />
## Usage
<!-- Further documentation on usage of the component -->
The following describes the props and example usage for this component.
### Type
By changing the `type` prop you can use different styles of the button.
| type | Description |
| ----------------- | ----------------------------------------------------------------------------------------------------- |
| `default` | default style of the button |
| `primary` | the principle call to action on the page |
| `secondary` | secondary actions on each page |
| `warning` | a warning action in the page |
| `danger` | a negative action (such as Delete) on the page |
| `danger--primary` | a negative principle call to action (such as Delete) on the page |
| `link` | an optional action or navigation action out of the app changes root html tag from `<button>` to `<a>` |
<!-- Embed other stories to further illustrate component usage -->
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--types" />
</Canvas>
```
Nice work! You're now ready to start creating comprehensive documentation using storybook 🎉👍

View File

@ -0,0 +1,59 @@
import { Story, Canvas, ArgsTable } from '@storybook/addon-docs';
import Button from '.';
# Button
Buttons communicate actions that users can take.
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--default-story" />
</Canvas>
## Component API
<ArgsTable of={Button} />
## Usage
The following describes the props and example usage for this component.
### Type
By changing the `type` prop you can use different styles of the button.
| type | Description |
| ----------------- | ----------------------------------------------------------------------------------------------------- |
| `default` | default style of the button |
| `primary` | the principle call to action on the page |
| `secondary` | secondary actions on each page |
| `warning` | a warning action in the page |
| `danger` | a negative action (such as Delete) on the page |
| `danger--primary` | a negative principle call to action (such as Delete) on the page |
| `link` | an optional action or navigation action out of the app changes root html tag from `<button>` to `<a>` |
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--types" />
</Canvas>
### Link Type
By changing the `type` to `"link"` the root html element of the button changes from `<button>` to `<a>`.
Rendered html
```html
<a class="button btn-link" role="button" tabindex="0">Click me</a>
```
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--link-type" />
</Canvas>
### With Icon
Pass an icon component to `icon` prop to add an icon.
<Canvas>
<Story id="ui-components-ui-button-button-stories-js--with-icon" />
</Canvas>

View File

@ -1,69 +1,96 @@
import React from 'react';
import { action } from '@storybook/addon-actions';
import { text, boolean } from '@storybook/addon-knobs';
import BuyIcon from '../icon/overview-buy-icon.component';
import README from './README.mdx';
import Button from '.';
export default {
title: 'Button',
id: __filename,
component: Button,
parameters: {
docs: {
page: README,
},
},
argTypes: {
children: { control: 'text' },
disabled: { control: 'boolean' },
onClick: { action: 'clicked' },
type: {
control: {
type: 'select',
},
options: [
'default',
'primary',
'secondary',
'warning',
'danger',
'danger-primary',
'link',
],
},
submit: { control: 'boolean' },
large: { control: 'boolean' },
className: { control: 'text' },
icon: {
control: {
type: 'select',
},
options: ['BuyIcon'],
mapping: {
BuyIcon: <BuyIcon />,
},
},
},
};
export const primaryType = () => (
<Button
onClick={action('clicked')}
type="primary"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
</Button>
export const DefaultStory = (args) => (
<Button {...args}>{args.children}</Button>
);
export const secondaryType = () => (
<Button
onClick={action('clicked')}
type="secondary"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
</Button>
DefaultStory.storyName = 'Default';
DefaultStory.args = {
children: 'Default',
};
export const Types = (args) => (
<>
<Button {...args} type="default">
{args.children || 'Default'}
</Button>
<Button {...args} type="primary">
{args.children || 'Primary'}
</Button>
<Button {...args} type="secondary">
{args.children || 'Secondary'}
</Button>
<Button {...args} type="warning">
{args.children || 'Warning'}
</Button>
<Button {...args} type="danger">
{args.children || 'Danger'}
</Button>
<Button {...args} type="danger-primary">
{args.children || 'Danger primary'}
</Button>
<Button {...args} type="link">
{args.children || 'Link'}
</Button>
</>
);
export const defaultType = () => (
<Button
onClick={action('clicked')}
type="default"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
</Button>
);
export const LinkType = (args) => <Button {...args} type="link" />;
export const warningType = () => (
<Button
onClick={action('clicked')}
type="warning"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
</Button>
);
LinkType.args = {
children: 'Click me',
};
export const dangerType = () => (
<Button
onClick={action('clicked')}
type="danger"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
</Button>
);
export const dangerPrimaryType = () => (
<Button
onClick={action('clicked')}
type="danger-primary"
disabled={boolean('disabled', false)}
>
{text('text', 'Click me')}
export const WithIcon = (args) => (
<Button {...args} type="primary" icon={<BuyIcon />}>
{args.children || 'Buy'}
</Button>
);

View File

@ -27,6 +27,4 @@ export const DefaultStory = () => {
);
};
DefaultStory.story = {
name: 'Default',
};
DefaultStory.storyName = 'Default';

3666
yarn.lock

File diff suppressed because it is too large Load Diff