Skip to content

Commit

Permalink
chore: update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
marcolink committed Feb 11, 2024
1 parent c28c1ff commit b83ad9a
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 158 deletions.
244 changes: 98 additions & 146 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,191 +1,141 @@
# Storybook Addon Contentful Preview
Preview your components with contentful data

### Development scripts

- `npm run start` runs babel in watch mode and starts Storybook
- `npm run build` build and package your addon code

### Switch from TypeScript to JavaScript

Don't want to use TypeScript? We offer a handy eject command: `npm run eject-ts`

This will convert all code to JS. It is a destructive process, so we recommended running this before you start writing any code.

## What's included?

![Demo](https://user-images.githubusercontent.com/42671/107857205-e7044380-6dfa-11eb-8718-ad02e3ba1a3f.gif)

The addon code lives in `src`. It demonstrates all core addon related concepts. The three [UI paradigms](https://storybook.js.org/docs/react/addons/addon-types#ui-based-addons)

- `src/Tool.tsx`
- `src/Panel.tsx`
- `src/Tab.tsx`

Which, along with the addon itself, are registered in `src/manager.ts`.

Managing State and interacting with a story:

- `src/withGlobals.ts` & `src/Tool.tsx` demonstrates how to use `useGlobals` to manage global state and modify the contents of a Story.
- `src/withRoundTrip.ts` & `src/Panel.tsx` demonstrates two-way communication using channels.
- `src/Tab.tsx` demonstrates how to use `useParameter` to access the current story's parameters.

Your addon might use one or more of these patterns. Feel free to delete unused code. Update `src/manager.ts` and `src/preview.ts` accordingly.

Lastly, configure you addon name in `src/constants.ts`.

### Bundling
Preview your components with contentful data. Connect your storybook to contentful and [live preview](https://www.contentful.com/developers/docs/tutorials/general/live-preview/) your components with real
data.

Addons can interact with a Storybook project in multiple ways. It is recommended to familiarize yourself with [the basics](https://storybook.js.org/docs/react/addons/introduction) before getting started.

- Manager entries are used to add UI or behavior to the Storybook manager UI.
- Preview entries are used to add UI or behavior to the preview iframe where stories are rendered.
- Presets are used to modify the Storybook configuration, similar to how [users can configure their `main.ts` configurations](https://storybook.js.org/docs/react/api/main-config).

Since each of these places represents a different environment with different features and modules, it is also recommended to split and build your modules accordingly. This addon-kit comes with a preconfigured [bundling configuration](./tsup.config.ts) that supports this split, and you are free to modify and extend it as needed.

You can define which modules match which environments in the [`package.json#bundler`](./package.json) property:

- `exportEntries` is a list of module entries that users can manually import from anywhere they need to. For example, you could have decorators that users need to import into their `preview.ts` file or utility functions that can be used in their `main.ts` files.
- `managerEntries` is a list of module entries meant only for the manager UI. These modules will be bundled to ESM and won't include types since they are mostly loaded by Storybook directly.
- `previewEntries` is a list of module entries meant only for the preview UI. These modules will be bundled to ESM and won't include types since they are mostly loaded by Storybook directly.

Manager and preview entries are only used in the browser so they only output ESM modules. Export entries could be used both in the browser and in Node depending on their use case, so they both output ESM and CJS modules.

#### Globalized packages

Storybook provides a predefined set of packages that are available in the manager UI and the preview UI. In the final bundle of your addon, these packages should not be included. Instead, the imports should stay in place, allowing Storybook to replace those imports with the actual packages during the Storybook build process.

The list of packages differs between the manager and the preview, which is why there is a slight difference between `managerEntries` and `previewEntries`. Most notably, `react` and `react-dom` are prebundled in the manager but not in the preview. This means that your manager entries can use React to build UI without bundling it or having a direct reference to it. Therefore, it is safe to have React as a `devDependency` even though you are using it in production. _Requiring React as a peer dependency would unnecessarily force your users to install React._
## Installation

An exception to this rule is if you are using React to inject UI into the preview, which does not come prebundled with React. In such cases, you need to move `react` and `react-dom` to a peer dependency. However, we generally advise against this pattern since it would limit the usage of your addon to React-based Storybooks.
First, install the package.

### Metadata
```bash
npm install -D storybook-addon-contentful-preview
```

Storybook addons are listed in the [catalog](https://storybook.js.org/addons) and distributed via npm. The catalog is populated by querying npm's registry for Storybook-specific metadata in `package.json`. This project has been configured with sample data. Learn more about available options in the [Addon metadata docs](https://storybook.js.org/docs/react/addons/addon-catalog#addon-metadata).
Then, register it as an addon in `.storybook/main.{js|ts}`.

## Documentation
```ts
export default {
addons: ['storybook-addon-contentful-preview'],
};
```

To help the community use your addon and understand its capabilities, please document it thoroughly.
## Usage

To get started, replace this README with the content in this sample template, modeled after how essential addons (like [Actions](https://storybook.js.org/docs/essentials/actions)) are documented. Then update the content to describe your addon.
### Plugin
When registered, The plugin will automatically add the required decorators to your storybook.
You can then use the `contentfulPreview` parameter to connect your storybook to contentful. The decorators will be
ignored, if the `contentfulPreview` parameter is not set.

### Sample documentation template
### Manual
The decorators can also be used manually, if you want to have more control over the behavior.

````md
# My Addon
### Parameters

## Installation
This addon contributes the following parameters to Storybook, under the `contentfulPreview` namespace:

First, install the package.
| Name | Type | Description | Required |
|---------------|------------|------------------------------------------------------------------------------------------------------------|----------|
| `spaceId` | `string` | The space id of your contentful space | Yes |
| `accessToken` | `string` | The access token of your contentful space | Yes |
| `entryId` | `string` | The entry id of the content you want to preview | Yes |
| `locale` | `string` | The locale of the content you want to preview | No |
| `host` | `string` | The host of the contentful api (defaults to `api.contentful.com` | No |
| `livePreview` | `boolean` | Enables the live preview sdk | No |
| `argsMutator` | `function` | Mutator for the loaded entry data. By default, all fields will be populated as top-level args to the story | No |

```sh
npm install --save-dev my-addon
```
### Decorators

Then, register it as an addon in `.storybook/main.js`.
#### `withContentful`

```js
// .storybook/main.ts
When you want to preview your component with contentful data, you can use the `withContentful` decorator. This decorator
will fetch the data from contentful and pass it to your component.

// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
```ts
import {withContentful} from 'storybook-addon-contentful-preview';

const config: StorybookConfig = {
// ...rest of config
addons: [
'@storybook/addon-essentials'
'my-addon', // 👈 register the addon here
],
export default {
title: 'Button',
decorators: [withContentful],
parameters: {
contentful: {
spaceId: 'your-space',
accessToken: 'your-access-token',
entryId: 'your-entry-id',
}
}
};

export default config;
```

## Usage

The primary way to use this addon is to define the `exampleParameter` parameter. You can do this the
component level, as below, to affect all stories in the file, or you can do it for a single story.

```js
// Button.stories.ts
#### `withContentfulLivePreview`
When you want to preview your component with contentful data, you can use the `withContentfulLivePreview` decorator to enable the [live preview sdk](https://github.com/contentful/live-preview/). This decorator will fetch the data from contentful and pass it to your component when renderer inside the contentful UI.

// Replace your-framework with the name of your framework
import type { Meta } from '@storybook/your-framework';

import { Button } from './Button';
```ts
import {withContentful, withLivePreview} from 'storybook-addon-contentful-preview';

const meta: Meta<typeof Button> = {
component: Button,
export default {
title: 'Button',
decorators: [withLivePreview, withContentful],
parameters: {
myAddon: {
exampleParameter: true,
// See API section below for available parameters
contentful: {
spaceId: 'your-space',
accessToken: 'your-access-token',
entryId: 'your-entry-id',
livePreview: true,
}
}
};

export default meta;
```
> Only tested in conjunction with the `withContentful` decorator
Another way to use the addon is...

## API

### Parameters

This addon contributes the following parameters to Storybook, under the `myAddon` namespace:

#### `disable`

Type: `boolean`

Disable this addon's behavior. This parameter is most useful to allow overriding at more specific
levels. For example, if this parameter is set to true at the project level, it could then be
re-enabled by setting it to false at the meta (component) or story level.

### Options

When registering this addon, you can configure it with the following options, which are passed when
registering the addon, like so:
#### `withEntryArgMutator`

When you want to modify the loaded entry data, you can use the `withEntryArgMutator` decorator.
By default, the entry will be populated under `args.contentful_entry`. You can use this decorator to modify the loaded entry data before it is passed to your component.

```ts
// .storybook/main.ts

// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';

const config: StorybookConfig = {
// ...rest of config
addons: [
'@storybook/essentials',
{
name: 'my-addon',
options: {
// 👈 options for my-addon go here
},
},
],
};
import {withContentful, withEntryArgMutator} from 'storybook-addon-contentful-preview';

export default config;
export default {
title: 'Button',
decorators: [withEntryArgMutator, withContentful],
parameters: {
contentful: {
spaceId: 'your-space',
accessToken: 'your-access-token',
entryId: 'your-entry-id',
livePreview: true,
// optionally, you can use the argsMutator param to modify the default behaviour
argsMutator: (entry, args) => {
return {
...args,
// ...entry.fields <-- default behaviour
headline: entry.fields.title
}
}
}
}
};
```

#### `useExperimentalBehavior`

Type: `boolean`

Enable experimental behavior to...
## Development

````
### Development scripts

- `npm run start` runs babel in watch mode and starts Storybook
- `npm run build` build and package your addon code

## Release Management

### Setup

This project is configured to use [auto](https://github.com/intuit/auto) for release management. It generates a changelog and pushes it to both GitHub and npm. Therefore, you need to configure access to both:
This project is configured to use [auto](https://github.com/intuit/auto) for release management. It generates a
changelog and pushes it to both GitHub and npm. Therefore, you need to configure access to both:

- [`NPM_TOKEN`](https://docs.npmjs.com/creating-and-viewing-access-tokens#creating-access-tokens) Create a token with both _Read and Publish_ permissions.
- [`NPM_TOKEN`](https://docs.npmjs.com/creating-and-viewing-access-tokens#creating-access-tokens) Create a token with
both _Read and Publish_ permissions.
- [`GH_TOKEN`](https://github.com/settings/tokens) Create a token with the `repo` scope.

Then open your `package.json` and edit the following fields:
Expand All @@ -209,7 +159,8 @@ Lastly, **create labels on GitHub**. You’ll use these labels in the future whe
npx auto create-labels
```

If you check on GitHub, you’ll now see a set of labels that `auto` would like you to use. Use these to tag future pull requests.
If you check on GitHub, you’ll now see a set of labels that `auto` would like you to use. Use these to tag future pull
requests.

#### GitHub Actions

Expand All @@ -219,7 +170,8 @@ Go to `Settings > Secrets`, click `New repository secret`, and add your `NPM_TOK

### Creating a release

To create a release locally you can run the following command, otherwise the GitHub action will make the release for you.
To create a release locally you can run the following command, otherwise the GitHub action will make the release for
you.

```sh
npm run release
Expand Down
4 changes: 2 additions & 2 deletions src/contentful-decorator.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// chromatic.d.ts
import {ContentfulParameters} from "~/storybook-addon/withContentful";
import {PARAM_KEY} from "./constants";
import {ContentfulPreviewParameters} from "./types";

declare module '@storybook/types' {
interface Parameters {
[PARAM_KEY]?: Partial<ContentfulParameters>;
[PARAM_KEY]?: Partial<ContentfulPreviewParameters>;
}
}
4 changes: 2 additions & 2 deletions src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import type {ProjectAnnotations, Renderer} from "@storybook/types";
import {PARAM_KEY} from "./constants";
import {withContentful} from "./withContentful";
import {withArgsMutator} from "./withArgsMutator";
import {withEntryArgMutator} from "./withEntryArgMutator";
import {withLivePreview} from "./withLivePreview";

/**
Expand All @@ -22,7 +22,7 @@ import {withLivePreview} from "./withLivePreview";
const preview: ProjectAnnotations<Renderer> = {

// seems they are executed in reverse order
decorators: [withArgsMutator, withLivePreview, withContentful],
decorators: [withEntryArgMutator, withLivePreview, withContentful],
globals: {
[PARAM_KEY]: {
// Example of setting a default value for a global parameter
Expand Down
4 changes: 2 additions & 2 deletions src/stories/DebugComponent.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {Meta} from '@storybook/react';
import {StoryObj} from "@storybook/react";
import {ContentfulDebugComponent} from "./ContentfulDebugComponent";
import {withArgsMutator} from "../withArgsMutator";
import {withEntryArgMutator} from "../withEntryArgMutator";

const meta = {
title: 'ContentfulPreview/Debug',
Expand All @@ -14,7 +14,7 @@ type Story = StoryObj<typeof ContentfulDebugComponent>;
* render static data (if parameter `contentfulPreview` is not set),
*/
export const Static: Story = {
decorators: [withArgsMutator],
decorators: [withEntryArgMutator],
args: {
contentful_entry: {
sys: {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ export type ContentfulPreviewParameters = {
host: string,
debugMode: boolean,
entryId: string,
argsMutator: (args: Args) => Args
entryMutator: (args: Args) => Args
}
10 changes: 5 additions & 5 deletions src/withArgsMutator.tsx → src/withEntryArgMutator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,24 @@ export function defaultArgsMutator(entry: BaseEntry, args: Args): Args {
/*
* This decorator is used to pass the entry fields to the story args
*/
export const withArgsMutator = makeDecorator({
name: 'withArgsMutator',
export const withEntryArgMutator = makeDecorator({
name: 'withEntryArgMutator',
parameterName: PARAM_KEY,
skipIfNoParametersOrOptions: false,
wrapper: (
storyFn,
context,
{parameters = {}}: {
parameters: Partial<Pick<ContentfulPreviewParameters, 'argsMutator' | 'debugMode'>>
parameters: Partial<Pick<ContentfulPreviewParameters, 'entryMutator' | 'debugMode'>>
}
) => {
const globalContentfulPreview = context.parameters.globals[PARAM_KEY];
const debugMode = mergeParam([parameters.debugMode, globalContentfulPreview?.debugMode], false)
if(debugMode) {
console.log('🎨 Decorated with withArgsMutator')
console.log('🎨 Decorated with withEntryArgMutator')
}
if (isContentfulObject(context.args[PARAM_ENTRY])) {
const argsMutator = parameters?.argsMutator || defaultArgsMutator
const argsMutator = parameters?.entryMutator || defaultArgsMutator
context.args = argsMutator(context.args[PARAM_ENTRY], context.args)
}
return storyFn(context);
Expand Down

0 comments on commit b83ad9a

Please sign in to comment.