Skip to content

Commit

Permalink
Merge pull request #25789 from storybookjs/version-non-patch-from-8.0…
Browse files Browse the repository at this point in the history
….0-alpha.15

Release: Prerelease 8.0.0-alpha.16
  • Loading branch information
shilman authored Jan 30, 2024
2 parents 241dee7 + d36c9b9 commit f701a28
Show file tree
Hide file tree
Showing 26 changed files with 251 additions and 142 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.prerelease.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 8.0.0-alpha.16

- CLI: Fix `upgrade` detecting the wrong version of existing Storybooks - [#25752](https://github.com/storybookjs/storybook/pull/25752), thanks [@JReinhold](https://github.com/JReinhold)!
- CLI: Update init for react native v7 - [#25780](https://github.com/storybookjs/storybook/pull/25780), thanks [@dannyhw](https://github.com/dannyhw)!
- UI: Improve how the addon panel work on mobile - [#25787](https://github.com/storybookjs/storybook/pull/25787), thanks [@cdedreuille](https://github.com/cdedreuille)!

## 8.0.0-alpha.15

- Next.js: Add logger statements for compiler selection - [#25755](https://github.com/storybookjs/storybook/pull/25755), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)!
Expand Down
2 changes: 1 addition & 1 deletion CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
/code/addons/measure/ @yannbf @valentinpalkovic
/code/addons/outline/ @yannbf @valentinpalkovic
/code/addons/storysource/ @ndelangen
/code/addons/themes/ @JReinhold @Integrayshaun
/code/addons/themes/ @JReinhold @yannbf
/code/addons/toolbars/ @ndelangen @JReinhold
/code/addons/viewport/ @yannbf @ndelangen

Expand Down
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2017 Kadira Inc. <[email protected]>
Copyright (c) 2024 Storybook

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
1 change: 1 addition & 0 deletions code/addons/themes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ For tool-specific setup, check out the recipes below
- [`@emotion/styled`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/emotion.md)
- [`@mui/material`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/material-ui.md)
- [`bootstrap`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/bootstrap.md)
- [`postcss`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/postcss.md)
- [`styled-components`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/styled-components.md)
- [`tailwind`](https://github.com/storybookjs/storybook/tree/next/code/addons/themes/docs/getting-started/tailwind.md)
- [`[email protected]`](https://github.com/storybookjs/storybook/blob/next/code/addons/themes/docs/api.md#writing-a-custom-decorator)
Expand Down
114 changes: 114 additions & 0 deletions code/addons/themes/docs/getting-started/postcss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# 🏁 Getting started with `postcss`

## 📦 Install addon

To get started, **install the package** as a dev dependency

yarn:

```zsh
yarn add -D @storybook/addon-themes postcss-dark-theme-class
```

npm:

```zsh
npm install -D @storybook/addon-themes postcss-dark-theme-class
```

pnpm:

```zsh
pnpm add -D @storybook/addon-themes postcss-dark-theme-class
```

## 🧩 Register Addon

Now, **include the addon** in your `.storybook/main.js` file.

```diff
module.exports = {
stories: [
"../stories/**/*.stories.mdx",
"../stories/**/*.stories.@(js|jsx|ts|tsx)",
],
addons: [
"@storybook/addon-essentials",
+ "@storybook/addon-themes"
],
};
```

## 🏷️ Add class to `prefers-color-scheme` media

CSS has special media at-rule for dark theme: `@media (prefers-color-scheme: dark)`. [`postcss-dark-theme-class`](https://github.com/postcss/postcss-dark-theme-class) can copy content of those at-rules to `.is-dark` selector.

Check your project for existing PostCSS config: `postcss.config.js` in the project root, `"postcss"` section in `package.json` or postcss in bundle config.

Add plugin to the list.

```diff
module.exports = {
plugins: [
+ require('postcss-dark-theme-class'),
require('autoprefixer')
]
}
```

Use `prefers-color-scheme` media in your CSS:

```css
:root {
--text-color: black;
}
@media (prefers-color-scheme: dark) {
html {
--text-color: white
}
}
```

## 🥾 Import your CSS

To give your stories access to styles, import them into your `.storybook/preview.js` file.

```diff
import { Preview } from "@storybook/your-renderer";

+import "../src/index.css";

const preview: Preview = {
parameters: { /* ... */ },
};

export default preview;
```

## 🎨 Provide your theme(s)

To enable switching between these modes in a click for your stories, use our `withThemeByClassName` decorator by adding the following code to your `.storybook/preview.js` file.

```diff
-import { Preview } from "@storybook/your-renderer";
+import { Preview, Renderer } from "@storybook/your-renderer";
+import { withThemeByClassName } from "@storybook/addon-themes";

import "../src/index.css";


const preview: Preview = {
parameters: { /* ... */ },
+ decorators: [
+ withThemeByClassName<Renderer>({
+ themes: {
+ light: "is-light",
+ dark: "is-dark",
+ },
+ defaultTheme: "light",
+ }),
+ ]
};

export default preview;
```
14 changes: 8 additions & 6 deletions code/lib/cli/src/generators/REACT_NATIVE/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const generator = async (

const missingReactDom =
!packageJson.dependencies['react-dom'] && !packageJson.devDependencies['react-dom'];

const reactVersion = packageJson.dependencies.react;

const packagesToResolve = [
Expand All @@ -24,25 +25,26 @@ const generator = async (
'@storybook/react-native',
];

// change these to latest version once v6 stable is released
const packagesWithFixedVersion = [
'@storybook/addon-actions@^6.5.16',
'@storybook/addon-controls@^6.5.16',
];
const packagesWithFixedVersion: string[] = [];

const versionedPackages = await packageManager.getVersionedPackages(packagesToResolve);

const babelDependencies = await getBabelDependencies(packageManager, packageJson);

const packages: string[] = [];

packages.push(...babelDependencies);

packages.push(...packagesWithFixedVersion);

packages.push(...versionedPackages);

if (missingReactDom && reactVersion) {
packages.push(`react-dom@${reactVersion}`);
}

await packageManager.addDependencies({ ...npmOptions, packageJson }, packages);

packageManager.addScripts({
'storybook-generate': 'sb-rn-get-stories',
'storybook-watch': 'sb-rn-watcher',
Expand All @@ -53,7 +55,7 @@ const generator = async (
await copyTemplateFiles({
packageManager,
renderer: 'react-native',
language: SupportedLanguage.JAVASCRIPT,
language: SupportedLanguage.TYPESCRIPT_3_8,
destination: storybookConfigFolder,
includeCommonAssets: false,
});
Expand Down
29 changes: 19 additions & 10 deletions code/lib/cli/src/initiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
HandledError,
JsPackageManagerFactory,
commandLog,
codeLog,
paddedLog,
} from '@storybook/core-common';
import type { JsPackageManager } from '@storybook/core-common';
Expand Down Expand Up @@ -347,15 +346,25 @@ export async function doInitiate(
}

if (projectType === ProjectType.REACT_NATIVE) {
logger.log();
logger.log(chalk.yellow('NOTE: installation is not 100% automated.\n'));
logger.log(`To quickly run Storybook, replace contents of your app entry with:\n`);
codeLog(["export {default} from './.storybook';"]);
logger.log('\n Then to run your Storybook, type:\n');
codeLog([packageManager.getRunCommand('start')]);
logger.log('\n For more in information, see the github readme:\n');
logger.log(chalk.cyan('https://github.com/storybookjs/react-native'));
logger.log();
logger.log(dedent`
${chalk.yellow('NOTE: installation is not 100% automated.')}
To run Storybook, you will need to:
1. Replace the contents of your app entry with the following
${chalk.inverse(' ' + "export {default} from './.storybook';" + ' ')}
2. Enable transformer.unstable_allowRequireContext in your metro config
For a more detailed guide go to:
${chalk.cyan('https://github.com/storybookjs/react-native#existing-project')}
Then to run your Storybook, type:
${chalk.inverse(' ' + packageManager.getRunCommand('start') + ' ')}
`);

return { shouldRunDev: false };
}
Expand Down
36 changes: 33 additions & 3 deletions code/lib/cli/src/upgrade.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { getStorybookCoreVersion } from '@storybook/telemetry';
import {
UpgradeStorybookToLowerVersionError,
UpgradeStorybookToSameVersionError,
Expand All @@ -8,11 +7,18 @@ import { doUpgrade, getStorybookVersion } from './upgrade';

import type * as sbcc from '@storybook/core-common';

const findInstallationsMock = vi.fn<string[], Promise<sbcc.InstallationMetadata | undefined>>();

vi.mock('@storybook/telemetry');
vi.mock('@storybook/core-common', async (importOriginal) => {
const originalModule = (await importOriginal()) as typeof sbcc;
return {
...originalModule,
JsPackageManagerFactory: {
getPackageManager: () => ({
findInstallations: findInstallationsMock,
}),
},
versions: Object.keys(originalModule.versions).reduce(
(acc, key) => {
acc[key] = '8.0.0';
Expand Down Expand Up @@ -46,13 +52,37 @@ describe.each([

describe('Upgrade errors', () => {
it('should throw an error when upgrading to a lower version number', async () => {
vi.mocked(getStorybookCoreVersion).mockResolvedValue('8.1.0');
findInstallationsMock.mockResolvedValue({
dependencies: {
'@storybook/cli': [
{
version: '8.1.0',
},
],
},
duplicatedDependencies: {},
infoCommand: '',
dedupeCommand: '',
});

await expect(doUpgrade({} as any)).rejects.toThrowError(UpgradeStorybookToLowerVersionError);
expect(findInstallationsMock).toHaveBeenCalledWith(['storybook', '@storybook/cli']);
});
it('should throw an error when upgrading to the same version number', async () => {
vi.mocked(getStorybookCoreVersion).mockResolvedValue('8.0.0');
findInstallationsMock.mockResolvedValue({
dependencies: {
'@storybook/cli': [
{
version: '8.0.0',
},
],
},
duplicatedDependencies: {},
infoCommand: '',
dedupeCommand: '',
});

await expect(doUpgrade({} as any)).rejects.toThrowError(UpgradeStorybookToSameVersionError);
expect(findInstallationsMock).toHaveBeenCalledWith(['storybook', '@storybook/cli']);
});
});
23 changes: 18 additions & 5 deletions code/lib/cli/src/upgrade.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { sync as spawnSync } from 'cross-spawn';
import { telemetry, getStorybookCoreVersion } from '@storybook/telemetry';
import { telemetry } from '@storybook/telemetry';
import semver, { eq, lt, prerelease } from 'semver';
import { logger } from '@storybook/node-logger';
import { withTelemetry } from '@storybook/core-server';
Expand All @@ -11,7 +11,7 @@ import {
import chalk from 'chalk';
import dedent from 'ts-dedent';
import boxen from 'boxen';
import type { PackageManagerName } from '@storybook/core-common';
import type { JsPackageManager, PackageManagerName } from '@storybook/core-common';
import {
JsPackageManagerFactory,
isCorePackage,
Expand All @@ -37,6 +37,18 @@ export const getStorybookVersion = (line: string) => {
};
};

const getInstalledStorybookVersion = async (packageManager: JsPackageManager) => {
const installations = await packageManager.findInstallations(['storybook', '@storybook/cli']);
if (!installations) {
return;
}
const cliVersion = installations.dependencies['@storybook/cli']?.[0].version;
if (cliVersion) {
return cliVersion;
}
return installations.dependencies['storybook']?.[0].version;
};

const deprecatedPackages = [
{
minVersion: '6.0.0-alpha.0',
Expand Down Expand Up @@ -113,8 +125,9 @@ export const doUpgrade = async ({
}: UpgradeOptions) => {
const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr });

// If we can't determine the existing version (Yarn PnP), fallback to v0.0.0 to not block the upgrade
const beforeVersion = (await getStorybookCoreVersion()) ?? '0.0.0';
// If we can't determine the existing version fallback to v0.0.0 to not block the upgrade
const beforeVersion = (await getInstalledStorybookVersion(packageManager)) ?? '0.0.0';

const currentVersion = versions['@storybook/cli'];
const isCanary = currentVersion.startsWith('0.0.0');

Expand Down Expand Up @@ -206,7 +219,7 @@ export const doUpgrade = async ({
automigrationResults = await automigrate({ dryRun, yes, packageManager: pkgMgr, configDir });
}
if (!options.disableTelemetry) {
const afterVersion = await getStorybookCoreVersion();
const afterVersion = await getInstalledStorybookVersion(packageManager);
const { preCheckFailure, fixResults } = automigrationResults || {};
const automigrationTelemetry = {
automigrationResults: preCheckFailure ? null : fixResults,
Expand Down
Loading

0 comments on commit f701a28

Please sign in to comment.