Skip to content

Commit

Permalink
Merge pull request #27517 from storybookjs/shilman/initial-globals
Browse files Browse the repository at this point in the history
CSF: Rename `preview.js` `globals` to `initialGlobals`
  • Loading branch information
shilman authored Jun 11, 2024
2 parents ba52208 + 8dbd2d3 commit 29f649b
Show file tree
Hide file tree
Showing 42 changed files with 460 additions and 174 deletions.
16 changes: 16 additions & 0 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 @@ -411,6 +413,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
2 changes: 1 addition & 1 deletion code/addons/backgrounds/src/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ export const parameters = {
},
};

export const globals = {
export const initialGlobals = {
[PARAM_KEY]: null as any,
};
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: 1 addition & 1 deletion code/addons/measure/src/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { PARAM_KEY } from './constants';

export const decorators: Addon_DecoratorFunction[] = [withMeasure];

export const globals = {
export const initialGlobals = {
[PARAM_KEY]: false,
};
2 changes: 1 addition & 1 deletion code/addons/outline/src/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { PARAM_KEY } from './constants';

export const decorators: Addon_DecoratorFunction[] = [withOutline];

export const globals = {
export const initialGlobals = {
[PARAM_KEY]: false,
};
2 changes: 1 addition & 1 deletion code/addons/viewport/src/preview.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const globals = { viewport: 'reset', viewportRotated: false };
export const initialGlobals = { viewport: 'reset', viewportRotated: false };
2 changes: 1 addition & 1 deletion code/addons/viewport/src/shortcuts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type API } from '@storybook/manager-api';
import { ADDON_ID } from './constants';
import { globals as defaultGlobals } from './preview';
import { initialGlobals as defaultGlobals } from './preview';

const getCurrentViewportIndex = (viewportsKeys: string[], current: string): number =>
viewportsKeys.indexOf(current);
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, 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();
});
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
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const docsRenderer = {
};
export const teardownrenderToCanvas: Mock<[TeardownRenderToCanvas]> = vi.fn();
export const projectAnnotations = {
globals: { a: 'b' },
initialGlobals: { a: 'b' },
globalTypes: {},
decorators: [vi.fn((s) => s())],
render: vi.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3353,7 +3353,7 @@ describe('PreviewWeb', () => {
return {
...projectAnnotations,
args: { global: 'added' },
globals: { a: 'edited' },
initialGlobals: { a: 'edited' },
decorators: [newGlobalDecorator],
};
};
Expand Down
8 changes: 4 additions & 4 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 } = this.projectAnnotations;

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

Expand All @@ -95,8 +95,8 @@ export class StoryStore<TRenderer extends Renderer> {
setProjectAnnotations(projectAnnotations: ProjectAnnotations<TRenderer>) {
// By changing `this.projectAnnotations, we implicitly invalidate the `prepareStoryWithCache`
this.projectAnnotations = normalizeProjectAnnotations(projectAnnotations);
const { globals, globalTypes } = projectAnnotations;
this.globals.set({ globals, globalTypes });
const { initialGlobals, globalTypes } = projectAnnotations;
this.globals.set({ globals: initialGlobals, globalTypes });
}

// This means that one of the CSF files has changed.
Expand Down
Loading

0 comments on commit 29f649b

Please sign in to comment.