diff --git a/code/addons/a11y/src/components/Report/HighlightToggle.tsx b/code/addons/a11y/src/components/Report/HighlightToggle.tsx index cff5ec7ceb9..90a81b26c06 100644 --- a/code/addons/a11y/src/components/Report/HighlightToggle.tsx +++ b/code/addons/a11y/src/components/Report/HighlightToggle.tsx @@ -31,8 +31,8 @@ function areAllRequiredElementsHighlighted( return highlightedCount === 0 ? CheckBoxStates.UNCHECKED : highlightedCount === elementsToHighlight.length - ? CheckBoxStates.CHECKED - : CheckBoxStates.INDETERMINATE; + ? CheckBoxStates.CHECKED + : CheckBoxStates.INDETERMINATE; } const HighlightToggle: React.FC = ({ toggleId, elementsToHighlight = [] }) => { diff --git a/code/addons/backgrounds/src/containers/BackgroundSelector.tsx b/code/addons/backgrounds/src/containers/BackgroundSelector.tsx index 87bf6e84f13..c8d4bcb9019 100644 --- a/code/addons/backgrounds/src/containers/BackgroundSelector.tsx +++ b/code/addons/backgrounds/src/containers/BackgroundSelector.tsx @@ -37,40 +37,24 @@ const createBackgroundSelectorItem = memoize(1000)( }) ); -const getDisplayedItems = memoize(10)( - ( - backgrounds: Background[], - selectedBackgroundColor: string | null, - change: (arg: { selected: string; name: string }) => void - ) => { - const backgroundSelectorItems = backgrounds.map(({ name, value }) => - createBackgroundSelectorItem( - null, - name, - value, - true, - change, - value === selectedBackgroundColor - ) - ); +const getDisplayedItems = memoize(10)(( + backgrounds: Background[], + selectedBackgroundColor: string | null, + change: (arg: { selected: string; name: string }) => void +) => { + const backgroundSelectorItems = backgrounds.map(({ name, value }) => + createBackgroundSelectorItem(null, name, value, true, change, value === selectedBackgroundColor) + ); - if (selectedBackgroundColor !== 'transparent') { - return [ - createBackgroundSelectorItem( - 'reset', - 'Clear background', - 'transparent', - null, - change, - false - ), - ...backgroundSelectorItems, - ]; - } - - return backgroundSelectorItems; + if (selectedBackgroundColor !== 'transparent') { + return [ + createBackgroundSelectorItem('reset', 'Clear background', 'transparent', null, change, false), + ...backgroundSelectorItems, + ]; } -); + + return backgroundSelectorItems; +}); const DEFAULT_BACKGROUNDS_CONFIG: BackgroundsParameter = { default: null, diff --git a/code/addons/viewport/src/Tool.tsx b/code/addons/viewport/src/Tool.tsx index f365fb65d04..53e7bce1c45 100644 --- a/code/addons/viewport/src/Tool.tsx +++ b/code/addons/viewport/src/Tool.tsx @@ -35,21 +35,24 @@ const responsiveViewport: ViewportItem = { const baseViewports: ViewportItem[] = [responsiveViewport]; -const toLinks = memoize(50)( - (list: ViewportItem[], active: LinkBase, updateGlobals, close): Link[] => { - return list - .filter((i) => i.id !== responsiveViewport.id || active.id !== i.id) - .map((i) => { - return { - ...i, - onClick: () => { - updateGlobals({ viewport: i.id }); - close(); - }, - }; - }); - } -); +const toLinks = memoize(50)(( + list: ViewportItem[], + active: LinkBase, + updateGlobals, + close +): Link[] => { + return list + .filter((i) => i.id !== responsiveViewport.id || active.id !== i.id) + .map((i) => { + return { + ...i, + onClick: () => { + updateGlobals({ viewport: i.id }); + close(); + }, + }; + }); +}); interface LinkBase { id: string; diff --git a/code/builders/builder-vite/src/vite-config.test.ts b/code/builders/builder-vite/src/vite-config.test.ts index 0dfd0534ee3..8f34e65277e 100644 --- a/code/builders/builder-vite/src/vite-config.test.ts +++ b/code/builders/builder-vite/src/vite-config.test.ts @@ -25,7 +25,7 @@ const dummyOptions: Options = { builder: {}, }, options: {}, - }[key]), + })[key], } as Presets, presetsList: [], }; diff --git a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts index ac573827715..4f4590132f1 100644 --- a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts +++ b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts @@ -132,9 +132,8 @@ export default async ( externals['@storybook/blocks'] = '__STORYBOOK_BLOCKS_EMPTY_MODULE__'; } - const { virtualModules: virtualModuleMapping, entries: dynamicEntries } = await getVirtualModules( - options - ); + const { virtualModules: virtualModuleMapping, entries: dynamicEntries } = + await getVirtualModules(options); return { name: 'preview', @@ -286,26 +285,26 @@ export default async ( }), ] : builderOptions.useSWC - ? [ - new TerserWebpackPlugin({ - minify: TerserWebpackPlugin.swcMinify, - terserOptions: { - sourceMap: !options.build?.test?.disableSourcemaps, - mangle: false, - keep_fnames: true, - }, - }), - ] - : [ - new TerserWebpackPlugin({ - parallel: true, - terserOptions: { - sourceMap: !options.build?.test?.disableSourcemaps, - mangle: false, - keep_fnames: true, - }, - }), - ], + ? [ + new TerserWebpackPlugin({ + minify: TerserWebpackPlugin.swcMinify, + terserOptions: { + sourceMap: !options.build?.test?.disableSourcemaps, + mangle: false, + keep_fnames: true, + }, + }), + ] + : [ + new TerserWebpackPlugin({ + parallel: true, + terserOptions: { + sourceMap: !options.build?.test?.disableSourcemaps, + mangle: false, + keep_fnames: true, + }, + }), + ], } : {}), }, diff --git a/code/frameworks/angular/src/client/angular-beta/ComputesTemplateFromComponent.ts b/code/frameworks/angular/src/client/angular-beta/ComputesTemplateFromComponent.ts index a4462ea1a3d..e75354a4bf9 100644 --- a/code/frameworks/angular/src/client/angular-beta/ComputesTemplateFromComponent.ts +++ b/code/frameworks/angular/src/client/angular-beta/ComputesTemplateFromComponent.ts @@ -172,7 +172,7 @@ const buildTemplate = ( const firstSelector = selector.split(',')[0]; const templateReplacers: [ string | RegExp, - string | ((substring: string, ...args: any[]) => string) + string | ((substring: string, ...args: any[]) => string), ][] = [ [/(^.*?)(?=[,])/, '$1'], [/(^\..+)/, 'div$1'], diff --git a/code/frameworks/angular/src/client/angular-beta/utils/PropertyExtractor.ts b/code/frameworks/angular/src/client/angular-beta/utils/PropertyExtractor.ts index e6db7384488..f7bb907831c 100644 --- a/code/frameworks/angular/src/client/angular-beta/utils/PropertyExtractor.ts +++ b/code/frameworks/angular/src/client/angular-beta/utils/PropertyExtractor.ts @@ -41,7 +41,10 @@ export class PropertyExtractor implements NgModuleMetadata { applicationProviders?: Array>; /* eslint-enable @typescript-eslint/lines-between-class-members */ - constructor(private metadata: NgModuleMetadata, private component?: any) { + constructor( + private metadata: NgModuleMetadata, + private component?: any + ) { this.init(); } diff --git a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/attribute-selector.component.ts b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/attribute-selector.component.ts index 58618870358..af082743914 100644 --- a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/attribute-selector.component.ts +++ b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/attribute-selector.component.ts @@ -11,7 +11,10 @@ export class AttributeSelectorComponent { selectors!: string; - constructor(public el: ElementRef, private resolver: ComponentFactoryResolver) { + constructor( + public el: ElementRef, + private resolver: ComponentFactoryResolver + ) { const factory = this.resolver.resolveComponentFactory(AttributeSelectorComponent); this.selectors = factory.selector; this.generatedTemplate = el.nativeElement.outerHTML; diff --git a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/class-selector.component.ts b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/class-selector.component.ts index 3e81b5c5074..74dd70d7251 100644 --- a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/class-selector.component.ts +++ b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/class-selector.component.ts @@ -11,7 +11,10 @@ export class ClassSelectorComponent { selectors!: string; - constructor(public el: ElementRef, private resolver: ComponentFactoryResolver) { + constructor( + public el: ElementRef, + private resolver: ComponentFactoryResolver + ) { const factory = this.resolver.resolveComponentFactory(ClassSelectorComponent); this.selectors = factory.selector; this.generatedTemplate = el.nativeElement.outerHTML; diff --git a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/multiple-selector.component.ts b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/multiple-selector.component.ts index 00a4b98c3bf..88d7020da50 100644 --- a/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/multiple-selector.component.ts +++ b/code/frameworks/angular/template/stories/basics/component-with-complex-selectors/multiple-selector.component.ts @@ -11,7 +11,10 @@ export class MultipleSelectorComponent { selectors!: string; - constructor(public el: ElementRef, private resolver: ComponentFactoryResolver) { + constructor( + public el: ElementRef, + private resolver: ComponentFactoryResolver + ) { const factory = this.resolver.resolveComponentFactory(MultipleClassSelectorComponent); this.selectors = factory.selector; this.generatedTemplate = el.nativeElement.outerHTML; @@ -29,7 +32,10 @@ export class MultipleClassSelectorComponent { selectors!: string; - constructor(public el: ElementRef, private resolver: ComponentFactoryResolver) { + constructor( + public el: ElementRef, + private resolver: ComponentFactoryResolver + ) { const factory = this.resolver.resolveComponentFactory(MultipleClassSelectorComponent); this.selectors = factory.selector; this.generatedTemplate = el.nativeElement.outerHTML; diff --git a/code/frameworks/nextjs/src/babel/plugins/jsx-pragma.ts b/code/frameworks/nextjs/src/babel/plugins/jsx-pragma.ts index 419b178d576..76e1eec9c66 100644 --- a/code/frameworks/nextjs/src/babel/plugins/jsx-pragma.ts +++ b/code/frameworks/nextjs/src/babel/plugins/jsx-pragma.ts @@ -78,9 +78,9 @@ export default function jsxPragma({ types: t }: { types: typeof BabelTypes }): P ? // import { $import as _pragma } from '$module' t.importSpecifier(importAs, t.identifier(state.opts.import)) : state.opts.importNamespace - ? t.importNamespaceSpecifier(importAs) - : // import _pragma from '$module' - t.importDefaultSpecifier(importAs), + ? t.importNamespaceSpecifier(importAs) + : // import _pragma from '$module' + t.importDefaultSpecifier(importAs), ], t.stringLiteral(state.opts.module || 'react') ); diff --git a/code/frameworks/nextjs/src/babel/plugins/next-ssg-transform.ts b/code/frameworks/nextjs/src/babel/plugins/next-ssg-transform.ts index 5fa80c7e125..4c97b90e470 100644 --- a/code/frameworks/nextjs/src/babel/plugins/next-ssg-transform.ts +++ b/code/frameworks/nextjs/src/babel/plugins/next-ssg-transform.ts @@ -198,10 +198,10 @@ export default function nextTransformSsg({ p.node.type === 'ObjectProperty' ? 'value' : p.node.type === 'RestElement' - ? 'argument' - : (function () { - throw new Error('invariant'); - })() + ? 'argument' + : (function () { + throw new Error('invariant'); + })() ) as NodePath; if (isIdentifierReferenced(local)) { variableState.refs.add(local); @@ -360,10 +360,10 @@ export default function nextTransformSsg({ p.node.type === 'ObjectProperty' ? 'value' : p.node.type === 'RestElement' - ? 'argument' - : (function () { - throw new Error('invariant'); - })() + ? 'argument' + : (function () { + throw new Error('invariant'); + })() ) as NodePath; if (refs.has(local) && !isIdentifierReferenced(local)) { diff --git a/code/lib/cli/src/automigrate/fixes/angular-builders-multiproject.test.ts b/code/lib/cli/src/automigrate/fixes/angular-builders-multiproject.test.ts index 5d5b36f0c52..50844068d13 100644 --- a/code/lib/cli/src/automigrate/fixes/angular-builders-multiproject.test.ts +++ b/code/lib/cli/src/automigrate/fixes/angular-builders-multiproject.test.ts @@ -104,7 +104,7 @@ describe('is not Nx project', () => { () => ({ hasStorybookBuilder: true, - } as any) + }) as any ); }); @@ -129,7 +129,7 @@ describe('is not Nx project', () => { project1: { root: 'project1', architect: {} }, }, rootProject: 'project1', - } as any) + }) as any ); }); @@ -155,7 +155,7 @@ describe('is not Nx project', () => { project2: { root: 'project2', architect: {} }, }, rootProject: null, - } as any) + }) as any ); }); diff --git a/code/lib/cli/src/automigrate/fixes/angular-builders.test.ts b/code/lib/cli/src/automigrate/fixes/angular-builders.test.ts index 7c9e63bd4a5..c527b6434b3 100644 --- a/code/lib/cli/src/automigrate/fixes/angular-builders.test.ts +++ b/code/lib/cli/src/automigrate/fixes/angular-builders.test.ts @@ -107,7 +107,7 @@ describe('is not Nx project', () => { () => ({ hasStorybookBuilder: true, - } as any) + }) as any ); }); @@ -133,7 +133,7 @@ describe('is not Nx project', () => { project2: { root: 'project2', architect: {} }, }, rootProject: null, - } as any) + }) as any ); }); @@ -158,7 +158,7 @@ describe('is not Nx project', () => { project1: { root: 'project1', architect: {} }, }, rootProject: 'project1', - } as any) + }) as any ); }); diff --git a/code/lib/cli/src/automigrate/fixes/new-frameworks.ts b/code/lib/cli/src/automigrate/fixes/new-frameworks.ts index 657372d70ea..f335d654050 100644 --- a/code/lib/cli/src/automigrate/fixes/new-frameworks.ts +++ b/code/lib/cli/src/automigrate/fixes/new-frameworks.ts @@ -218,10 +218,10 @@ export const newFrameworks: Fix = { ❌ Your project should be upgraded to use the framework package ${chalk.bold( newFrameworkPackage )}, but we detected that you are using Vite ${chalk.bold( - viteVersion - )}, which is unsupported in ${chalk.bold( - 'Storybook 7.0' - )}. Please upgrade Vite to ${chalk.bold('3.0.0 or higher')} and rerun this migration. + viteVersion + )}, which is unsupported in ${chalk.bold( + 'Storybook 7.0' + )}. Please upgrade Vite to ${chalk.bold('3.0.0 or higher')} and rerun this migration. `); } @@ -351,8 +351,8 @@ export const newFrameworks: Fix = { This migration is set to update your project to use the ${chalk.magenta( '@storybook/react-vite' )} framework, but Storybook provides a framework package specifically for Next.js projects: ${chalk.magenta( - '@storybook/nextjs' - )}. + '@storybook/nextjs' + )}. This package provides a better, out of the box experience for Next.js users, however it is only compatible with the Webpack 5 builder, so we can't automigrate for you, as you are using the Vite builder. If you switch this project to use Webpack 5 and rerun this migration, we can update your project. @@ -379,8 +379,8 @@ export const newFrameworks: Fix = { This migration is set to update your project to use the ${chalk.magenta( '@storybook/svelte-webpack5' )} framework, but Storybook provides a framework package specifically for SvelteKit projects: ${chalk.magenta( - '@storybook/sveltekit' - )}. + '@storybook/sveltekit' + )}. This package provides a better experience for SvelteKit users, however it is only compatible with the Vite builder, so we can't automigrate for you, as you are using the Webpack builder. diff --git a/code/lib/cli/src/automigrate/fixes/nodejs-requirement.ts b/code/lib/cli/src/automigrate/fixes/nodejs-requirement.ts index 4c3006b7a36..cf82bceb9ba 100644 --- a/code/lib/cli/src/automigrate/fixes/nodejs-requirement.ts +++ b/code/lib/cli/src/automigrate/fixes/nodejs-requirement.ts @@ -32,8 +32,8 @@ export const nodeJsRequirement: Fix = { We've detected that you're using Node ${chalk.bold( nodeVersion )} but Storybook 7 only supports Node ${chalk.bold( - 'v16.0.0' - )} and higher. You will either need to upgrade your Node version or keep using an older version of Storybook. + 'v16.0.0' + )} and higher. You will either need to upgrade your Node version or keep using an older version of Storybook. Please see the migration guide for more information: ${chalk.yellow( diff --git a/code/lib/cli/src/automigrate/fixes/sb-scripts.ts b/code/lib/cli/src/automigrate/fixes/sb-scripts.ts index 24ac7854ef4..5192ccd4e18 100644 --- a/code/lib/cli/src/automigrate/fixes/sb-scripts.ts +++ b/code/lib/cli/src/automigrate/fixes/sb-scripts.ts @@ -20,49 +20,52 @@ const logger = console; * which could actually be a custom script even though the name matches the legacy binary name */ export const getStorybookScripts = (allScripts: NonNullable) => { - return Object.keys(allScripts).reduce((acc, key) => { - const currentScript = allScripts[key]; - if (currentScript == null) { + return Object.keys(allScripts).reduce( + (acc, key) => { + const currentScript = allScripts[key]; + if (currentScript == null) { + return acc; + } + let isStorybookScript = false; + const allWordsFromScript = currentScript.split(' '); + const newScript = allWordsFromScript + .map((currentWord, index) => { + const previousWord = allWordsFromScript[index - 1]; + + // full word check, rather than regex which could be faulty + const isSbBinary = + currentWord === 'build-storybook' || + currentWord === 'start-storybook' || + currentWord === 'sb'; + + // in case people have scripts like `yarn start-storybook` + const isPrependedByPkgManager = + previousWord && + ['npx', 'run', 'yarn', 'pnpx', 'pnpm dlx'].some((cmd) => previousWord.includes(cmd)); + + if (isSbBinary && !isPrependedByPkgManager) { + isStorybookScript = true; + return currentWord + .replace('sb', 'storybook') + .replace('start-storybook', 'storybook dev') + .replace('build-storybook', 'storybook build'); + } + + return currentWord; + }) + .join(' '); + + if (isStorybookScript) { + acc[key] = { + before: currentScript, + after: newScript, + }; + } + return acc; - } - let isStorybookScript = false; - const allWordsFromScript = currentScript.split(' '); - const newScript = allWordsFromScript - .map((currentWord, index) => { - const previousWord = allWordsFromScript[index - 1]; - - // full word check, rather than regex which could be faulty - const isSbBinary = - currentWord === 'build-storybook' || - currentWord === 'start-storybook' || - currentWord === 'sb'; - - // in case people have scripts like `yarn start-storybook` - const isPrependedByPkgManager = - previousWord && - ['npx', 'run', 'yarn', 'pnpx', 'pnpm dlx'].some((cmd) => previousWord.includes(cmd)); - - if (isSbBinary && !isPrependedByPkgManager) { - isStorybookScript = true; - return currentWord - .replace('sb', 'storybook') - .replace('start-storybook', 'storybook dev') - .replace('build-storybook', 'storybook build'); - } - - return currentWord; - }) - .join(' '); - - if (isStorybookScript) { - acc[key] = { - before: currentScript, - after: newScript, - }; - } - - return acc; - }, {} as Record); + }, + {} as Record + ); }; /** @@ -111,10 +114,10 @@ export const sbScripts: Fix = { return dedent` We've detected you are using ${sbFormatted} with scripts from previous versions of Storybook. Starting in Storybook 7, the ${chalk.yellow('start-storybook')} and ${chalk.yellow( - 'build-storybook' - )} binaries have changed to ${chalk.magenta('storybook dev')} and ${chalk.magenta( - 'storybook build' - )} respectively. + 'build-storybook' + )} binaries have changed to ${chalk.magenta('storybook dev')} and ${chalk.magenta( + 'storybook build' + )} respectively. In order to work with ${sbFormatted}, your storybook scripts have to be adjusted to use the binary. We can adjust them for you: ${newScriptsMessage.join('\n\n')} @@ -129,10 +132,13 @@ export const sbScripts: Fix = { logger.info(`✅ Updating scripts in package.json`); logger.log(); if (!dryRun) { - const newScripts = Object.keys(storybookScripts).reduce((acc, scriptKey) => { - acc[scriptKey] = storybookScripts[scriptKey].after; - return acc; - }, {} as Record); + const newScripts = Object.keys(storybookScripts).reduce( + (acc, scriptKey) => { + acc[scriptKey] = storybookScripts[scriptKey].after; + return acc; + }, + {} as Record + ); logger.log(); diff --git a/code/lib/cli/src/automigrate/fixes/wrap-require-utils.ts b/code/lib/cli/src/automigrate/fixes/wrap-require-utils.ts index 99bf4b8d550..ef06f654a65 100644 --- a/code/lib/cli/src/automigrate/fixes/wrap-require-utils.ts +++ b/code/lib/cli/src/automigrate/fixes/wrap-require-utils.ts @@ -47,8 +47,8 @@ export function getRequireWrapperName(config: ConfigFile) { doesVariableOrFunctionDeclarationExist(node, 'wrapForPnp') ? ['wrapForPnp'] : doesVariableOrFunctionDeclarationExist(node, defaultRequireWrapperName) - ? [defaultRequireWrapperName] - : [] + ? [defaultRequireWrapperName] + : [] ); if (declarationName.length) { diff --git a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts index e23c29dcea4..4c51a53224e 100644 --- a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts +++ b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts @@ -92,8 +92,8 @@ export function getMigrationSummary({ const title = hasNoFixes ? 'No migrations were applicable to your project' : hasFailures - ? 'Migration check ran with failures' - : 'Migration check ran successfully'; + ? 'Migration check ran with failures' + : 'Migration check ran successfully'; return boxen(messages.filter(Boolean).join(segmentDivider), { borderStyle: 'round', diff --git a/code/lib/cli/src/automigrate/helpers/new-frameworks-utils.ts b/code/lib/cli/src/automigrate/helpers/new-frameworks-utils.ts index 7f62392c683..2232993d9aa 100644 --- a/code/lib/cli/src/automigrate/helpers/new-frameworks-utils.ts +++ b/code/lib/cli/src/automigrate/helpers/new-frameworks-utils.ts @@ -107,12 +107,10 @@ export const detectBuilderInfo = async ({ // if builder is still not detected, rely on package dependencies if (!builderOrFrameworkName) { - const storybookBuilderViteVersion = await packageManager.getPackageVersion( - '@storybook/builder-vite' - ); - const storybookBuilderVite2Version = await packageManager.getPackageVersion( - 'storybook-builder-vite' - ); + const storybookBuilderViteVersion = + await packageManager.getPackageVersion('@storybook/builder-vite'); + const storybookBuilderVite2Version = + await packageManager.getPackageVersion('storybook-builder-vite'); const storybookBuilderWebpack5Version = await packageManager.getPackageVersion( '@storybook/builder-webpack5' ); diff --git a/code/lib/cli/src/detect.ts b/code/lib/cli/src/detect.ts index 0e6878c43c8..1138b84e016 100644 --- a/code/lib/cli/src/detect.ts +++ b/code/lib/cli/src/detect.ts @@ -185,9 +185,8 @@ export async function detectLanguage(packageManager: JsPackageManager) { '@typescript-eslint/parser' ); - const eslintPluginStorybookVersion = await packageManager.getPackageVersion( - 'eslint-plugin-storybook' - ); + const eslintPluginStorybookVersion = + await packageManager.getPackageVersion('eslint-plugin-storybook'); if (isTypescriptDirectDependency && typescriptVersion) { if ( diff --git a/code/lib/cli/src/doctor/getIncompatibleAddons.ts b/code/lib/cli/src/doctor/getIncompatibleAddons.ts index 465ad661a89..0a0fc5dc2d1 100644 --- a/code/lib/cli/src/doctor/getIncompatibleAddons.ts +++ b/code/lib/cli/src/doctor/getIncompatibleAddons.ts @@ -52,7 +52,7 @@ export const getIncompatibleAddons = async ( ({ name: addon, version: await packageManager.getPackageVersion(addon), - } as { name: keyof typeof incompatibleList; version: string }) + }) as { name: keyof typeof incompatibleList; version: string } ) ); diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index 75d12dc0149..2e4a3120ac0 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -355,9 +355,8 @@ export async function baseGenerator( try { if (process.env.CI !== 'true') { - const { hasEslint, isStorybookPluginInstalled, eslintConfigFile } = await extractEslintInfo( - packageManager - ); + const { hasEslint, isStorybookPluginInstalled, eslintConfigFile } = + await extractEslintInfo(packageManager); if (hasEslint && !isStorybookPluginInstalled) { if (skipPrompts || (await suggestESLintPlugin())) { diff --git a/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts b/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts index 2dd3251ead6..c57de55e1d2 100644 --- a/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts +++ b/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts @@ -192,7 +192,7 @@ export class Yarn1Proxy extends JsPackageManager { const existingVersions: Record = {}; const duplicatedDependencies: Record = {}; - const recurse = (tree: typeof trees[0]) => { + const recurse = (tree: (typeof trees)[0]) => { const { children } = tree; const { name, value } = parsePackageData(tree.name); if (!name || !name.includes('storybook')) return; diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index efdf01f0a45..10c8c0426a4 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -426,8 +426,8 @@ export class GenerateNewProjectOnInitError extends StorybookError { template() { return dedent` There was an error while using ${this.data.packageManager} to create a new ${ - this.data.projectType - } project. + this.data.projectType + } project. ${this.data.error instanceof Error ? this.data.error.message : ''} `; diff --git a/code/lib/core-server/src/utils/StoryIndexGenerator.ts b/code/lib/core-server/src/utils/StoryIndexGenerator.ts index 96e72091073..ae84c39cdba 100644 --- a/code/lib/core-server/src/utils/StoryIndexGenerator.ts +++ b/code/lib/core-server/src/utils/StoryIndexGenerator.ts @@ -538,10 +538,13 @@ export class StoryIndexGenerator { sortStoriesV7(sortableStories, storySortParameter, fileNameOrder); } - return sortableStories.reduce((acc, item) => { - acc[item.id] = item; - return acc; - }, {} as StoryIndex['entries']); + return sortableStories.reduce( + (acc, item) => { + acc[item.id] = item; + return acc; + }, + {} as StoryIndex['entries'] + ); } async getIndex() { diff --git a/code/lib/core-server/src/utils/build-or-throw.ts b/code/lib/core-server/src/utils/build-or-throw.ts index 5c1746a0be2..ead45e5a4e3 100644 --- a/code/lib/core-server/src/utils/build-or-throw.ts +++ b/code/lib/core-server/src/utils/build-or-throw.ts @@ -6,8 +6,8 @@ export async function buildOrThrow(callback: () => Promise): Promise { } catch (err: any) { const builderErrors = err.errors as { text: string }[]; if (builderErrors) { - const inconsistentVersionsError = builderErrors.find((er) => - er.text?.includes('No matching export') + const inconsistentVersionsError = builderErrors.find( + (er) => er.text?.includes('No matching export') ); if (inconsistentVersionsError) { diff --git a/code/lib/core-server/src/withTelemetry.test.ts b/code/lib/core-server/src/withTelemetry.test.ts index 639fbc82f97..99b6d99e117 100644 --- a/code/lib/core-server/src/withTelemetry.test.ts +++ b/code/lib/core-server/src/withTelemetry.test.ts @@ -79,7 +79,7 @@ describe('withTelemetry', () => { it('does not send full error message when crash reports are disabled', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ enableCrashReports: false } as any), + apply: async () => ({ enableCrashReports: false }) as any, }); await expect(async () => withTelemetry( @@ -99,7 +99,7 @@ describe('withTelemetry', () => { it('does send error message when crash reports are enabled', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ enableCrashReports: true } as any), + apply: async () => ({ enableCrashReports: true }) as any, }); await expect(async () => @@ -120,7 +120,7 @@ describe('withTelemetry', () => { it('does not send any error message when telemetry is disabled', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ disableTelemetry: true } as any), + apply: async () => ({ disableTelemetry: true }) as any, }); await expect(async () => @@ -141,7 +141,7 @@ describe('withTelemetry', () => { it('does send error messages when telemetry is disabled, but crash reports are enabled', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ disableTelemetry: true, enableCrashReports: true } as any), + apply: async () => ({ disableTelemetry: true, enableCrashReports: true }) as any, }); await expect(async () => @@ -162,7 +162,7 @@ describe('withTelemetry', () => { it('does not send full error messages when disabled crash reports are cached', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(false); @@ -184,7 +184,7 @@ describe('withTelemetry', () => { it('does send error messages when enabled crash reports are cached', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(true); @@ -206,7 +206,7 @@ describe('withTelemetry', () => { it('does not send full error messages when disabled crash reports are prompted', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(undefined); vi.mocked(prompts).mockResolvedValueOnce({ enableCrashReports: false }); @@ -229,7 +229,7 @@ describe('withTelemetry', () => { it('does send error messages when enabled crash reports are prompted', async () => { vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(undefined); vi.mocked(prompts).mockResolvedValueOnce({ enableCrashReports: true }); @@ -386,7 +386,7 @@ describe('getErrorLevel', () => { }; vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ enableCrashReports: true } as any), + apply: async () => ({ enableCrashReports: true }) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(false); @@ -405,7 +405,7 @@ describe('getErrorLevel', () => { }; vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ enableCrashReports: false } as any), + apply: async () => ({ enableCrashReports: false }) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(false); @@ -424,7 +424,7 @@ describe('getErrorLevel', () => { }; vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({ disableTelemetry: true } as any), + apply: async () => ({ disableTelemetry: true }) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(false); @@ -444,7 +444,7 @@ describe('getErrorLevel', () => { vi.mocked(cache.get).mockResolvedValueOnce(true); vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); const errorLevel = await getErrorLevel(options); @@ -462,7 +462,7 @@ describe('getErrorLevel', () => { }; vi.mocked(loadAllPresets).mockResolvedValueOnce({ - apply: async () => ({} as any), + apply: async () => ({}) as any, }); vi.mocked(cache.get).mockResolvedValueOnce(undefined); diff --git a/code/lib/csf-tools/src/CsfFile.ts b/code/lib/csf-tools/src/CsfFile.ts index 897f6b2e0b0..b7e187a0d02 100644 --- a/code/lib/csf-tools/src/CsfFile.ts +++ b/code/lib/csf-tools/src/CsfFile.ts @@ -100,11 +100,14 @@ const parseExportsOrder = (init: t.Expression) => { }; const sortExports = (exportByName: Record, order: string[]) => { - return order.reduce((acc, name) => { - const namedExport = exportByName[name]; - if (namedExport) acc[name] = namedExport; - return acc; - }, {} as Record); + return order.reduce( + (acc, name) => { + const namedExport = exportByName[name]; + if (namedExport) acc[name] = namedExport; + return acc; + }, + {} as Record + ); }; export interface CsfOptions { @@ -491,35 +494,38 @@ export class CsfFile { if (self._metaAnnotations.play) { self._meta.tags = [...(self._meta.tags || []), 'play-fn']; } - self._stories = entries.reduce((acc, [key, story]) => { - if (!isExportStory(key, self._meta as StaticMeta)) { - return acc; - } - const id = - story.parameters?.__id ?? - toId((self._meta?.id || self._meta?.title) as string, storyNameFromExport(key)); - const parameters: Record = { ...story.parameters, __id: id }; + self._stories = entries.reduce( + (acc, [key, story]) => { + if (!isExportStory(key, self._meta as StaticMeta)) { + return acc; + } + const id = + story.parameters?.__id ?? + toId((self._meta?.id || self._meta?.title) as string, storyNameFromExport(key)); + const parameters: Record = { ...story.parameters, __id: id }; - const { includeStories } = self._meta || {}; - if ( - key === '__page' && - (entries.length === 1 || (Array.isArray(includeStories) && includeStories.length === 1)) - ) { - parameters.docsOnly = true; - } - acc[key] = { ...story, id, parameters }; - const { tags, play } = self._storyAnnotations[key]; - if (tags) { - const node = t.isIdentifier(tags) - ? findVarInitialization(tags.name, this._ast.program) - : tags; - acc[key].tags = parseTags(node); - } - if (play) { - acc[key].tags = [...(acc[key].tags || []), 'play-fn']; - } - return acc; - }, {} as Record); + const { includeStories } = self._meta || {}; + if ( + key === '__page' && + (entries.length === 1 || (Array.isArray(includeStories) && includeStories.length === 1)) + ) { + parameters.docsOnly = true; + } + acc[key] = { ...story, id, parameters }; + const { tags, play } = self._storyAnnotations[key]; + if (tags) { + const node = t.isIdentifier(tags) + ? findVarInitialization(tags.name, this._ast.program) + : tags; + acc[key].tags = parseTags(node); + } + if (play) { + acc[key].tags = [...(acc[key].tags || []), 'play-fn']; + } + return acc; + }, + {} as Record + ); Object.keys(self._storyExports).forEach((key) => { if (!isExportStory(key, self._meta as StaticMeta)) { diff --git a/code/lib/instrumenter/src/instrumenter.ts b/code/lib/instrumenter/src/instrumenter.ts index ef171b4bcd0..c7acf016b22 100644 --- a/code/lib/instrumenter/src/instrumenter.ts +++ b/code/lib/instrumenter/src/instrumenter.ts @@ -248,12 +248,15 @@ export class Instrumenter { cleanup() { // Reset stories with retained state to their initial state, and drop the rest. - this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => { - const retainedState = getRetainedState(state); - if (!retainedState) return acc; - acc[storyId] = Object.assign(getInitialState(), retainedState); - return acc; - }, {} as Record); + this.state = Object.entries(this.state).reduce( + (acc, [storyId, state]) => { + const retainedState = getRetainedState(state); + if (!retainedState) return acc; + acc[storyId] = Object.assign(getInitialState(), retainedState); + return acc; + }, + {} as Record + ); const payload: SyncPayload = { controlStates: controlsDisabled, logItems: [] }; this.channel.emit(EVENTS.SYNC, payload); // @ts-expect-error (TS doesn't know about this global variable) diff --git a/code/lib/manager-api/src/lib/addons.ts b/code/lib/manager-api/src/lib/addons.ts index bbcffff4649..860a23b359f 100644 --- a/code/lib/manager-api/src/lib/addons.ts +++ b/code/lib/manager-api/src/lib/addons.ts @@ -104,7 +104,7 @@ export class AddonStore { | Addon_Types | Addon_TypesEnum.experimental_PAGE | Addon_TypesEnum.experimental_SIDEBAR_BOTTOM - | Addon_TypesEnum.experimental_SIDEBAR_TOP + | Addon_TypesEnum.experimental_SIDEBAR_TOP, >(type: T): Addon_Collection | any { if (!this.elements[type]) { this.elements[type] = {}; diff --git a/code/lib/manager-api/src/lib/stories.ts b/code/lib/manager-api/src/lib/stories.ts index dffc3dd45a8..5df933d3fd5 100644 --- a/code/lib/manager-api/src/lib/stories.ts +++ b/code/lib/manager-api/src/lib/stories.ts @@ -92,16 +92,19 @@ export const transformSetStoriesStoryDataToPreparedStoryIndex = ( export const transformStoryIndexV2toV3 = (index: StoryIndexV2): StoryIndexV3 => { return { v: 3, - stories: Object.values(index.stories).reduce((acc, entry) => { - acc[entry.id] = { - ...entry, - title: entry.kind, - name: entry.name || entry.story, - importPath: entry.parameters.fileName || '', - }; + stories: Object.values(index.stories).reduce( + (acc, entry) => { + acc[entry.id] = { + ...entry, + title: entry.kind, + name: entry.name || entry.story, + importPath: entry.parameters.fileName || '', + }; - return acc; - }, {} as StoryIndexV3['stories']), + return acc; + }, + {} as StoryIndexV3['stories'] + ), }; }; @@ -109,27 +112,30 @@ export const transformStoryIndexV3toV4 = (index: StoryIndexV3): API_PreparedStor const countByTitle = countBy(Object.values(index.stories), 'title'); return { v: 4, - entries: Object.values(index.stories).reduce((acc, entry: any) => { - let type: IndexEntry['type'] = 'story'; - if ( - entry.parameters?.docsOnly || - (entry.name === 'Page' && countByTitle[entry.title] === 1) - ) { - type = 'docs'; - } - acc[entry.id] = { - type, - ...(type === 'docs' && { tags: ['stories-mdx'], storiesImports: [] }), - ...entry, - }; + entries: Object.values(index.stories).reduce( + (acc, entry: any) => { + let type: IndexEntry['type'] = 'story'; + if ( + entry.parameters?.docsOnly || + (entry.name === 'Page' && countByTitle[entry.title] === 1) + ) { + type = 'docs'; + } + acc[entry.id] = { + type, + ...(type === 'docs' && { tags: ['stories-mdx'], storiesImports: [] }), + ...entry, + }; - // @ts-expect-error (we're removing something that should not be there) - delete acc[entry.id].story; - // @ts-expect-error (we're removing something that should not be there) - delete acc[entry.id].kind; + // @ts-expect-error (we're removing something that should not be there) + delete acc[entry.id].story; + // @ts-expect-error (we're removing something that should not be there) + delete acc[entry.id].kind; - return acc; - }, {} as API_PreparedStoryIndex['entries']), + return acc; + }, + {} as API_PreparedStoryIndex['entries'] + ), }; }; diff --git a/code/lib/manager-api/src/modules/addons.ts b/code/lib/manager-api/src/modules/addons.ts index c0084552d85..6eb8ef82aa6 100644 --- a/code/lib/manager-api/src/modules/addons.ts +++ b/code/lib/manager-api/src/modules/addons.ts @@ -28,7 +28,7 @@ export interface SubAPI { | Addon_Types | Addon_TypesEnum.experimental_PAGE | Addon_TypesEnum.experimental_SIDEBAR_BOTTOM - | Addon_TypesEnum.experimental_SIDEBAR_TOP = Addon_Types + | Addon_TypesEnum.experimental_SIDEBAR_TOP = Addon_Types, >( type: T ) => Addon_Collection; diff --git a/code/lib/manager-api/src/modules/whatsnew.ts b/code/lib/manager-api/src/modules/whatsnew.ts index ab460aa1148..eeeb9558a59 100644 --- a/code/lib/manager-api/src/modules/whatsnew.ts +++ b/code/lib/manager-api/src/modules/whatsnew.ts @@ -57,10 +57,11 @@ export const init: ModuleFn = ({ fullAPI, store, provider }) => { function getLatestWhatsNewPost(): Promise { provider.channel?.emit(REQUEST_WHATS_NEW_DATA); - return new Promise((resolve) => - provider.channel?.once(RESULT_WHATS_NEW_DATA, ({ data }: { data: WhatsNewData }) => - resolve(data) - ) + return new Promise( + (resolve) => + provider.channel?.once(RESULT_WHATS_NEW_DATA, ({ data }: { data: WhatsNewData }) => + resolve(data) + ) ); } diff --git a/code/lib/preview-api/src/modules/addons/hooks.ts b/code/lib/preview-api/src/modules/addons/hooks.ts index e7a747d571f..7ed8f9b2ec1 100644 --- a/code/lib/preview-api/src/modules/addons/hooks.ts +++ b/code/lib/preview-api/src/modules/addons/hooks.ts @@ -221,14 +221,14 @@ const invalidHooksError = () => function getHooksContextOrNull< TRenderer extends Renderer, - TArgs extends Args = Args + TArgs extends Args = Args, >(): HooksContext | null { return global.STORYBOOK_HOOKS_CONTEXT || null; } function getHooksContextOrThrow< TRenderer extends Renderer, - TArgs extends Args = Args + TArgs extends Args = Args, >(): HooksContext { const hooks = getHooksContextOrNull(); if (hooks == null) { @@ -530,7 +530,7 @@ export function useChannel(eventMap: EventMap, deps: any[] = []) { */ export function useStoryContext< TRenderer extends Renderer, - TArgs extends Args = Args + TArgs extends Args = Args, >(): StoryContext { const { currentContext } = getHooksContextOrThrow(); if (currentContext == null) { @@ -576,7 +576,7 @@ export function useParameter(parameterKey: string, defaultValue?: S): S | und export function useArgs(): [ TArgs, (newArgs: Partial) => void, - (argNames?: (keyof TArgs)[]) => void + (argNames?: (keyof TArgs)[]) => void, ] { const channel = addons.getChannel(); const { id: storyId, args } = useStoryContext(); diff --git a/code/lib/preview-api/src/modules/client-api/StoryStoreFacade.ts b/code/lib/preview-api/src/modules/client-api/StoryStoreFacade.ts index ccd95120b45..8833d57c31e 100644 --- a/code/lib/preview-api/src/modules/client-api/StoryStoreFacade.ts +++ b/code/lib/preview-api/src/modules/client-api/StoryStoreFacade.ts @@ -110,13 +110,16 @@ export class StoryStoreFacade { } throw err; } - const entries = sortedV7.reduce((acc, s) => { - // We use the original entry we stored in `this.stories` because it is possible that the CSF file itself - // exports a `parameters.fileName` which can be different and mess up our `importFn`. - // NOTE: this doesn't actually change the story object, just the index. - acc[s.id] = this.entries[s.id]; - return acc; - }, {} as StoryIndex['entries']); + const entries = sortedV7.reduce( + (acc, s) => { + // We use the original entry we stored in `this.stories` because it is possible that the CSF file itself + // exports a `parameters.fileName` which can be different and mess up our `importFn`. + // NOTE: this doesn't actually change the story object, just the index. + acc[s.id] = this.entries[s.id]; + return acc; + }, + {} as StoryIndex['entries'] + ); return { v: 4, entries }; } diff --git a/code/lib/preview-api/src/modules/core-client/start.test.ts b/code/lib/preview-api/src/modules/core-client/start.test.ts index cb29c9964f7..aa6f69cd725 100644 --- a/code/lib/preview-api/src/modules/core-client/start.test.ts +++ b/code/lib/preview-api/src/modules/core-client/start.test.ts @@ -83,7 +83,7 @@ beforeEach(() => { const start: typeof realStart = (...args) => { const result = realStart(...args); - const configure: typeof result['configure'] = ( + const configure: (typeof result)['configure'] = ( framework: string, loadable: Loadable, m?: NodeModule, diff --git a/code/lib/preview-api/src/modules/preview-web/PreviewWeb.mockdata.ts b/code/lib/preview-api/src/modules/preview-web/PreviewWeb.mockdata.ts index 08d14639aad..88dae40068d 100644 --- a/code/lib/preview-api/src/modules/preview-web/PreviewWeb.mockdata.ts +++ b/code/lib/preview-api/src/modules/preview-web/PreviewWeb.mockdata.ts @@ -57,7 +57,7 @@ export const importFn: Mocked = vi.fn( './src/ComponentTwo.stories.js': componentTwoExports, './src/Introduction.mdx': unattachedDocsExports, './src/ExtraComponentOne.stories.js': extraComponentOneExports, - }[path] || {}) + })[path] || {} ); export const docsRenderer = { diff --git a/code/lib/preview-api/src/modules/preview-web/WebView.ts b/code/lib/preview-api/src/modules/preview-web/WebView.ts index 6f02568934c..e3a7d360ac2 100644 --- a/code/lib/preview-api/src/modules/preview-web/WebView.ts +++ b/code/lib/preview-api/src/modules/preview-web/WebView.ts @@ -38,7 +38,7 @@ const ansiConverter = new AnsiToHtml({ }); export class WebView implements View { - private currentLayoutClass?: typeof layoutClassMap[keyof typeof layoutClassMap] | null; + private currentLayoutClass?: (typeof layoutClassMap)[keyof typeof layoutClassMap] | null; private testing = false; diff --git a/code/lib/preview-api/src/modules/store/StoryIndexStore.ts b/code/lib/preview-api/src/modules/store/StoryIndexStore.ts index 03e8a129b9b..803e9655358 100644 --- a/code/lib/preview-api/src/modules/store/StoryIndexStore.ts +++ b/code/lib/preview-api/src/modules/store/StoryIndexStore.ts @@ -12,10 +12,13 @@ import { MissingStoryAfterHmrError } from '@storybook/core-events/preview-errors export type StorySpecifier = StoryId | { name: StoryName; title: ComponentTitle } | '*'; const getImportPathMap = memoize(1)((entries: StoryIndex['entries']) => - Object.values(entries).reduce((acc, entry) => { - acc[entry.importPath] = acc[entry.importPath] || entry; - return acc; - }, {} as Record) + Object.values(entries).reduce( + (acc, entry) => { + acc[entry.importPath] = acc[entry.importPath] || entry; + return acc; + }, + {} as Record + ) ); export class StoryIndexStore { diff --git a/code/lib/preview-api/src/modules/store/StoryStore.ts b/code/lib/preview-api/src/modules/store/StoryStore.ts index 1fc0fa547d2..dded78f856b 100644 --- a/code/lib/preview-api/src/modules/store/StoryStore.ts +++ b/code/lib/preview-api/src/modules/store/StoryStore.ts @@ -185,10 +185,13 @@ export class StoryStore { }; return loadInBatches(importPaths).then((list) => - list.reduce((acc, { importPath, csfFile }) => { - acc[importPath] = csfFile; - return acc; - }, {} as Record>) + list.reduce( + (acc, { importPath, csfFile }) => { + acc[importPath] = csfFile; + return acc; + }, + {} as Record> + ) ); } diff --git a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts index 311a4467c78..cb93df64116 100644 --- a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts +++ b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts @@ -228,7 +228,7 @@ function preparePartialAnnotations( // eg. reactive proxies set by frameworks like SolidJS or Vue export function prepareContext< TRenderer extends Renderer, - TContext extends Pick, 'args' | 'argTypes' | 'globals'> + TContext extends Pick, 'args' | 'argTypes' | 'globals'>, >( context: TContext ): TContext & Pick, 'allArgs' | 'argsByTarget' | 'unmappedArgs'> { diff --git a/code/lib/router/src/utils.ts b/code/lib/router/src/utils.ts index 94d1d686053..c7cefd89bad 100644 --- a/code/lib/router/src/utils.ts +++ b/code/lib/router/src/utils.ts @@ -14,27 +14,27 @@ export interface StoryData { const splitPathRegex = /\/([^/]+)\/(?:(.*)_)?([^/]+)?/; -export const parsePath: (path: string | undefined) => StoryData = memoize(1000)( - (path: string | undefined | null) => { - const result: StoryData = { - viewMode: undefined, - storyId: undefined, - refId: undefined, - }; +export const parsePath: (path: string | undefined) => StoryData = memoize(1000)(( + path: string | undefined | null +) => { + const result: StoryData = { + viewMode: undefined, + storyId: undefined, + refId: undefined, + }; - if (path) { - const [, viewMode, refId, storyId] = path.toLowerCase().match(splitPathRegex) || []; - if (viewMode) { - Object.assign(result, { - viewMode, - storyId, - refId, - }); - } + if (path) { + const [, viewMode, refId, storyId] = path.toLowerCase().match(splitPathRegex) || []; + if (viewMode) { + Object.assign(result, { + viewMode, + storyId, + refId, + }); } - return result; } -); + return result; +}); interface Args { [key: string]: any; @@ -157,27 +157,29 @@ export const stringifyQuery = (query: Query) => type Match = { path: string }; -export const getMatch = memoize(1000)( - (current: string, target: string | RegExp, startsWith = true): Match | null => { - if (startsWith) { - if (typeof target !== 'string') { - throw new Error('startsWith only works with string targets'); - } - const startsWithTarget = current && current.startsWith(target); - if (startsWithTarget) { - return { path: current }; - } - - return null; +export const getMatch = memoize(1000)(( + current: string, + target: string | RegExp, + startsWith = true +): Match | null => { + if (startsWith) { + if (typeof target !== 'string') { + throw new Error('startsWith only works with string targets'); } - - const currentIsTarget = typeof target === 'string' && current === target; - const matchTarget = current && target && current.match(target); - - if (currentIsTarget || matchTarget) { + const startsWithTarget = current && current.startsWith(target); + if (startsWithTarget) { return { path: current }; } return null; } -); + + const currentIsTarget = typeof target === 'string' && current === target; + const matchTarget = current && target && current.match(target); + + if (currentIsTarget || matchTarget) { + return { path: current }; + } + + return null; +}); diff --git a/code/lib/theming/src/global.ts b/code/lib/theming/src/global.ts index 84e3debd6a3..499d59cb224 100644 --- a/code/lib/theming/src/global.ts +++ b/code/lib/theming/src/global.ts @@ -84,30 +84,28 @@ export const createReset = memoize(1)( }) ); -export const createGlobal = memoize(1)( - ({ - color, - background, - typography, - }: { - color: Color; - background: Background; - typography: Typography; - }): Return => { - const resetStyles = createReset({ typography }); - return { - ...resetStyles, - body: { - ...resetStyles.body, - color: color.defaultText, - background: background.app, - overflow: 'hidden', - }, +export const createGlobal = memoize(1)(({ + color, + background, + typography, +}: { + color: Color; + background: Background; + typography: Typography; +}): Return => { + const resetStyles = createReset({ typography }); + return { + ...resetStyles, + body: { + ...resetStyles.body, + color: color.defaultText, + background: background.app, + overflow: 'hidden', + }, - hr: { - ...resetStyles.hr, - borderTop: `1px solid ${color.border}`, - }, - }; - } -); + hr: { + ...resetStyles.hr, + borderTop: `1px solid ${color.border}`, + }, + }; +}); diff --git a/code/lib/types/src/modules/addons.ts b/code/lib/types/src/modules/addons.ts index 49d97e4c3a1..d4747f236fa 100644 --- a/code/lib/types/src/modules/addons.ts +++ b/code/lib/types/src/modules/addons.ts @@ -172,7 +172,7 @@ export type Addon_BaseDecorators = Array< export interface Addon_BaseAnnotations< TArgs, StoryFnReturnType, - TRenderer extends Renderer = Renderer + TRenderer extends Renderer = Renderer, > { /** * Dynamic data that are provided (and possibly updated by) Storybook and its addons. diff --git a/code/lib/types/src/modules/composedStory.ts b/code/lib/types/src/modules/composedStory.ts index a8902426aba..379bcb72890 100644 --- a/code/lib/types/src/modules/composedStory.ts +++ b/code/lib/types/src/modules/composedStory.ts @@ -53,7 +53,7 @@ export type PartialArgsStoryFn = PartialArgsStoryFn & { play: ComposedStoryPlayFn; args: TArgs; diff --git a/code/lib/types/src/modules/docs.ts b/code/lib/types/src/modules/docs.ts index ba52f2b7c13..6088c9c2a65 100644 --- a/code/lib/types/src/modules/docs.ts +++ b/code/lib/types/src/modules/docs.ts @@ -32,7 +32,7 @@ export type ResolvedModuleExportType = 'component' | 'meta' | 'story'; */ export type ResolvedModuleExportFromType< TType extends ResolvedModuleExportType, - TRenderer extends Renderer = Renderer + TRenderer extends Renderer = Renderer, > = TType extends 'component' ? { type: 'component'; @@ -40,8 +40,8 @@ export type ResolvedModuleExportFromType< projectAnnotations: NormalizedProjectAnnotations; } : TType extends 'meta' - ? { type: 'meta'; csfFile: CSFFile; preparedMeta: PreparedMeta } - : { type: 'story'; story: PreparedStory }; + ? { type: 'meta'; csfFile: CSFFile; preparedMeta: PreparedMeta } + : { type: 'story'; story: PreparedStory }; export type ResolvedModuleExport = { type: ResolvedModuleExportType; diff --git a/code/presets/react-webpack/src/framework-preset-react-docs.test.ts b/code/presets/react-webpack/src/framework-preset-react-docs.test.ts index c762e084105..67f7c971572 100644 --- a/code/presets/react-webpack/src/framework-preset-react-docs.test.ts +++ b/code/presets/react-webpack/src/framework-preset-react-docs.test.ts @@ -114,7 +114,7 @@ describe('framework-preset-react-docgen', () => { ({ check: false, reactDocgen: false, - } as Partial), + }) as Partial, }, presetsList: presetsListWithDocs, }); @@ -136,7 +136,7 @@ describe('framework-preset-react-docgen', () => { ({ check: false, reactDocgen: 'react-docgen-typescript', - } as Partial), + }) as Partial, }, presetsList: [], }); diff --git a/code/renderers/html/src/docs/sourceDecorator.test.ts b/code/renderers/html/src/docs/sourceDecorator.test.ts index 9d85fab19d2..3b3cc587a66 100644 --- a/code/renderers/html/src/docs/sourceDecorator.test.ts +++ b/code/renderers/html/src/docs/sourceDecorator.test.ts @@ -33,7 +33,7 @@ const makeContext = (name: string, parameters: any, args: any, extra?: object): initialArgs: {}, ...extra, - } as StoryContext); + }) as StoryContext; describe('sourceDecorator', () => { let mockChannel: { on: Mock; emit?: Mock }; diff --git a/code/renderers/react/src/docs/jsxDecorator.test.tsx b/code/renderers/react/src/docs/jsxDecorator.test.tsx index ee9a3c68671..a2f95bb6a09 100644 --- a/code/renderers/react/src/docs/jsxDecorator.test.tsx +++ b/code/renderers/react/src/docs/jsxDecorator.test.tsx @@ -113,12 +113,11 @@ describe('renderJsx', () => { }); it('forwardRef component', () => { - const MyExoticComponentRef = React.forwardRef(function MyExoticComponent( - props, - _ref - ) { - return
{props.children}
; - }); + const MyExoticComponentRef = React.forwardRef( + function MyExoticComponent(props, _ref) { + return
{props.children}
; + } + ); expect(renderJsx(createElement(MyExoticComponentRef, {}, 'I am forwardRef!'), {})) .toMatchInlineSnapshot(` diff --git a/code/renderers/react/src/public-types.ts b/code/renderers/react/src/public-types.ts index eaacc7fa14d..2481491c39b 100644 --- a/code/renderers/react/src/public-types.ts +++ b/code/renderers/react/src/public-types.ts @@ -46,7 +46,7 @@ export type StoryObj = [TMetaOrCmpOrArgs] extends [ render?: ArgsStoryFn; component?: infer Component; args?: infer DefaultArgs; - } + }, ] ? Simplify< (Component extends ComponentType ? ComponentProps : unknown) & @@ -59,8 +59,8 @@ export type StoryObj = [TMetaOrCmpOrArgs] extends [ > : never : TMetaOrCmpOrArgs extends ComponentType - ? StoryAnnotations> - : StoryAnnotations; + ? StoryAnnotations> + : StoryAnnotations; // This performs a downcast to function types that are mocks, when a mock fn is given to meta args. type AddMocks = Simplify<{ diff --git a/code/renderers/svelte/src/public-types.ts b/code/renderers/svelte/src/public-types.ts index 3e5abbb2867..99dba8d0778 100644 --- a/code/renderers/svelte/src/public-types.ts +++ b/code/renderers/svelte/src/public-types.ts @@ -55,8 +55,8 @@ export type StoryObj = MetaOrCmpOrArgs extends { > : never : MetaOrCmpOrArgs extends SvelteComponentTyped - ? StoryAnnotations, ComponentProps> - : StoryAnnotations; + ? StoryAnnotations, ComponentProps> + : StoryAnnotations; export type { SvelteRenderer }; export type Decorator = DecoratorFunction; diff --git a/code/renderers/svelte/src/types.ts b/code/renderers/svelte/src/types.ts index e30b2e8f549..43d42e01067 100644 --- a/code/renderers/svelte/src/types.ts +++ b/code/renderers/svelte/src/types.ts @@ -24,7 +24,7 @@ interface MountProps { type ComponentType< Props extends Record = any, - Events extends Record = any + Events extends Record = any, > = new (options: ComponentConstructorOptions) => { [P in keyof SvelteComponentTyped as P extends `$$${string}` ? never @@ -41,7 +41,7 @@ export interface SvelteRenderer = any, - Events extends Record = any + Events extends Record = any, > { Component?: ComponentType; on?: Record extends Events diff --git a/code/renderers/vue3/src/docs/sourceDecorator.ts b/code/renderers/vue3/src/docs/sourceDecorator.ts index e0820db75cb..aecdb01fabb 100644 --- a/code/renderers/vue3/src/docs/sourceDecorator.ts +++ b/code/renderers/vue3/src/docs/sourceDecorator.ts @@ -86,7 +86,7 @@ function mapAttributesAndDirectives(props: Args) { loc: { source: attributeSource(tranformKey(key), props[key]) }, // attribute value or directive value exp: { isStatic: false, loc: { source: props[key] } }, // directive expression modifiers: [''], - } as unknown as AttributeNode) + }) as unknown as AttributeNode ); } /** diff --git a/code/renderers/vue3/src/public-types.ts b/code/renderers/vue3/src/public-types.ts index 2bc2653eb0c..70076859cde 100644 --- a/code/renderers/vue3/src/public-types.ts +++ b/code/renderers/vue3/src/public-types.ts @@ -71,8 +71,8 @@ export type ComponentPropsAndSlots = ComponentProps & ExtractSlots; type ComponentPropsOrProps = TCmpOrArgs extends Constructor ? ComponentPropsAndSlots : TCmpOrArgs extends FunctionalComponent - ? ComponentPropsAndSlots - : TCmpOrArgs; + ? ComponentPropsAndSlots + : TCmpOrArgs; export type Decorator = DecoratorFunction; export type Loader = LoaderFunction; diff --git a/code/renderers/web-components/src/docs/sourceDecorator.test.ts b/code/renderers/web-components/src/docs/sourceDecorator.test.ts index 119f4e786d3..8a1ac068c74 100644 --- a/code/renderers/web-components/src/docs/sourceDecorator.test.ts +++ b/code/renderers/web-components/src/docs/sourceDecorator.test.ts @@ -29,7 +29,7 @@ const makeContext = (name: string, parameters: any, args: any, extra?: Partial { let mockChannel: { on: Mock; emit?: Mock }; diff --git a/code/renderers/web-components/template/stories/demo-wc-card.stories.js b/code/renderers/web-components/template/stories/demo-wc-card.stories.js index 193a961c6bc..00a6b358efe 100644 --- a/code/renderers/web-components/template/stories/demo-wc-card.stories.js +++ b/code/renderers/web-components/template/stories/demo-wc-card.stories.js @@ -3,12 +3,11 @@ import './demo-wc-card'; export default { component: 'demo-wc-card', - render: ({ backSide, header, rows, prefix }) => - html` - ${prefix}A simple card - `, + render: ({ backSide, header, rows, prefix }) => html` + ${prefix}A simple card + `, }; export const Front = { diff --git a/code/ui/components/src/components/icon/icon.tsx b/code/ui/components/src/components/icon/icon.tsx index 28b78983b71..78850f5e793 100644 --- a/code/ui/components/src/components/icon/icon.tsx +++ b/code/ui/components/src/components/icon/icon.tsx @@ -5,7 +5,7 @@ import { styled } from '@storybook/theming'; import { deprecate, logger } from '@storybook/client-logger'; export type IconType = keyof typeof icons; -type NewIconTypes = typeof icons[IconType]; +type NewIconTypes = (typeof icons)[IconType]; const Svg = styled.svg` display: inline-block; diff --git a/code/ui/manager/src/components/preview/Preview.tsx b/code/ui/manager/src/components/preview/Preview.tsx index 7096c1d9bf4..e93e70dc411 100644 --- a/code/ui/manager/src/components/preview/Preview.tsx +++ b/code/ui/manager/src/components/preview/Preview.tsx @@ -238,7 +238,7 @@ function filterTabs(panels: Addon_BaseType[], parameters: Record) { const t = arrTabs.find((tab) => tab.id === panel.id); return t === undefined || t.id === 'canvas' || !t.hidden; }) - .map((panel, index) => ({ ...panel, index } as Addon_BaseType)) + .map((panel, index) => ({ ...panel, index }) as Addon_BaseType) .sort((p1, p2) => { /* eslint-disable @typescript-eslint/naming-convention */ const tab_1 = arrTabs.find((tab) => tab.id === p1.id); diff --git a/code/ui/manager/src/components/sidebar/Refs.tsx b/code/ui/manager/src/components/sidebar/Refs.tsx index 292a345f6dc..3ce49f5fbfe 100644 --- a/code/ui/manager/src/components/sidebar/Refs.tsx +++ b/code/ui/manager/src/components/sidebar/Refs.tsx @@ -77,94 +77,94 @@ const CollapseButton = styled.button(({ theme }) => ({ }, })); -export const Ref: FC = React.memo(function Ref( - props -) { - const { docsOptions } = useStorybookState(); - const api = useStorybookApi(); - const { - index, - id: refId, - title = refId, - isLoading: isLoadingMain, - isBrowsing, - selectedStoryId, - highlightedRef, - setHighlighted, - loginUrl, - type, - expanded = true, - indexError, - previewInitialized, - } = props; - const length = useMemo(() => (index ? Object.keys(index).length : 0), [index]); - const indicatorRef = useRef(null); +export const Ref: FC = React.memo( + function Ref(props) { + const { docsOptions } = useStorybookState(); + const api = useStorybookApi(); + const { + index, + id: refId, + title = refId, + isLoading: isLoadingMain, + isBrowsing, + selectedStoryId, + highlightedRef, + setHighlighted, + loginUrl, + type, + expanded = true, + indexError, + previewInitialized, + } = props; + const length = useMemo(() => (index ? Object.keys(index).length : 0), [index]); + const indicatorRef = useRef(null); - const isMain = refId === DEFAULT_REF_ID; - const isLoadingInjected = - (type === 'auto-inject' && !previewInitialized) || type === 'server-checked'; - const isLoading = isLoadingMain || isLoadingInjected || type === 'unknown'; - const isError = !!indexError; - const isEmpty = !isLoading && length === 0; - const isAuthRequired = !!loginUrl && length === 0; + const isMain = refId === DEFAULT_REF_ID; + const isLoadingInjected = + (type === 'auto-inject' && !previewInitialized) || type === 'server-checked'; + const isLoading = isLoadingMain || isLoadingInjected || type === 'unknown'; + const isError = !!indexError; + const isEmpty = !isLoading && length === 0; + const isAuthRequired = !!loginUrl && length === 0; - const state = getStateType(isLoading, isAuthRequired, isError, isEmpty); - const [isExpanded, setExpanded] = useState(expanded); + const state = getStateType(isLoading, isAuthRequired, isError, isEmpty); + const [isExpanded, setExpanded] = useState(expanded); - useEffect(() => { - if (index && selectedStoryId && index[selectedStoryId]) { - setExpanded(true); - } - }, [setExpanded, index, selectedStoryId]); + useEffect(() => { + if (index && selectedStoryId && index[selectedStoryId]) { + setExpanded(true); + } + }, [setExpanded, index, selectedStoryId]); - const handleClick = useCallback(() => setExpanded((value) => !value), [setExpanded]); + const handleClick = useCallback(() => setExpanded((value) => !value), [setExpanded]); - const setHighlightedItemId = useCallback( - (itemId: string) => setHighlighted({ itemId, refId }), - [setHighlighted] - ); + const setHighlightedItemId = useCallback( + (itemId: string) => setHighlighted({ itemId, refId }), + [setHighlighted] + ); - const onSelectStoryId = useCallback( - (storyId: string) => api && api.selectStory(storyId, undefined, { ref: !isMain && refId }), - [api, isMain, refId] - ); + const onSelectStoryId = useCallback( + (storyId: string) => api && api.selectStory(storyId, undefined, { ref: !isMain && refId }), + [api, isMain, refId] + ); - return ( - <> - {isMain || ( - - - - {title} - - - - )} - {isExpanded && ( - - {state === 'auth' && } - {state === 'error' && } - {state === 'loading' && } - {state === 'empty' && } - {state === 'ready' && ( - - )} - - )} - - ); -}); + return ( + <> + {isMain || ( + + + + {title} + + + + )} + {isExpanded && ( + + {state === 'auth' && } + {state === 'error' && } + {state === 'loading' && } + {state === 'empty' && } + {state === 'ready' && ( + + )} + + )} + + ); + } +); diff --git a/code/ui/manager/src/components/sidebar/useHighlighted.ts b/code/ui/manager/src/components/sidebar/useHighlighted.ts index c259969cfe3..f98961510ec 100644 --- a/code/ui/manager/src/components/sidebar/useHighlighted.ts +++ b/code/ui/manager/src/components/sidebar/useHighlighted.ts @@ -32,7 +32,7 @@ export const useHighlighted = ({ }: HighlightedProps): [ Highlight, Dispatch>, - MutableRefObject + MutableRefObject, ] => { const initialHighlight = fromSelection(selected); const highlightedRef = useRef(initialHighlight); diff --git a/code/ui/manager/src/globals/globals-module-info.ts b/code/ui/manager/src/globals/globals-module-info.ts index 616148e80ca..193ee13d615 100644 --- a/code/ui/manager/src/globals/globals-module-info.ts +++ b/code/ui/manager/src/globals/globals-module-info.ts @@ -21,12 +21,15 @@ import { globalPackages, globalsNameReferenceMap } from './globals'; * The `runtime.ts` file is used inside the manager's browser code runtime. */ -export const globalsModuleInfoMap = globalPackages.reduce((acc, key) => { - acc[key] = { - type: 'esm', - varName: globalsNameReferenceMap[key], - namedExports: Exports[key], - defaultExport: true, - }; - return acc; -}, {} as Required>>); +export const globalsModuleInfoMap = globalPackages.reduce( + (acc, key) => { + acc[key] = { + type: 'esm', + varName: globalsNameReferenceMap[key], + namedExports: Exports[key], + defaultExport: true, + }; + return acc; + }, + {} as Required>> +); diff --git a/code/ui/manager/src/utils/tree.ts b/code/ui/manager/src/utils/tree.ts index d650362afcf..b51fc84f630 100644 --- a/code/ui/manager/src/utils/tree.ts +++ b/code/ui/manager/src/utils/tree.ts @@ -33,18 +33,20 @@ export const getParents = memoize(1000)((id: string, dataset: Dataset): Item[] = export const getAncestorIds = memoize(1000)((data: IndexHash, id: string): string[] => getParents(id, data).map((item) => item.id) ); -export const getDescendantIds = memoize(1000)( - (data: IndexHash, id: string, skipLeafs: boolean): string[] => { - const entry = data[id]; - const children = entry.type === 'story' || entry.type === 'docs' ? [] : entry.children; - return children.reduce((acc, childId) => { - const child = data[childId]; - if (!child || (skipLeafs && (child.type === 'story' || child.type === 'docs'))) return acc; - acc.push(childId, ...getDescendantIds(data, childId, skipLeafs)); - return acc; - }, []); - } -); +export const getDescendantIds = memoize(1000)(( + data: IndexHash, + id: string, + skipLeafs: boolean +): string[] => { + const entry = data[id]; + const children = entry.type === 'story' || entry.type === 'docs' ? [] : entry.children; + return children.reduce((acc, childId) => { + const child = data[childId]; + if (!child || (skipLeafs && (child.type === 'story' || child.type === 'docs'))) return acc; + acc.push(childId, ...getDescendantIds(data, childId, skipLeafs)); + return acc; + }, []); +}); export function getPath(item: Item, ref: RefType): string[] { const parent = item.type !== 'root' && item.parent ? ref.index[item.parent] : null;