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

Next.js: Add portable stories API #26142

Merged
Merged
Show file tree
Hide file tree
Changes from 6 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
6 changes: 3 additions & 3 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ workflows:
- build
matrix:
parameters:
directory: ["react", "vue3"]
directory: ["react", "vue3", "nextjs"]
# TODO: reenable once we find out the source of flakyness
# - test-runner-dev:
# requires:
Expand Down Expand Up @@ -727,7 +727,7 @@ workflows:
- build
matrix:
parameters:
directory: ["react", "vue3"]
directory: ["react", "vue3", "nextjs"]
- bench:
parallelism: 5
requires:
Expand Down Expand Up @@ -790,7 +790,7 @@ workflows:
- build
matrix:
parameters:
directory: ["react", "vue3"]
directory: ["react", "vue3", "nextjs"]
- test-empty-init:
requires:
- build
Expand Down
1 change: 1 addition & 0 deletions code/frameworks/nextjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './types';
export * from './portable-stories';
131 changes: 131 additions & 0 deletions code/frameworks/nextjs/src/portable-stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import {
composeStory as originalComposeStory,
composeStories as originalComposeStories,
setProjectAnnotations as originalSetProjectAnnotations,
} from '@storybook/preview-api';
import type {
Args,
ProjectAnnotations,
StoryAnnotationsOrFn,
Store_CSFExports,
StoriesWithPartialProps,
} from '@storybook/types';

import {
render as reactRenderFn,
parameters as reactParameters,
} from '../../../renderers/react/src/entry-preview';
import * as nextJsAnnotations from './preview';

import type { ReactRenderer, Meta } from '@storybook/react';

/** Function that sets the globalConfig of your storybook. The global config is the preview module of your .storybook folder.
*
* It should be run a single time, so that your global config (e.g. decorators) is applied to your stories when using `composeStories` or `composeStory`.
*
* Example:
*```jsx
* // setup.js (for jest)
* import { setProjectAnnotations } from '@storybook/react';
JReinhold marked this conversation as resolved.
Show resolved Hide resolved
* import projectAnnotations from './.storybook/preview';
*
* setProjectAnnotations(projectAnnotations);
*```
*
* @param projectAnnotations - e.g. (import projectAnnotations from '../.storybook/preview')
*/
export function setProjectAnnotations(
projectAnnotations: ProjectAnnotations<ReactRenderer> | ProjectAnnotations<ReactRenderer>[]
) {
originalSetProjectAnnotations<ReactRenderer>(projectAnnotations);
}

// This will not be necessary once we have auto preset loading
const defaultProjectAnnotations: ProjectAnnotations<ReactRenderer> = {
...nextJsAnnotations,
render: reactRenderFn,
parameters: {
...nextJsAnnotations.parameters,
...reactParameters,
},
};

/**
* Function that will receive a story along with meta (e.g. a default export from a .stories file)
* and optionally projectAnnotations e.g. (import * from '../.storybook/preview)
* and will return a composed component that has all args/parameters/decorators/etc combined and applied to it.
*
*
* It's very useful for reusing a story in scenarios outside of Storybook like unit testing.
*
* Example:
*```jsx
* import { render } from '@testing-library/react';
* import { composeStory } from '@storybook/react';
JReinhold marked this conversation as resolved.
Show resolved Hide resolved
* import Meta, { Primary as PrimaryStory } from './Button.stories';
*
* const Primary = composeStory(PrimaryStory, Meta);
*
* test('renders primary button with Hello World', () => {
* const { getByText } = render(<Primary>Hello world</Primary>);
* expect(getByText(/Hello world/i)).not.toBeNull();
* });
*```
*
* @param story
* @param componentAnnotations - e.g. (import Meta from './Button.stories')
* @param [projectAnnotations] - e.g. (import * as projectAnnotations from '../.storybook/preview') this can be applied automatically if you use `setProjectAnnotations` in your setup files.
* @param [exportsName] - in case your story does not contain a name and you want it to have a name.
*/
export function composeStory<TArgs extends Args = Args>(
story: StoryAnnotationsOrFn<ReactRenderer, TArgs>,
componentAnnotations: Meta<TArgs | any>,
projectAnnotations?: ProjectAnnotations<ReactRenderer>,
exportsName?: string
) {
return originalComposeStory<ReactRenderer, TArgs>(
story as StoryAnnotationsOrFn<ReactRenderer, Args>,
componentAnnotations,
projectAnnotations,
defaultProjectAnnotations,
exportsName
);
}

/**
* Function that will receive a stories import (e.g. `import * as stories from './Button.stories'`)
* and optionally projectAnnotations (e.g. `import * from '../.storybook/preview`)
* and will return an object containing all the stories passed, but now as a composed component that has all args/parameters/decorators/etc combined and applied to it.
*
*
* It's very useful for reusing stories in scenarios outside of Storybook like unit testing.
*
* Example:
*```jsx
* import { render } from '@testing-library/react';
* import { composeStories } from '@storybook/react';
JReinhold marked this conversation as resolved.
Show resolved Hide resolved
* import * as stories from './Button.stories';
*
* const { Primary, Secondary } = composeStories(stories);
*
* test('renders primary button with Hello World', () => {
* const { getByText } = render(<Primary>Hello world</Primary>);
* expect(getByText(/Hello world/i)).not.toBeNull();
* });
*```
*
* @param csfExports - e.g. (import * as stories from './Button.stories')
* @param [projectAnnotations] - e.g. (import * as projectAnnotations from '../.storybook/preview') this can be applied automatically if you use `setProjectAnnotations` in your setup files.
*/
export function composeStories<TModule extends Store_CSFExports<ReactRenderer, any>>(
csfExports: TModule,
projectAnnotations?: ProjectAnnotations<ReactRenderer>
) {
// @ts-expect-error (Converted from ts-ignore)
const composedStories = originalComposeStories(csfExports, projectAnnotations, composeStory);

return composedStories as unknown as Omit<
StoriesWithPartialProps<ReactRenderer, TModule>,
keyof Store_CSFExports
>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
36 changes: 36 additions & 0 deletions test-storybooks/portable-stories-kitchen-sink/nextjs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { StorybookConfig } from "@storybook/nextjs";

const config: StorybookConfig = {
stories: ["../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
addons: [
"@storybook/addon-essentials",
"@storybook/addon-interactions"
],
framework: {
name: "@storybook/nextjs",
options: {},
},
};
export default config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React from 'react';
import type { Preview } from '@storybook/react';

console.log('preview file is called!');

const preview: Preview = {
decorators: [
(StoryFn) => (
<div data-testid="global-decorator">
Global Decorator
<br />
{StoryFn()}
</div>
),
],
globalTypes: {
locale: {
description: 'Locale for components',
defaultValue: 'en',
toolbar: {
title: 'Locale',
icon: 'circlehollow',
items: ['es', 'en'],
},
},
},
};

export default preview;
40 changes: 40 additions & 0 deletions test-storybooks/portable-stories-kitchen-sink/nextjs/README.md
Copy link
Contributor

Choose a reason for hiding this comment

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

let's delete this to not cause confusion.

Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const nextJest = require('next/jest.js');

const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: __dirname
})

// Add any custom config to be passed to Jest
const config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
setupFilesAfterEnv: ['@testing-library/jest-dom'],
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(config)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};

export default nextConfig;
Loading
Loading