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

CSF: Rename preview.js globals to initialGlobals #27517

Merged
merged 17 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
49 changes: 33 additions & 16 deletions MIGRATION.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<h1>Migration</h1>

- [From version 8.1.x to 8.2.x](#from-version-81x-to-82x)
- [Preview.js globals renamed to initialGlobals](#previewjs-globals-renamed-to-initialglobals)
- [From version 8.0.x to 8.1.x](#from-version-80x-to-81x)
- [Portable stories](#portable-stories)
- [@storybook/nextjs requires specific path aliases to be setup](#storybooknextjs-requires-specific-path-aliases-to-be-setup)
Expand Down Expand Up @@ -97,17 +99,17 @@
- [Tab addons cannot manually route, Tool addons can filter their visibility via tabId](#tab-addons-cannot-manually-route-tool-addons-can-filter-their-visibility-via-tabid)
- [Removed `config` preset](#removed-config-preset-1)
- [From version 7.5.0 to 7.6.0](#from-version-750-to-760)
- [CommonJS with Vite is deprecated](#commonjs-with-vite-is-deprecated)
- [Using implicit actions during rendering is deprecated](#using-implicit-actions-during-rendering-is-deprecated)
- [typescript.skipBabel deprecated](#typescriptskipbabel-deprecated)
- [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop)
- [Addons no longer need a peer dependency on React](#addons-no-longer-need-a-peer-dependency-on-react)
- [CommonJS with Vite is deprecated](#commonjs-with-vite-is-deprecated)
- [Using implicit actions during rendering is deprecated](#using-implicit-actions-during-rendering-is-deprecated)
- [typescript.skipBabel deprecated](#typescriptskipbabel-deprecated)
- [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop)
- [Addons no longer need a peer dependency on React](#addons-no-longer-need-a-peer-dependency-on-react)
- [From version 7.4.0 to 7.5.0](#from-version-740-to-750)
- [`storyStoreV6` and `storiesOf` is deprecated](#storystorev6-and-storiesof-is-deprecated)
- [`storyIndexers` is replaced with `experimental_indexers`](#storyindexers-is-replaced-with-experimental_indexers)
- [`storyStoreV6` and `storiesOf` is deprecated](#storystorev6-and-storiesof-is-deprecated)
- [`storyIndexers` is replaced with `experimental_indexers`](#storyindexers-is-replaced-with-experimental_indexers)
- [From version 7.0.0 to 7.2.0](#from-version-700-to-720)
- [Addon API is more type-strict](#addon-api-is-more-type-strict)
- [Addon-controls hideNoControlsWarning parameter is deprecated](#addon-controls-hidenocontrolswarning-parameter-is-deprecated)
- [Addon API is more type-strict](#addon-api-is-more-type-strict)
- [Addon-controls hideNoControlsWarning parameter is deprecated](#addon-controls-hidenocontrolswarning-parameter-is-deprecated)
- [From version 6.5.x to 7.0.0](#from-version-65x-to-700)
- [7.0 breaking changes](#70-breaking-changes)
- [Dropped support for Node 15 and below](#dropped-support-for-node-15-and-below)
Expand All @@ -133,7 +135,7 @@
- [Deploying build artifacts](#deploying-build-artifacts)
- [Dropped support for file URLs](#dropped-support-for-file-urls)
- [Serving with nginx](#serving-with-nginx)
- [Ignore story files from node\_modules](#ignore-story-files-from-node_modules)
- [Ignore story files from node_modules](#ignore-story-files-from-node_modules)
- [7.0 Core changes](#70-core-changes)
- [7.0 feature flags removed](#70-feature-flags-removed)
- [Story context is prepared before for supporting fine grained updates](#story-context-is-prepared-before-for-supporting-fine-grained-updates)
Expand All @@ -147,7 +149,7 @@
- [Addon-interactions: Interactions debugger is now default](#addon-interactions-interactions-debugger-is-now-default)
- [7.0 Vite changes](#70-vite-changes)
- [Vite builder uses Vite config automatically](#vite-builder-uses-vite-config-automatically)
- [Vite cache moved to node\_modules/.cache/.vite-storybook](#vite-cache-moved-to-node_modulescachevite-storybook)
- [Vite cache moved to node_modules/.cache/.vite-storybook](#vite-cache-moved-to-node_modulescachevite-storybook)
- [7.0 Webpack changes](#70-webpack-changes)
- [Webpack4 support discontinued](#webpack4-support-discontinued)
- [Babel mode v7 exclusively](#babel-mode-v7-exclusively)
Expand Down Expand Up @@ -197,7 +199,7 @@
- [Dropped addon-docs manual babel configuration](#dropped-addon-docs-manual-babel-configuration)
- [Dropped addon-docs manual configuration](#dropped-addon-docs-manual-configuration)
- [Autoplay in docs](#autoplay-in-docs)
- [Removed STORYBOOK\_REACT\_CLASSES global](#removed-storybook_react_classes-global)
- [Removed STORYBOOK_REACT_CLASSES global](#removed-storybook_react_classes-global)
- [7.0 Deprecations and default changes](#70-deprecations-and-default-changes)
- [storyStoreV7 enabled by default](#storystorev7-enabled-by-default)
- [`Story` type deprecated](#story-type-deprecated)
Expand Down Expand Up @@ -410,6 +412,20 @@
- [Packages renaming](#packages-renaming)
- [Deprecated embedded addons](#deprecated-embedded-addons)

## From version 8.1.x to 8.2.x

### Preview.js globals renamed to initialGlobals

Starting in 8.2 `preview.js` `globals` are deprecated and have been renamed to `initialGlobals`. We will remove `preview.js` `globals` in 9.0.

```diff
// .storybook/preview.js
export default {
- globals: [ a: 1, b: 2 ],
+ initiaGlobals: [ a: 1, b: 2 ],
}
```

## From version 8.0.x to 8.1.x

### Portable stories
Expand Down Expand Up @@ -439,6 +455,7 @@ The `docs.autodocs` setting in `main.js` is deprecated in 8.1 and will be remove
It has been replaced with a tags-based system which is more flexible than before.

`docs.autodocs` takes three values:

- `true`: generate autodocs for every component
- `false`: don't generate autodocs at all
- `tag`: generate autodocs for components that have been tagged `'autodocs'`.
Expand All @@ -448,8 +465,8 @@ Starting in 8.1, to generate autodocs for every component (`docs.autodocs = true
```js
// .storybook/preview.js
export default {
tags: ['autodocs'],
}
tags: ["autodocs"],
};
```

Tags cascade, so setting `'autodocs'` at the project level automatically propagates to every component and story. If you set autodocs globally and want to opt-out for a particular component, you can remove the `'autodocs'` tag for a component like this:
Expand All @@ -458,8 +475,8 @@ Tags cascade, so setting `'autodocs'` at the project level automatically propaga
// Button.stories.ts
export default {
component: Button,
tags: ['!autodocs'],
}
tags: ["!autodocs"],
};
```

If you had set `docs.autodocs = 'tag'`, the default setting, you can remove the setting from `.storybook/main.js`. That is now the default behavior.
Expand Down
2 changes: 1 addition & 1 deletion code/addons/links/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/addon-bundle.ts"
},
"dependencies": {
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/global": "^5.0.0",
"ts-dedent": "^2.0.0"
},
Expand Down
2 changes: 2 additions & 0 deletions code/lib/cli/src/automigrate/fixes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { addonPostCSS } from './addon-postcss';
import { vta } from './vta';
import { upgradeStorybookRelatedDependencies } from './upgrade-storybook-related-dependencies';
import { autodocsTags } from './autodocs-tags';
import { initialGlobals } from './initial-globals';

export * from '../types';

Expand Down Expand Up @@ -62,6 +63,7 @@ export const allFixes: Fix[] = [
upgradeStorybookRelatedDependencies,
vta,
autodocsTags,
initialGlobals,
];

export const initFixes: Fix[] = [eslintPlugin];
33 changes: 33 additions & 0 deletions code/lib/cli/src/automigrate/fixes/initial-globals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable no-underscore-dangle */
import { vi, describe, expect, it } from 'vitest';
import path from 'path';
import * as fsExtra from 'fs-extra';
import { initialGlobals } from './initial-globals';

vi.mock('fs-extra', async () => import('../../../../../__mocks__/fs-extra'));

const previewConfigPath = path.join('.storybook', 'preview.js');
const check = async (previewContents: string) => {
vi.mocked<typeof import('../../../../../__mocks__/fs-extra')>(fsExtra as any).__setMockFiles({
[previewConfigPath]: previewContents,
});
return initialGlobals.check({
packageManager: {} as any,
configDir: '',
mainConfig: {} as any,
storybookVersion: '8.0',
previewConfigPath,
});
};

it('no globals setting', async () => {
await expect(check(`export default { tags: ['a', 'b']}`)).resolves.toBeFalsy();
});

it('initialGlobals setting', async () => {
await expect(check(`export default { initialGlobals: { a: 1 } }`)).resolves.toBeFalsy();
});

it('globals setting', async () => {
await expect(check(`export default { globals: { a: 1 } }`)).resolves.toBeTruthy();
});
tmeasday marked this conversation as resolved.
Show resolved Hide resolved
52 changes: 52 additions & 0 deletions code/lib/cli/src/automigrate/fixes/initial-globals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { dedent } from 'ts-dedent';
import chalk from 'chalk';
import { readFile, writeFile } from 'fs-extra';
import type { Expression } from '@babel/types';
import type { ConfigFile } from '@storybook/csf-tools';
import { loadConfig, formatConfig } from '@storybook/csf-tools';
import type { Fix } from '../types';

const MIGRATION =
'https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#previewjs-globals-renamed-to-initialglobals';

interface Options {
previewConfig: ConfigFile;
previewConfigPath: string;
globals: Expression;
}

/**
* Rename preview.js globals to initialGlobals
*/
export const initialGlobals: Fix<Options> = {
id: 'initial-globals',
versionRange: ['*.*.*', '>=8.0.*'],
async check({ previewConfigPath }) {
if (!previewConfigPath) return null;

const previewConfig = loadConfig((await readFile(previewConfigPath)).toString()).parse();
const globals = previewConfig.getFieldNode(['globals']) as Expression;
if (!globals) return null;

return { globals, previewConfig, previewConfigPath };
},

prompt({ previewConfigPath }) {
return dedent`
The ${chalk.cyan('globals')} setting in ${chalk.cyan(previewConfigPath)} is deprecated
and has been renamed to ${chalk.cyan('initialGlobals')}.

Learn more: ${chalk.yellow(MIGRATION)}

Rename ${chalk.cyan('globals')} to ${chalk.cyan('initalGlobals')}?
`;
},

async run({ dryRun, result }) {
result.previewConfig.removeField(['globals']);
result.previewConfig.setFieldNode(['initialGlobals'], result.globals);
if (!dryRun) {
await writeFile(result.previewConfigPath, formatConfig(result.previewConfig));
}
},
};
2 changes: 1 addition & 1 deletion code/lib/codemod/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"@babel/core": "^7.24.4",
"@babel/preset-env": "^7.24.4",
"@babel/types": "^7.24.0",
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/csf-tools": "workspace:*",
"@storybook/node-logger": "workspace:*",
"@storybook/types": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion code/lib/core-events/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts"
},
"dependencies": {
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"ts-dedent": "^2.0.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion code/lib/core-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@storybook/channels": "workspace:*",
"@storybook/core-common": "workspace:*",
"@storybook/core-events": "workspace:*",
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/csf-tools": "workspace:*",
"@storybook/docs-mdx": "3.1.0-next.0",
"@storybook/global": "^5.0.0",
Expand Down
2 changes: 1 addition & 1 deletion code/lib/csf-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"@babel/parser": "^7.24.4",
"@babel/traverse": "^7.24.1",
"@babel/types": "^7.24.0",
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/types": "workspace:*",
"fs-extra": "^11.1.0",
"recast": "^0.23.5",
Expand Down
36 changes: 36 additions & 0 deletions code/lib/csf-tools/src/ConfigFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,42 @@ describe('ConfigFile', () => {
};
`);
});
it('root globals as variable', () => {
expect(
removeField(
['globals'],
dedent`
const preview = { globals: { a: 1 }, bar: { a: 1 } };
export default preview;
`
)
).toMatchInlineSnapshot(`
const preview = {
bar: { a: 1 }
};
export default preview;
`);
});

it('root globals satsifies as variable', () => {
expect(
removeField(
['globals'],
dedent`
const preview = {
globals: { a: 1 },
bar: { a: 1 }
} satisfies Foo;
export default preview;
`
)
).toMatchInlineSnapshot(`
const preview = {
bar: { a: 1 }
} satisfies Foo;
export default preview;
`);
});
});

describe('quotes', () => {
Expand Down
17 changes: 13 additions & 4 deletions code/lib/csf-tools/src/ConfigFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,10 +493,19 @@ export class ConfigFile {
}
}
// default export
if (t.isExportDefaultDeclaration(node) && t.isObjectExpression(node.declaration)) {
const properties = node.declaration.properties as t.ObjectProperty[];
removeProperty(properties, path[0]);
removedRootProperty = true;
if (t.isExportDefaultDeclaration(node)) {
let decl: t.Expression | undefined | null = node.declaration as t.Expression;
if (t.isIdentifier(decl)) {
decl = _findVarInitialization(decl.name, this._ast.program);
}
if (t.isTSAsExpression(decl) || t.isTSSatisfiesExpression(decl)) {
decl = decl.expression;
}
if (t.isObjectExpression(decl)) {
const properties = decl.properties as t.ObjectProperty[];
removeProperty(properties, path[0]);
removedRootProperty = true;
}
}
// module.exports
if (
Expand Down
2 changes: 1 addition & 1 deletion code/lib/manager-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"@storybook/channels": "workspace:*",
"@storybook/client-logger": "workspace:*",
"@storybook/core-events": "workspace:*",
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/global": "^5.0.0",
"@storybook/icons": "^1.2.5",
"@storybook/router": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion code/lib/preview-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"@storybook/channels": "workspace:*",
"@storybook/client-logger": "workspace:*",
"@storybook/core-events": "workspace:*",
"@storybook/csf": "^0.1.7",
"@storybook/csf": "^0.1.8",
"@storybook/global": "^5.0.0",
"@storybook/types": "workspace:*",
"@types/qs": "^6.9.5",
Expand Down
4 changes: 2 additions & 2 deletions code/lib/preview-api/src/modules/store/StoryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ export class StoryStore<TRenderer extends Renderer> {
this.storyIndex = new StoryIndexStore(storyIndex);

this.projectAnnotations = normalizeProjectAnnotations(projectAnnotations);
const { globals, globalTypes } = projectAnnotations;
const { initialGlobals, globalTypes } = projectAnnotations;

this.args = new ArgsStore();
this.globals = new GlobalsStore({ globals, globalTypes });
this.globals = new GlobalsStore({ globals: initialGlobals, globalTypes });
this.hooks = {};
this.cleanupCallbacks = {};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type {
ProjectAnnotations,
NormalizedProjectAnnotations,
} from '@storybook/types';
import { once } from '@storybook/client-logger';
import { dedent } from 'ts-dedent';

import { inferArgTypes } from '../inferArgTypes';
import { inferControls } from '../inferControls';
Expand All @@ -17,8 +19,18 @@ export function normalizeProjectAnnotations<TRenderer extends Renderer>({
decorators,
loaders,
beforeEach,
globals,
initialGlobals,
...annotations
}: ProjectAnnotations<TRenderer>): NormalizedProjectAnnotations<TRenderer> {
if (globals) {
once.warn(dedent`
The preview.js 'globals' field is deprecated and will be removed in Storybook 9.0.
Please use 'initialGlobals' instead. Learn more:

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#previewjs-globals-renamed-to-initialglobals
`);
}
return {
...(argTypes && { argTypes: normalizeInputTypes(argTypes as ArgTypes) }),
...(globalTypes && { globalTypes: normalizeInputTypes(globalTypes) }),
Expand All @@ -34,6 +46,7 @@ export function normalizeProjectAnnotations<TRenderer extends Renderer>({
// compatibility reasons, we will leave this in the store until 7.0
inferControls,
],
initialGlobals: initialGlobals ?? globals,
...annotations,
};
}
Loading
Loading