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

Preview API: Add csf factory utilities #30388

Merged
merged 1 commit into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 9 additions & 4 deletions code/addons/test/src/vitest-plugin/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
/* eslint-disable no-underscore-dangle */
import { type RunnerTask, type TaskMeta, type TestContext } from 'vitest';

import { type Report, composeStory } from 'storybook/internal/preview-api';
import {
type Report,
composeStory,
getCsfFactoryAnnotations,
} from 'storybook/internal/preview-api';
import type { ComponentAnnotations, ComposedStoryFn } from 'storybook/internal/types';

import { server } from '@vitest/browser/context';
Expand All @@ -26,11 +30,12 @@ export const testStory = (
skipTags: string[]
) => {
return async (context: TestContext & { story: ComposedStoryFn }) => {
const annotations = getCsfFactoryAnnotations(story, meta);
const composedStory = composeStory(
'isCSFFactory' in story ? (story as any).input : story,
'isCSFFactory' in story ? (meta as any).input : meta,
annotations.story,
annotations.meta,
{ initialGlobals: (await getInitialGlobals?.()) ?? {}, tags: await getTags?.() },
Copy link
Contributor

Choose a reason for hiding this comment

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

style: optional chaining on getInitialGlobals could be moved to line 24 where the function is destructured for better error handling

'isCSFFactory' in story ? (story as any).config?.input : undefined,
annotations.preview,
exportName
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ export async function generateModernIframeScriptCode(options: Options, projectRo
const getPreviewAnnotationsFunction = `
const getProjectAnnotations = async (hmrPreviewAnnotationModules = []) => {
const preview = await import('${previewFileUrl}');
const csfFactoryPreview = Object.values(preview).find(module => {
return 'isCSFFactoryPreview' in module
});
const csfFactoryPreview = getCsfFactoryPreview(preview);

if (csfFactoryPreview) {
return csfFactoryPreview.input;
Expand Down Expand Up @@ -81,7 +79,7 @@ export async function generateModernIframeScriptCode(options: Options, projectRo

setup();

import { composeConfigs, PreviewWeb, ClientApi } from 'storybook/internal/preview-api';
import { composeConfigs, PreviewWeb, ClientApi, getCsfFactoryPreview } from 'storybook/internal/preview-api';
import { importFn } from '${SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE}';


Expand Down
8 changes: 7 additions & 1 deletion code/core/src/preview-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ export {
normalizeProjectAnnotations,
} from './store';

export { createPlaywrightTest } from './modules/store/csf/portable-stories';
/** CSF API */
export {
createPlaywrightTest,
getCsfFactoryPreview,
getCsfFactoryAnnotations,
isCsfFactory,
} from './modules/store/csf';

export type { PropDescriptor } from './store';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {

import { dedent } from 'ts-dedent';

import type { StoryStore } from '../../store';
import { type StoryStore, isCsfFactory } from '../../store';
import type { DocsContextProps } from './DocsContextProps';

export class DocsContext<TRenderer extends Renderer> implements DocsContextProps<TRenderer> {
Expand Down Expand Up @@ -163,7 +163,8 @@ export class DocsContext<TRenderer extends Renderer> implements DocsContextProps
}

const story = this.exportToStory.get(
'isCSFFactory' in moduleExportOrType ? moduleExportOrType.input : moduleExportOrType
// TODO: @kasperpeulen will fix this once csf factory types are defined
isCsfFactory(moduleExportOrType) ? (moduleExportOrType as any).input : moduleExportOrType
);

if (story) {
Expand Down
42 changes: 42 additions & 0 deletions code/core/src/preview-api/modules/store/csf/csf-factory-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/* eslint-disable @typescript-eslint/naming-convention */

/* eslint-disable no-underscore-dangle */
import type {
Args,
ComponentAnnotations,
LegacyStoryAnnotationsOrFn,
ModuleExports,
ProjectAnnotations,
Renderer,
StoryAnnotations,
} from '@storybook/types';

export function getCsfFactoryPreview(preview: ModuleExports): ProjectAnnotations<any> | null {
return Object.values(preview).find(isCsfFactory) ?? null;
}

export function isCsfFactory(target: StoryAnnotations | ProjectAnnotations<any>) {
return (
target != null &&
typeof target === 'object' &&
('isCSFFactory' in target || 'isCSFFactoryPreview' in target)
);
}

export function getCsfFactoryAnnotations<
TRenderer extends Renderer = Renderer,
TArgs extends Args = Args,
>(
story: LegacyStoryAnnotationsOrFn<TRenderer>,
meta?: ComponentAnnotations<TRenderer, TArgs>,
projectAnnotations?: ProjectAnnotations<TRenderer>
) {
const _isCsfFactory = isCsfFactory(story);

return {
// TODO: @kasperpeulen will fix this once csf factory types are defined
story: _isCsfFactory ? (story as any)?.input : story,
meta: _isCsfFactory ? (story as any)?.meta?.input : meta,
preview: _isCsfFactory ? (story as any)?.config?.input : projectAnnotations,
};
}
1 change: 1 addition & 0 deletions code/core/src/preview-api/modules/store/csf/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export * from './getValuesFromArgTypes';
export * from './composeConfigs';
export * from './stepRunners';
export * from './portable-stories';
export * from './csf-factory-utils';
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 adding a newline at the end of file to match style of other exports

19 changes: 3 additions & 16 deletions code/core/src/preview-api/modules/store/csf/portable-stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { dedent } from 'ts-dedent';
import { HooksContext } from '../../../addons';
import { ReporterAPI } from '../reporter-api';
import { composeConfigs } from './composeConfigs';
import { getCsfFactoryAnnotations } from './csf-factory-utils';
import { getValuesFromArgTypes } from './getValuesFromArgTypes';
import { normalizeComponentAnnotations } from './normalizeComponentAnnotations';
import { normalizeProjectAnnotations } from './normalizeProjectAnnotations';
Expand Down Expand Up @@ -89,21 +90,6 @@ export function setProjectAnnotations<TRenderer extends Renderer = Renderer>(

const cleanups: CleanupCallback[] = [];

export function getAnnotations<TRenderer extends Renderer = Renderer, TArgs extends Args = Args>(
story: LegacyStoryAnnotationsOrFn<TRenderer>,
meta?: ComponentAnnotations<TRenderer, TArgs>,
projectAnnotations?: ProjectAnnotations<TRenderer>
) {
const isCsfFactory =
(typeof story === 'function' || typeof story === 'object') && 'isCSFFactory' in story;

return {
storyAnnotations: isCsfFactory ? (story as any)?.input : story,
componentAnnotations: isCsfFactory ? (story as any)?.meta?.input : meta,
projectAnnotations: isCsfFactory ? (story as any)?.config?.input : projectAnnotations,
};
}

export function composeStory<TRenderer extends Renderer = Renderer, TArgs extends Args = Args>(
storyAnnotations: LegacyStoryAnnotationsOrFn<TRenderer>,
componentAnnotations: ComponentAnnotations<TRenderer, TArgs>,
Expand Down Expand Up @@ -295,7 +281,8 @@ export function composeStories<TModule extends Store_CSFExports>(

const composedStories = Object.entries(stories).reduce(
(storiesMap, [exportsName, story]: [string, any]) => {
const { storyAnnotations, componentAnnotations } = getAnnotations(story);
const { story: storyAnnotations, meta: componentAnnotations } =
getCsfFactoryAnnotations(story);
Comment on lines +284 to +285
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Destructuring could fail if getCsfFactoryAnnotations returns undefined. Consider adding a null check or default values.

if (!meta && componentAnnotations) {
meta = componentAnnotations;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export function processCSFFile<TRenderer extends Renderer>(

const firstStory: any = Object.values(namedExports)[0];
Copy link
Contributor

Choose a reason for hiding this comment

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

style: casting to any here loses type safety - consider using a more specific type or adding runtime type checks

// CSF4
// TODO: @kasperpeulen will fix this once csf factory types are defined
if (!defaultExport && 'isCSFFactory' in firstStory) {
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: check for firstStory being undefined before accessing properties to prevent runtime errors

const meta: NormalizedComponentAnnotations<TRenderer> =
normalizeComponentAnnotations<TRenderer>(firstStory.meta.input, title, importPath);
Expand Down
Loading