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

Core: Typesafe parameters #30601

Open
wants to merge 7 commits into
base: next
Choose a base branch
from
Open

Core: Typesafe parameters #30601

wants to merge 7 commits into from

Conversation

kasperpeulen
Copy link
Contributor

@kasperpeulen kasperpeulen commented Feb 20, 2025

Closes #

What I did

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This pull request has been released as version 0.0.0-pr-30601-sha-ec299491. Try it out in a new sandbox by running npx [email protected] sandbox or in an existing project with npx [email protected] upgrade.

More information
Published version 0.0.0-pr-30601-sha-ec299491
Triggered by @kasperpeulen
Repository storybookjs/storybook
Branch kasper/csf-parameters
Commit ec299491
Datetime Mon Feb 24 15:27:40 UTC 2025 (1740410860)
Workflow run 13501621404

To request a new release of this pull request, mention the @storybookjs/core team.

core team members can create a new canary release here or locally with gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=30601

name before after diff z %
createSize 0 B 0 B 0 B - -
generateSize 79.6 MB 79.6 MB 0 B -4.27 0%
initSize 79.6 MB 79.6 MB 0 B -4.27 0%
diffSize 97 B 97 B 0 B - 0%
buildSize 7.29 MB 7.31 MB 21.5 kB 0.25 0.3%
buildSbAddonsSize 1.9 MB 1.9 MB 156 B Infinity 0%
buildSbCommonSize 195 kB 195 kB 0 B - 0%
buildSbManagerSize 1.88 MB 1.88 MB -4.69 kB -0.82 -0.2%
buildSbPreviewSize 0 B 0 B 0 B - -
buildStaticSize 0 B 0 B 0 B - -
buildPrebuildSize 3.97 MB 3.97 MB -4.53 kB -0.75 -0.1%
buildPreviewSize 3.32 MB 3.34 MB 26 kB 0.41 0.8%
testBuildSize 0 B 0 B 0 B - -
testBuildSbAddonsSize 0 B 0 B 0 B - -
testBuildSbCommonSize 0 B 0 B 0 B - -
testBuildSbManagerSize 0 B 0 B 0 B - -
testBuildSbPreviewSize 0 B 0 B 0 B - -
testBuildStaticSize 0 B 0 B 0 B - -
testBuildPrebuildSize 0 B 0 B 0 B - -
testBuildPreviewSize 0 B 0 B 0 B - -
name before after diff z %
createTime 10.2s 7.8s -2s -424ms -0.72 -31%
generateTime 22.6s 18.6s -4s -4ms -0.78 -21.5%
initTime 5.4s 4.6s -756ms -0.25 -16.1%
buildTime 11s 8.6s -2s -470ms -0.97 -28.6%
testBuildTime 0ms 0ms 0ms - -
devPreviewResponsive 5.5s 4.9s -586ms -0.55 -11.8%
devManagerResponsive 5.3s 4.7s -634ms -0.55 -13.4%
devManagerHeaderVisible 681ms 746ms 65ms -0.21 8.7%
devManagerIndexVisible 691ms 803ms 112ms 0.13 13.9%
devStoryVisibleUncached 1.1s 1.8s 620ms -0.02 34.2%
devStoryVisible 758ms 822ms 64ms 0.03 7.8%
devAutodocsVisible 674ms 790ms 116ms 0.34 14.7%
devMDXVisible 622ms 792ms 170ms 0.93 21.5%
buildManagerHeaderVisible 1.1s 778ms -415ms -0.17 -53.3%
buildManagerIndexVisible 1.2s 829ms -447ms -0.09 -53.9%
buildStoryVisible 1.1s 758ms -416ms -0.13 -54.9%
buildAutodocsVisible 1s 749ms -327ms 0.87 -43.7%
buildMDXVisible 683ms 657ms -26ms 0.44 -4%

Greptile Summary

Enhanced type safety across Storybook addons by introducing consistent parameter typing and addon definition patterns.

  • Replaced definePreview with definePreviewAddon from storybook/internal/csf for better type inference
  • Added new *Types interfaces (e.g. A11yTypes, ActionsTypes) to wrap parameters and globals for each addon
  • Made configuration parameters optional with ? modifier for better flexibility
  • Introduced PreviewAddon interface and InferTypes utility in csf-factories.ts for improved addon type safety
  • Updated Next.js framework integrations to support the new typesafe parameter system

Copy link

nx-cloud bot commented Feb 20, 2025

View your CI Pipeline Execution ↗ for commit 238df1b.

Command Status Duration Result
nx run-many -t build --parallel=3 ✅ Succeeded 2m View ↗

☁️ Nx Cloud last updated this comment at 2025-02-24 18:57:18 UTC

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

37 file(s) reviewed, 14 comment(s)
Edit PR Review Bot Settings | Greptile

@@ -26,6 +26,7 @@ import { definePreview } from '@storybook/react-vite';

import addonA11y from '@storybook/addon-a11y';
import addonEssentials from '@storybook/addon-essentials';
import addonHighlight from '@storybook/addon-highlight';
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: addonHighlight is imported but never used in the configuration

Suggested change
import addonHighlight from '@storybook/addon-highlight';

@@ -1,7 +1,9 @@
import { definePreviewAddon } from 'storybook/internal/csf';
import { definePreview } from 'storybook/internal/preview-api';
Copy link
Contributor

Choose a reason for hiding this comment

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

style: definePreview is imported but never used - should be removed

Suggested change
import { definePreview } from 'storybook/internal/preview-api';

import type { ActionsTypes } from '@storybook/addon-actions';
import type { BackgroundTypes } from '@storybook/addon-backgrounds';
import type { DocsTypes } from '@storybook/addon-docs';
import type { HighLightTypes } from '@storybook/addon-highlight';
Copy link
Contributor

Choose a reason for hiding this comment

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

syntax: Inconsistent casing - imported as 'HighLightTypes' but defined as 'HighlightTypes' in the source file

Suggested change
import type { HighLightTypes } from '@storybook/addon-highlight';
import type { HighlightTypes } from '@storybook/addon-highlight';

Comment on lines +13 to +14
export interface HighLightTypes {
parameters: HighlightParameters;
Copy link
Contributor

Choose a reason for hiding this comment

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

syntax: inconsistent casing - 'HighLightTypes' should be 'HighlightTypes' to match the casing of HighlightParameters

Suggested change
export interface HighLightTypes {
parameters: HighlightParameters;
export interface HighlightTypes {
parameters: HighlightParameters;

@@ -1,5 +1,9 @@
import { definePreviewAddon } from 'storybook/internal/csf';
import { definePreview } from 'storybook/internal/preview-api';
Copy link
Contributor

Choose a reason for hiding this comment

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

style: definePreview import is no longer used and can be removed

Suggested change
import { definePreview } from 'storybook/internal/preview-api';

Comment on lines 41 to 50
interface Animal {
animalStuff: any;
}
interface Dog extends Types {
dogStuff: any;
}

interface Bla extends Types {
blaStuff: any;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Duplicate interface definitions for Animal - one at line 41 and another at line 54


const c = [handleAnimal, handleDog];

type A = typeof c extends Type<infer T>[] ? T: never;
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Type alias 'A' is redefined - conflicts with previous definition on line 27

return definePreviewBase({
...preview,
addons: [nextPreview, ...(preview.addons ?? [])],
}) as NextPreview;
}) as unknown as NextPreview<InferTypes<Addons>>;
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Double type assertion (as unknown as) may hide type errors. Consider refactoring to avoid this pattern.

ReactRenderer & NextJsTypes & InferTypes<Addons>
>
): NextPreview<InferTypes<Addons>> {
// @ts-expect-error hard
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Generic ts-expect-error comment needs more specific explanation of why this type error is expected and can't be fixed

return definePreviewBase({
...preview,
addons: [nextPreview, ...(preview.addons ?? [])],
}) as NextPreview;
}) as unknown as NextPreview<InferTypes<Addons>>;
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Double type assertion (as unknown as) is dangerous and could mask real type errors. Consider restructuring to avoid this

Comment on lines +33 to +45
export interface ReactPreview<T extends Types> extends Preview<ReactRenderer & T> {
meta<
TArgs extends Args,
Decorators extends DecoratorFunction<ReactRenderer, any>,
Decorators extends DecoratorFunction<ReactRenderer & T, any>,
// Try to make Exact<Partial<TArgs>, TMetaArgs> work
TMetaArgs extends Partial<TArgs>,
>(
meta: {
render?: ArgsStoryFn<ReactRenderer, TArgs>;
render?: ArgsStoryFn<ReactRenderer & T, TArgs>;
component?: ComponentType<TArgs>;
decorators?: Decorators | Decorators[];
args?: TMetaArgs;
} & Omit<ComponentAnnotations<ReactRenderer, TArgs>, 'decorators'>
} & Omit<ComponentAnnotations<ReactRenderer & T, TArgs>, 'decorators'>
Copy link
Contributor

@mrginglymus mrginglymus Feb 24, 2025

Choose a reason for hiding this comment

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

I've been playing with this locally as I'm super excited to use it. In order to make it work with my setup though I'm having more success in making the preview look like this...

interface ReactPreview extends Preview<ReactRenderer> {
    // TMetaArgs does not need to extend Partial<Args> as we may wish to overwrite properties
    meta<TArgs extends Args, Decorators extends DecoratorFunction<ReactRenderer, any>, TMetaArgs extends Args>(meta: {
        // My render function accepts the metaArgs not the Args - they often include changes to the components declared 
        // types such as changing `icon?: React.ReactNode` to `icon?: bool`, so the user can toggle an icon in the story
        // more easily.
        render?: ArgsStoryFn<ReactRenderer, TMetaArgs>;
        // As current
        component?: ComponentType<TArgs>;
        decorators?: Decorators | Decorators[];
        args?: TMetaArgs;
        // Extend `ComponentAnnotations` with `TMetaArgs | TArgs`. This allows me to declare `argTypes` that would
        // have been injected by autoDocs but aren't present in `metaArgs` (e.g. an externally controlled value that is
        // managed by the renderer`.
        //
        // Also, critically, exclude the four declared props above to ensure they are exactyl as declared
    } & Omit<ComponentAnnotations<ReactRenderer, TMetaArgs | TArgs>, 'render'| 'component' | 'args'| 'decorators'>): ReactMeta<{
        // Less sure about these return types - but as above, it's `TMetaArgs` plus anything from `TArgs` _not_ overwritten in `TMetaArgs`.
        args: Simplify<Omit<TArgs, keyof TMetaArgs> & TMetaArgs & Simplify<RemoveIndexSignature<DecoratorsArgs<ReactRenderer, Decorators>>>>;
    }, {
        args: Omit<TArgs, keyof TMetaArgs> & TMetaArgs;
    }>;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Could you perhaps write unit tests for the cases that you want to have covered here?

For example, I do have a test that allow the render args to be widened:

it('Correct args are inferred when type is widened for render function', () => {
const meta = preview.meta({
component: Button,
args: { disabled: false },
render: (args: ButtonProps & { theme: ThemeData }, { component }) => {
// component is not null as it is provided in meta
const Component = component!;
return (
<Theme theme={args.theme}>
<Component {...args} />
</Theme>
);
},
});
const Basic = meta.story({ args: { theme: 'light', label: 'good' } });
});

Copy link
Contributor

Choose a reason for hiding this comment

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

Absolutely! I'll raise a PR against this branch tomorrow.

Copy link
Contributor

Choose a reason for hiding this comment

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

@kasperpeulen here's the branch with an example story: mrginglymus@0fe2412

The first example is fixable by mucking about with ReactPreview in preview.tsx; fixing the second example requires a much deeper fix I think as it requires the StoryAnnotations to infer their args from their render function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants