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

CLI: Add "intents" question & auto-install test addon & improve test-addon compatibility #30202

Open
wants to merge 161 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
161 commits
Select commit Hold shift + click to select a range
bde2134
ink in core and esm in create-storybook
ndelangen Jan 7, 2025
7e4592d
ink in init
ndelangen Jan 7, 2025
9f88950
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 7, 2025
59d7c63
fix
ndelangen Jan 7, 2025
6462b7b
keep other package dist bundling unchanged
ndelangen Jan 7, 2025
3a19d00
fix
ndelangen Jan 7, 2025
71df9d9
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 7, 2025
b5f7b2e
support ink types
ndelangen Jan 7, 2025
25d7e76
use esm of CLI
ndelangen Jan 7, 2025
760ce6d
fixes for check to support for moduleresolution=bundler
ndelangen Jan 7, 2025
c44aca3
add cjs
ndelangen Jan 7, 2025
321de92
undo shim change in prepare script
ndelangen Jan 7, 2025
9683316
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 7, 2025
20844fc
disable parallelism as it's not letting me see the issue, and i canno…
ndelangen Jan 7, 2025
57bc122
rendering with ink embedded in vite
ndelangen Jan 7, 2025
0eec9b0
add `node` condition for chalk
ndelangen Jan 7, 2025
e84572d
fix
ndelangen Jan 7, 2025
0f42062
unit test pass?
ndelangen Jan 8, 2025
b843a68
Discard changes to .circleci/config.yml
ndelangen Jan 8, 2025
199b5bf
fix linting
ndelangen Jan 8, 2025
5da8301
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 8, 2025
0fccec9
fix linting
ndelangen Jan 8, 2025
fb51e3b
add first demo story of an ink component
ndelangen Jan 8, 2025
1a5fe81
Discard changes to code/lib/cli-storybook/test/default/cli.test.cjs
ndelangen Jan 8, 2025
7440621
cleanup
ndelangen Jan 8, 2025
21c04b7
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 9, 2025
9541d3e
cleanup
ndelangen Jan 9, 2025
1e75423
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 9, 2025
5ff6089
typings
ndelangen Jan 9, 2025
90f12d7
update the target environment so we do not need TLA plugin, which see…
ndelangen Jan 9, 2025
69d64f8
cleanup
ndelangen Jan 9, 2025
a876450
fix types
ndelangen Jan 9, 2025
94843bf
patch away the top-level-away and devtools from ink to fix https://cl…
ndelangen Jan 9, 2025
b79205f
Revert "patch away the top-level-away and devtools from ink to fix ht…
ndelangen Jan 9, 2025
49f2c44
fix dev
ndelangen Jan 9, 2025
35505ec
fix dev actually
ndelangen Jan 9, 2025
f02c1a7
centered
ndelangen Jan 9, 2025
211318f
fix firefox Intl.Segmenter in chromatic
ndelangen Jan 9, 2025
580cf60
try to fix
ndelangen Jan 9, 2025
234c8da
alt solution
ndelangen Jan 9, 2025
6555742
add debug
ndelangen Jan 9, 2025
fe1e4c7
debug
ndelangen Jan 9, 2025
098a52e
Merge changes from POC
ghengeveld Jan 10, 2025
02cffc8
conditional ink stories, do not add when running vitest
ndelangen Jan 10, 2025
c97f554
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 10, 2025
2cbdd8e
fix windows compilation problem with pathing
ndelangen Jan 10, 2025
e821aae
remove story I added fro debugging purposes
ndelangen Jan 10, 2025
660aa3c
trying to fix the include pattern
ndelangen Jan 10, 2025
18b4f8d
again
ndelangen Jan 10, 2025
82851be
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 10, 2025
f6975ff
cleanup
ndelangen Jan 10, 2025
ec64802
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 13, 2025
1cdcb1a
split the create-storybook CLI into a modern & legacy part, based on …
ndelangen Jan 13, 2025
8c9d6af
add comments
ndelangen Jan 13, 2025
b5d1593
render the app
ndelangen Jan 13, 2025
6423249
wip
ghengeveld Jan 14, 2025
cfd010a
Merge pull request #30256 from storybookjs/gert/cli-with-ink
ndelangen Jan 14, 2025
b6e2afe
version accurate
ndelangen Jan 14, 2025
b530642
scaffold reducer state
ndelangen Jan 14, 2025
cf905a2
adding more input
ndelangen Jan 14, 2025
4b9f6cf
cleanup
ndelangen Jan 14, 2025
bbdae44
add more steps details
ndelangen Jan 15, 2025
54b0998
add a run step && cleanup
ndelangen Jan 15, 2025
9983643
add node utils via context, so storybook doesn't run into it
ndelangen Jan 15, 2025
d5ca217
crude install
ndelangen Jan 15, 2025
dcd3d1f
add require for resolving to context, use ni for package manager oper…
ndelangen Jan 15, 2025
a59ea66
reduce bloat
ndelangen Jan 16, 2025
af7ec07
fix
ndelangen Jan 16, 2025
75019af
fixes & add place for metrics component
ndelangen Jan 16, 2025
d8fc245
handle steps as a straight line. each step can skip itself in a useEf…
ndelangen Jan 16, 2025
df22449
cleanup
ndelangen Jan 16, 2025
ab86684
I guess we can keep it
ndelangen Jan 16, 2025
9c70158
move Confirm component
ndelangen Jan 16, 2025
195c39f
simplify
ndelangen Jan 16, 2025
8ff6e74
figured out a way to cancel
ndelangen Jan 16, 2025
f58c72d
track errors from procedures
ndelangen Jan 16, 2025
4817715
more error handling in interllation procedure
ndelangen Jan 16, 2025
3fe3307
better error handling
ndelangen Jan 16, 2025
a4c188e
improve error handling (no meaningless error if a meaningful one was …
ndelangen Jan 16, 2025
212b99f
install with versions & improve UI
ndelangen Jan 17, 2025
4bf774d
improve UI
ndelangen Jan 17, 2025
924fb94
uppercase to indicate <enter> will select that
ndelangen Jan 20, 2025
133f948
refactor, to reduce long files
ndelangen Jan 20, 2025
3de4555
move check to context
ndelangen Jan 20, 2025
dde08df
more stories
ndelangen Jan 20, 2025
9dc465b
cleanup
ndelangen Jan 20, 2025
25e2024
cleanup
ndelangen Jan 20, 2025
d41f56d
context changes
ndelangen Jan 20, 2025
1276642
fixes
ndelangen Jan 20, 2025
10bf2e7
fixes
ndelangen Jan 20, 2025
d9f0590
fix
ndelangen Jan 20, 2025
076929d
add story
ndelangen Jan 20, 2025
03c8751
cleanup
ndelangen Jan 20, 2025
b28651c
Add telemetry
ghengeveld Jan 20, 2025
174473c
improve
ndelangen Jan 21, 2025
6443b00
Omit directory for privacy reasons
ghengeveld Jan 21, 2025
2a2f9b0
Rename files
ghengeveld Jan 21, 2025
dbdb3a1
Merge branch 'norbert/cli-with-ink' into gert/init-telemetry
ghengeveld Jan 21, 2025
2ad4e6f
Merge pull request #30313 from storybookjs/gert/init-telemetry
ghengeveld Jan 21, 2025
17eb077
fix
ndelangen Jan 21, 2025
68fd581
fix
ndelangen Jan 21, 2025
d281b9a
improve error handling
ndelangen Jan 21, 2025
3114096
cleanup
ndelangen Jan 21, 2025
23379b3
cleanup
ndelangen Jan 21, 2025
9e3968d
add completion & spinners to procedures && add telemetry as tracked task
ndelangen Jan 21, 2025
5b2bbab
have some fun, I got the user's name
ndelangen Jan 21, 2025
db1e037
improve header
ndelangen Jan 22, 2025
90f0a74
improve error handling of installation
ndelangen Jan 22, 2025
4958640
fixes
ndelangen Jan 22, 2025
89c404c
fix typo
ndelangen Jan 22, 2025
e003420
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 22, 2025
8b13cb1
Disable telemetry notification when running create-storybook because …
ghengeveld Jan 22, 2025
7a167e0
Implement checks
ghengeveld Jan 22, 2025
16a7433
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 22, 2025
958e81e
fix intents
ndelangen Jan 22, 2025
7ea83ed
no default in CLI, but set defaults in the component instead. This wa…
ndelangen Jan 23, 2025
1a6be9c
no default intents in app
ndelangen Jan 23, 2025
3159795
Implement first set of actual checks
ghengeveld Jan 23, 2025
7044963
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 23, 2025
fb670b9
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 23, 2025
e8d1fdf
add crude config generation
ndelangen Jan 24, 2025
8a58dbe
add main config generation
ndelangen Jan 24, 2025
da9991b
improve config generation
ndelangen Jan 24, 2025
1368d0d
improve messaging of configDir check
ndelangen Jan 24, 2025
e9abc33
previewConfig file generation
ndelangen Jan 24, 2025
5661454
Various prerequisite checks
ghengeveld Jan 24, 2025
2f2472c
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 24, 2025
426013c
Cleanup comments
ghengeveld Jan 24, 2025
f83bd4b
add a map for package names
ndelangen Jan 24, 2025
4302698
Merge branch 'norbert/cli-with-ink' of https://github.com/storybookjs…
ndelangen Jan 24, 2025
6266659
add detection
ndelangen Jan 27, 2025
29e75e1
I suppose we could do it like this
ndelangen Jan 27, 2025
e858811
add cwd
ndelangen Jan 27, 2025
6b9ec5d
Wrapup Vitest compatibility checks
ghengeveld Jan 27, 2025
6f059c1
Add new compatibility checks to old create-storybook CLI
ghengeveld Jan 28, 2025
a594eea
Fix installation process
ghengeveld Jan 28, 2025
8468f6f
remove unused ink
ndelangen Jan 29, 2025
88f3cbc
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 29, 2025
ef2f0e6
make intents question optional && more cleanup
ndelangen Jan 29, 2025
c3b2f8b
improve check
ndelangen Jan 29, 2025
46771c5
cleanup
ndelangen Jan 29, 2025
f4f1e3b
fix typing
ndelangen Jan 29, 2025
457a447
cleanup
ndelangen Jan 29, 2025
1c0dd49
fix
ndelangen Jan 29, 2025
9028541
do not run on CI
ndelangen Jan 29, 2025
6a6e89b
Merge branch 'next' into norbert/cli-with-ink
ndelangen Jan 31, 2025
e433a08
cleanup
ndelangen Jan 31, 2025
6867b54
add intents to telemetry
ndelangen Jan 31, 2025
da37286
cleanup
ndelangen Jan 31, 2025
8e0d959
cleanup
ndelangen Jan 31, 2025
fe2dc28
cleanup
ndelangen Jan 31, 2025
5bad95b
cleanup
ndelangen Jan 31, 2025
2a2806f
prebundle create-storybook more
ndelangen Jan 31, 2025
2ff6044
remove prettier as a dependency
ndelangen Jan 31, 2025
5adcfd5
direct depend on storybook/core
ndelangen Jan 31, 2025
d43667d
fix forgotten usages of storybook/internal
ndelangen Jan 31, 2025
43029f5
Add support for extending existing Vitest workspace file
ghengeveld Jan 31, 2025
dc10757
Handle non-interactive (non TTY) mode
ghengeveld Jan 31, 2025
35656f0
add CLi flag for intents & send original intent to telemetry
ndelangen Jan 31, 2025
78a2d72
Don't default to migrating to nextjs-vite
ghengeveld Jan 31, 2025
0063c5e
Check for framework compatibility with addon-test
ghengeveld Jan 31, 2025
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
11 changes: 10 additions & 1 deletion code/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,16 @@ module.exports = {
},
},
{
files: ['*.js', '*.jsx', '*.json', '*.html', '**/.storybook/*.ts', '**/.storybook/*.tsx'],
files: [
'*.js',
'*.jsx',
'*.json',
'*.html',
'**/.storybook/*.ts',
'**/.storybook/*.tsx',
'**/.storybook/**/*.ts',
'**/.storybook/**/*.tsx',
],
Comment on lines +61 to +70
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Consider using a more concise glob pattern like '/.storybook//*.{ts,tsx}' instead of separate patterns

parserOptions: {
project: null,
},
Expand Down
3 changes: 2 additions & 1 deletion code/.storybook/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { StorybookConfig } from '../frameworks/react-vite';

const componentsPath = join(__dirname, '../core/src/components');
const managerApiPath = join(__dirname, '../core/src/manager-api');
const imageContextPath = join(__dirname, '..//frameworks/nextjs/src/image-context.ts');
const imageContextPath = join(__dirname, '../frameworks/nextjs/src/image-context.ts');

const config: StorybookConfig = {
stories: [
Expand Down Expand Up @@ -159,6 +159,7 @@ const config: StorybookConfig = {
build: {
// disable sourcemaps in CI to not run out of memory
sourcemap: process.env.CI !== 'true',
target: ['chrome100'],
},
server: {
watch: {
Expand Down
225 changes: 104 additions & 121 deletions code/addons/test/src/postinstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs';
import * as fs from 'node:fs/promises';
import { writeFile } from 'node:fs/promises';

import { traverse } from 'storybook/internal/babel';
import { babelParse, generate, traverse } from 'storybook/internal/babel';
import {
JsPackageManagerFactory,
extractProperFrameworkName,
Expand All @@ -28,16 +28,23 @@ import { dedent } from 'ts-dedent';
import { type PostinstallOptions } from '../../../lib/cli-storybook/src/add';
import { SUPPORTED_FRAMEWORKS, SUPPORTED_RENDERERS } from './constants';
import { printError, printInfo, printSuccess, step } from './postinstall-logger';
import { updateWorkspaceFile } from './updateWorkspaceFile';
import { getAddonNames } from './utils';

const ADDON_NAME = '@storybook/experimental-addon-test' as const;
const EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.cts', '.mts', '.cjs', '.mjs'] as const;
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.cts', '.mts', '.cjs', '.mjs'];

const addonInteractionsName = '@storybook/addon-interactions';
const addonA11yName = '@storybook/addon-a11y';

const findFile = async (basename: string, extraExtensions: string[] = []) =>
findUp([...EXTENSIONS, ...extraExtensions].map((ext) => basename + ext));
const findFile = async (basename: string, extensions = EXTENSIONS) =>
findUp(extensions.map((ext) => basename + ext));

const loadTemplate = async (name: string, replacements: Record<string, string>) => {
let template = await fs.readFile(resolve(__dirname, name), 'utf8');
Object.entries(replacements).forEach(([key, value]) => (template = template.replace(key, value)));
return template;
};

export default async function postInstall(options: PostinstallOptions) {
printSuccess(
Expand Down Expand Up @@ -67,22 +74,23 @@ export default async function postInstall(options: PostinstallOptions) {

const hasCustomWebpackConfig = !!config.getFieldNode(['webpackFinal']);

const isInteractive = process.stdout.isTTY && !process.env.CI;

if (info.frameworkPackageName === '@storybook/nextjs' && !hasCustomWebpackConfig) {
const out = options.yes
? {
migrateToExperimentalNextjsVite: true,
}
: await prompts({
type: 'confirm',
name: 'migrateToExperimentalNextjsVite',
message: dedent`
const out =
options.yes || !isInteractive
? { migrateToExperimentalNextjsVite: !!options.yes }
: await prompts({
type: 'confirm',
name: 'migrateToExperimentalNextjsVite',
message: dedent`
The addon requires the use of @storybook/experimental-nextjs-vite to work with Next.js.
https://storybook.js.org/docs/writing-tests/test-addon#install-and-set-up

Do you want to migrate?
`,
initial: true,
});
initial: true,
});

if (out.migrateToExperimentalNextjsVite) {
await packageManager.addDependencies({ installAsDevDependencies: true }, [
Expand Down Expand Up @@ -221,12 +229,14 @@ export default async function postInstall(options: PostinstallOptions) {
`
);

const response = await prompts({
type: 'confirm',
name: 'shouldUninstall',
message: `Would you like me to remove and unregister ${addonInteractionsName}? Press N to abort the entire installation.`,
initial: true,
});
const response = isInteractive
? await prompts({
type: 'confirm',
name: 'shouldUninstall',
message: `Would you like me to remove and unregister ${addonInteractionsName}? Press N to abort the entire installation.`,
initial: true,
})
: { shouldUninstall: true };

shouldUninstall = response.shouldUninstall;
}
Expand Down Expand Up @@ -300,7 +310,7 @@ export default async function postInstall(options: PostinstallOptions) {
});

const fileExtension =
allDeps['typescript'] || (await findFile('tsconfig', ['.json'])) ? 'ts' : 'js';
allDeps.typescript || (await findFile('tsconfig', [...EXTENSIONS, '.json'])) ? 'ts' : 'js';

const vitestSetupFile = resolve(options.configDir, `vitest.setup.${fileExtension}`);
if (existsSync(vitestSetupFile)) {
Expand Down Expand Up @@ -372,30 +382,11 @@ export default async function postInstall(options: PostinstallOptions) {
}
}

// Check for existing Vitest workspace. We can't extend it so manual setup is required.
const vitestWorkspaceFile = await findFile('vitest.workspace');
if (vitestWorkspaceFile) {
printError(
'🚨 Oh no!',
dedent`
Found an existing Vitest workspace file:
${colors.gray(vitestWorkspaceFile)}

I was able to configure most of the addon but could not safely extend
your existing workspace file automatically, you must do it yourself. This was the last step.

Please refer to the documentation to complete the setup manually:
${picocolors.cyan(`https://storybook.js.org/docs/writing-tests/test-addon#manual-setup`)}
`
);
logger.line(1);
return;
}

// Check for an existing config file. Can be from Vitest (preferred) or Vite (with `test` option).
// Check for an existing config file. Can be from Vitest (preferred) or Vite.
const viteConfigFile = await findFile('vite.config');
if (viteConfigFile) {
const viteConfig = await fs.readFile(viteConfigFile, 'utf8');
// We don't support extending a test config in a Vite config file, so we bail out.
if (viteConfig.match(/\Wtest:\s*{/)) {
printError(
'🚨 Oh no!',
Expand All @@ -415,6 +406,7 @@ export default async function postInstall(options: PostinstallOptions) {
}
}

const vitestWorkspaceFile = await findFile('vitest.workspace', ['.ts', '.js', '.json']);
const vitestConfigFile = await findFile('vitest.config');
const vitestShimFile = await findFile('vitest.shims.d');
const rootConfig = vitestConfigFile || viteConfigFile;
Expand All @@ -426,11 +418,7 @@ export default async function postInstall(options: PostinstallOptions) {
enabled: true,
headless: true,
provider: 'playwright',
instances: [
{
browser: 'chromium',
}
]
instances: [{ browser: 'chromium' }]
}`
: `{
enabled: true,
Expand All @@ -446,88 +434,83 @@ export default async function postInstall(options: PostinstallOptions) {
);
}

if (rootConfig) {
// If there's an existing config, we create a workspace file so we can run Storybook tests alongside.
const extension = extname(rootConfig);
const browserWorkspaceFile = resolve(dirname(rootConfig), `vitest.workspace${extension}`);
// to be set in vitest config
const vitestSetupFilePath = relative(dirname(browserWorkspaceFile), vitestSetupFile);
if (vitestWorkspaceFile) {
// If there's an existing workspace file, we update that file to include the Storybook test plugin.
// We assume the existing workspaces include the Vite(st) config, so we won't add it.
const vitestSetupFilePath = relative(dirname(vitestWorkspaceFile), vitestSetupFile);
const workspaceTemplate = await loadTemplate('vitest.workspace.template.ts', {
EXTENDS_WORKSPACE: viteConfigFile
? relative(dirname(vitestWorkspaceFile), viteConfigFile)
: '',
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: vitestSetupFilePath,
}).then((t) => t.replace(`\n 'ROOT_CONFIG',`, '').replace(/\s+extends: '',/, ''));
const workspaceFile = await fs.readFile(vitestWorkspaceFile, 'utf8');
const source = babelParse(workspaceTemplate);
const target = babelParse(workspaceFile);

const updated = updateWorkspaceFile(source, target);
if (!updated) {
printError(
'🚨 Oh no!',
dedent`
Could not update existing Vitest workspace file:
${colors.gray(vitestWorkspaceFile)}

I was able to configure most of the addon but could not safely extend
your existing workspace file automatically, you must do it yourself.

Please refer to the documentation to complete the setup manually:
${picocolors.cyan(`https://storybook.js.org/docs/writing-tests/test-addon#manual-setup`)}
`
);
logger.line(1);
return;
}

logger.line(1);
logger.plain(`${step} Creating a Vitest project workspace file:`);
logger.plain(colors.gray(` ${browserWorkspaceFile}`));
logger.plain(`${step} Updating your Vitest workspace file:`);
logger.plain(colors.gray(` ${vitestWorkspaceFile}`));

const formattedContent = await formatFileContent(vitestWorkspaceFile, generate(target).code);
await writeFile(vitestWorkspaceFile, formattedContent);
} else if (rootConfig) {
// If there's an existing Vite/Vitest config, we create a workspace file so we can run Storybook tests alongside.
const extension = extname(rootConfig).includes('ts') ? '.ts' : '.js';
const newWorkspaceFile = resolve(dirname(rootConfig), `vitest.workspace${extension}`);
const vitestSetupFilePath = relative(dirname(newWorkspaceFile), vitestSetupFile);
const workspaceTemplate = await loadTemplate('vitest.workspace.template.ts', {
ROOT_CONFIG: relative(dirname(newWorkspaceFile), rootConfig),
// We only extend from Vite config (without test property), not Vitest config.
EXTENDS_WORKSPACE: viteConfigFile ? relative(dirname(newWorkspaceFile), viteConfigFile) : '',
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: vitestSetupFilePath,
}).then((t) => t.replace(/\s+extends: '',/, ''));

await writeFile(
browserWorkspaceFile,
await formatFileContent(
browserWorkspaceFile,
dedent`
import { defineWorkspace } from 'vitest/config';
import { storybookTest } from '@storybook/experimental-addon-test/vitest-plugin';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const dirname = typeof __dirname !== 'undefined'
? __dirname
: path.dirname(fileURLToPath(import.meta.url));

// More info at: https://storybook.js.org/docs/writing-tests/test-addon
export default defineWorkspace([
'${relative(dirname(browserWorkspaceFile), rootConfig)}',
{
extends: '${viteConfigFile ? relative(dirname(browserWorkspaceFile), viteConfigFile) : ''}',
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/writing-tests/test-addon#storybooktest
storybookTest({ configDir: path.join(dirname, '${options.configDir}') })
],
test: {
name: 'storybook',
browser: ${browserConfig},
setupFiles: ['${vitestSetupFilePath}'],
},
},
]);
`.replace(/\s+extends: '',/, '')
)
);
logger.line(1);
logger.plain(`${step} Creating a Vitest workspace file:`);
logger.plain(colors.gray(` ${newWorkspaceFile}`));

const formattedContent = await formatFileContent(newWorkspaceFile, workspaceTemplate);
await writeFile(newWorkspaceFile, formattedContent);
} else {
// If there's no existing Vitest/Vite config, we create a new Vitest config file.
const newVitestConfigFile = resolve(`vitest.config.${fileExtension}`);
// to be set in vitest config
const vitestSetupFilePath = relative(dirname(newVitestConfigFile), vitestSetupFile);
const newConfigFile = resolve(`vitest.config.${fileExtension}`);
const vitestSetupFilePath = relative(dirname(newConfigFile), vitestSetupFile);
const configTemplate = await loadTemplate('vitest.config.template.ts', {
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: vitestSetupFilePath,
});

logger.line(1);
logger.plain(`${step} Creating a Vitest project config file:`);
logger.plain(colors.gray(` ${newVitestConfigFile}`));
logger.plain(`${step} Creating a Vitest config file:`);
logger.plain(colors.gray(` ${newConfigFile}`));

await writeFile(
newVitestConfigFile,
dedent`
import { defineConfig } from 'vitest/config';
import { storybookTest } from '@storybook/experimental-addon-test/vitest-plugin';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const dirname = typeof __dirname !== 'undefined'
? __dirname
: path.dirname(fileURLToPath(import.meta.url));

// More info at: https://storybook.js.org/docs/writing-tests/test-addon
export default defineConfig({
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/writing-tests/test-addon#storybooktest
storybookTest({ configDir: path.join(dirname, '${options.configDir}') })
],
test: {
name: 'storybook',
browser: ${browserConfig},
setupFiles: ['${vitestSetupFilePath}'],
},
});
`
);
const formattedContent = await formatFileContent(newConfigFile, configTemplate);
await writeFile(newConfigFile, formattedContent);
}

const runCommand = rootConfig ? `npx vitest --project=storybook` : `npx vitest`;
Expand Down
Loading
Loading