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

feat: update globals with selected theme - react #63

Closed
wants to merge 1 commit into from
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
26 changes: 23 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const parameters = {
};
```

See the [storybook documentation](https://storybook.js.org/docs/addons/using-addons/#global-configuration) for more informations.
See the [storybook documentation](https://storybook.js.org/docs/addons/using-addons/#global-configuration) for more information.

### In story (Component Story Format)

Expand Down Expand Up @@ -201,7 +201,7 @@ Setup the decorator globally in the `preview.js` file:

```jsx
import { addDecorator } from '@storybook/react'; // <- or your storybook framework
import { withThemes } from 'storybook-addon-themes/react'; // <- or your storybook framework
import { withThemes } from 'storybook-addon-themes'; // <- or your storybook framework

addDecorator(withThemes);

Expand Down Expand Up @@ -273,7 +273,7 @@ storiesOf('StoriesOf|Button', module)

#### General

You can provide a component that will be used as decorator using the `Decorator` option in the `theme` parameter.
You can provide a component that will be used as decorator using the `Decorator` option in the `theme` parameter. This requires `withThemes` to be included in the storybook [`decorators`](https://storybook.js.org/docs/react/writing-stories/decorators) array.

The decorator will get the following properties :

Expand Down Expand Up @@ -341,9 +341,29 @@ function Decorator(props) {
};
```

### Globals - React only

Creating a storybook [decorator](https://storybook.js.org/docs/react/essentials/toolbars-and-globals#create-a-decorator) gives you access to the story context including [`globals`](https://storybook.js.org/docs/react/essentials/toolbars-and-globals#globals). This allows for accessing the selected theme name via `context.global.themes.value`.

```js
// .storybook/preview.js

import React from 'react';

export const decorators = [
(Story, context) => (
<div style={{ margin: '3em' }}>
<h1>Theme: {context.themes.value}</h1>
<Story />
</div>
),
];
```

## Framework Support Table

| | [React](app/react)|[React Native](app/react-native)|[Vue](app/vue)|[Angular](app/angular)| [Polymer](app/polymer)| [Mithril](app/mithril)| [HTML](app/html)| [Marko](app/marko)| [Svelte](app/svelte)| [Riot](app/riot)| [Ember](app/ember)| [Preact](app/preact)|
| ----------- |:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|
|Usage without decorator |+| |+|+|+|+|+|+|+|+|+|+|
|Usage with decorator |+| |+| | | |+| |+| | | |
|Usage with `context.globals` |+| | | | | | | | | | | |
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
},
"peerDependenciesMeta": {
"react": {
"react": "^16.8.0",
"optional": true
},
"svelte": {
Expand Down
149 changes: 81 additions & 68 deletions src/manager/ThemeSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import React, { Component, Fragment } from 'react';
import React, { FC, Fragment, useCallback, useEffect, useState } from 'react';
import memoize from 'memoizerific';

import { API } from '@storybook/api';
import { API, useGlobals, useParameter } from '@storybook/api';
import { SET_STORIES } from '@storybook/core-events';

import { Icons, IconButton, WithTooltip, TooltipLinkList } from '@storybook/components';

import { CHANGE, DECORATOR, THEME } from '../constants';
import { Theme, ThemeSelectorItem } from '../models';
import { getConfigFromApi, getSelectedTheme, getSelectedThemeName } from '../shared';
import { CHANGE, DECORATOR, PARAM_KEY, THEME } from '../constants';
import { Theme, ThemeConfig, ThemeSelectorItem } from '../models';
import { defaultOptions, getConfigFromApi, getSelectedTheme, getSelectedThemeName } from '../shared';

import { ColorIcon } from './ColorIcon';
import { ThemeStory } from './ThemeStory';
Expand Down Expand Up @@ -36,8 +36,8 @@ const createThemeSelectorItem = memoize(1000)(
);

const getDisplayableState = memoize(10)(
(props: ThemeToolProps, state: ThemeToolState, change) => {
const { clearable, list, target, default: defaultTheme } = getConfigFromApi(props.api);
(config: ThemeConfig, state: ThemeToolState, change) => {
const { clearable, list, target, default: defaultTheme } = config;
const selectedThemeName = getSelectedThemeName(list, defaultTheme, state.selected);

let availableThemeSelectorItems: ThemeSelectorItem[] = [];
Expand Down Expand Up @@ -78,77 +78,90 @@ interface ThemeToolState {
expanded: boolean;
}

export class ThemeSelector extends Component<ThemeToolProps, ThemeToolState> {
state: ThemeToolState = {
decorator: false,
selected: null,
expanded: false,
};
export const ThemeSelector: FC<ThemeToolProps> = ({ api }) => {
const [decorator, setDecorator] = useState(false);
const [expanded, setExpanded] = useState(false);
const [globals, updateGlobals] = useGlobals();

private setStories = () => this.setState({ selected: null });
const themesConfig = useParameter<ThemeConfig>(
PARAM_KEY,
defaultOptions
);
const selected: string = globals[PARAM_KEY]?.value;

private setTheme = (theme: string) => this.setState({ selected: theme });
const setSelected = useCallback(
(value: string) => {
updateGlobals({ [PARAM_KEY]: { ...globals[PARAM_KEY], value } });
},
[themesConfig, globals, updateGlobals]
);

private setDecorator = () => this.setState({ decorator: true });
const clearSelection = () => setSelected(null);
const setDecoratorTrue = () => setDecorator(true);

componentDidMount() {
const { api } = this.props;
api.on(SET_STORIES, this.setStories);
api.on(THEME, this.setTheme);
api.on(DECORATOR, this.setDecorator);
}
const change = (args: { selected: string; expanded: boolean }) => {
const { list, onChange } = getConfigFromApi(api);

componentWillUnmount() {
const { api } = this.props;
api.off(SET_STORIES, this.setStories);
api.off(THEME, this.setTheme);
api.off(DECORATOR, this.setDecorator);
}
setExpanded(args.expanded);

api.emit(CHANGE, args.selected);

change = (args: { selected: string; expanded: boolean }) => {
const { selected } = args;
const { api } = this.props;
const { list, onChange } = getConfigFromApi(api);
this.setState(args);
api.emit(CHANGE, selected);
if (typeof onChange === 'function') {
const selectedTheme = getSelectedTheme(list, selected);
const selectedTheme = getSelectedTheme(list, args.selected);
onChange(selectedTheme);
}

setSelected(args.selected);
};

render() {
const { decorator, expanded } = this.state;
const { items, selectedTheme, target, themes } = getDisplayableState(
this.props,
this.state,
this.change
);

return items.length ? (
<Fragment>
{!decorator && (
<ThemeStory iframeId={iframeId} selectedTheme={selectedTheme} target={target} themes={themes} />
)}
<WithTooltip
placement="top"
trigger="click"
tooltipShown={expanded}
onVisibilityChange={(newVisibility: boolean) =>
this.setState({ expanded: newVisibility })
}
tooltip={<TooltipLinkList links={items} />}
closeOnClick
const { items, selectedTheme, target, themes } = getDisplayableState(
themesConfig,
{
decorator,
selected,
expanded,
},
change
);

useEffect(() => {
api.on(SET_STORIES, clearSelection);
api.on(THEME, setSelected);
api.on(DECORATOR, setDecoratorTrue);

if (!selected) {
const selectedName = getSelectedThemeName(themesConfig.list, themesConfig.default)
setSelected(selectedName);
}

return () => {
api.off(SET_STORIES, clearSelection);
api.off(THEME, setSelected);
api.off(DECORATOR, setDecoratorTrue);
}
}, [clearSelection, setSelected, setDecoratorTrue]);

return items.length ? (
<Fragment>
{!decorator && (
<ThemeStory iframeId={iframeId} selectedTheme={selectedTheme} target={target} themes={themes} />
)}
<WithTooltip
placement="top"
trigger="click"
tooltipShown={expanded}
onVisibilityChange={setExpanded}
tooltip={<TooltipLinkList links={items} />}
closeOnClick
>
<IconButton
key="theme"
active={selectedTheme}
title="Change the theme of the preview"
>
<IconButton
key="theme"
active={selectedTheme}
title="Change the theme of the preview"
>
<Icons icon="photo" />
</IconButton>
</WithTooltip>
</Fragment>
) : null;
}
<Icons icon="photo" />
</IconButton>
</WithTooltip>
</Fragment>
) : null;
}
2 changes: 1 addition & 1 deletion src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { API } from '@storybook/api';
import { PARAM_KEY } from './constants';
import { Theme, ThemeConfig } from './models';

const defaultOptions: ThemeConfig = {
export const defaultOptions: ThemeConfig = {
clearable: true,
list: []
};
Expand Down