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

Turn on strict types in store + preview-web #18536

Merged
merged 7 commits into from
Jun 23, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
20 changes: 16 additions & 4 deletions lib/addons/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
StoryKind,
StoryName,
Args,
ComponentTitle,
} from '@storybook/csf';

import { Addon } from './index';
Expand Down Expand Up @@ -50,18 +51,29 @@ export interface StorySortObjectParameter {
includeNames?: boolean;
}

interface StoryIndexEntry {
type Path = string;
interface BaseIndexEntry {
id: StoryId;
name: StoryName;
title: string;
importPath: string;
title: ComponentTitle;
importPath: Path;
}
export type StoryIndexEntry = BaseIndexEntry & {
type: 'story';
};

export type DocsIndexEntry = BaseIndexEntry & {
storiesImports: Path[];
type: 'docs';
legacy?: boolean;
};
export type IndexEntry = StoryIndexEntry | DocsIndexEntry;

// The `any` here is the story store's `StoreItem` record. Ideally we should probably only
// pass a defined subset of that full data, but we pass it all so far :shrug:
export type StorySortComparator = Comparator<[StoryId, any, Parameters, Parameters]>;
export type StorySortParameter = StorySortComparator | StorySortObjectParameter;
export type StorySortComparatorV7 = Comparator<StoryIndexEntry>;
export type StorySortComparatorV7 = Comparator<IndexEntry>;
export type StorySortParameterV7 = StorySortComparatorV7 | StorySortObjectParameter;

export interface OptionsParameter extends Object {
Expand Down
11 changes: 6 additions & 5 deletions lib/core-client/src/preview/start.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { start } from './start';

jest.mock('@storybook/preview-web/dist/cjs/WebView');
jest.spyOn(WebView.prototype, 'prepareForDocs').mockReturnValue('docs-root');
jest.spyOn(WebView.prototype, 'prepareForStory').mockReturnValue('story-root');

jest.mock('global', () => ({
// @ts-ignore
Expand Down Expand Up @@ -156,7 +157,7 @@ describe('start', () => {
expect.objectContaining({
id: 'component-a--story-one',
}),
undefined
'story-root'
);
});

Expand Down Expand Up @@ -328,7 +329,7 @@ describe('start', () => {
}),
}),
}),
undefined
'story-root'
);
});

Expand Down Expand Up @@ -365,7 +366,7 @@ describe('start', () => {
},
}),
}),
undefined
'story-root'
);

expect((window as any).IS_STORYBOOK).toBe(true);
Expand Down Expand Up @@ -707,7 +708,7 @@ describe('start', () => {
expect.objectContaining({
id: 'component-c--story-one',
}),
undefined
'story-root'
);
});

Expand Down Expand Up @@ -1184,7 +1185,7 @@ describe('start', () => {
expect.objectContaining({
id: 'component-a--story-one',
}),
undefined
'story-root'
);
});
});
Expand Down
33 changes: 23 additions & 10 deletions lib/preview-web/src/DocsRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,17 @@ export class DocsRender<TFramework extends AnyFramework> implements Render<TFram

public disableKeyListeners = false;

public teardown: (options: { viewModeChanged?: boolean }) => Promise<void>;
public teardown?: (options: { viewModeChanged?: boolean }) => Promise<void>;

public torndown = false;

constructor(
private channel: Channel,
private store: StoryStore<TFramework>,
public entry: IndexEntry
) {
this.id = entry.id;
this.legacy = entry.type !== 'docs' || entry.legacy;
this.legacy = entry.type !== 'docs' || !!entry.legacy;
}

// The two story "renders" are equal and have both loaded the same story
Expand Down Expand Up @@ -105,6 +107,8 @@ export class DocsRender<TFramework extends AnyFramework> implements Render<TFram
};
}

if (!this.csfFiles) throw new Error('getDocsContext called before prepare');

let metaCsfFile: ModuleExports;
const exportToStoryId = new Map<ModuleExport, StoryId>();
const storyIdToCSFFile = new Map<StoryId, CSFFile<TFramework>>();
Expand All @@ -126,16 +130,18 @@ export class DocsRender<TFramework extends AnyFramework> implements Render<TFram
return {
...base,
storyIdByModuleExport: (moduleExport) => {
if (exportToStoryId.has(moduleExport)) return exportToStoryId.get(moduleExport);
const storyId = exportToStoryId.get(moduleExport);
if (storyId) return storyId;

throw new Error(`No story found with that export: ${moduleExport}`);
},
storyById,
componentStories: () => {
return Object.entries(metaCsfFile)
.map(([_, moduleExport]) => exportToStoryId.get(moduleExport))
.filter(Boolean)
.map(storyById);
return (
Object.entries(metaCsfFile)
.map(([_, moduleExport]) => exportToStoryId.get(moduleExport))
.filter(Boolean) as StoryId[]
).map(storyById);
},
setMeta(m: ModuleExports) {
metaCsfFile = m;
Expand All @@ -154,10 +160,15 @@ export class DocsRender<TFramework extends AnyFramework> implements Render<TFram
}

async render() {
if (!(this.story || this.exports) || !this.docsContext || !this.canvasElement)
if (
!(this.story || this.exports) ||
!this.docsContext ||
!this.canvasElement ||
!this.store.projectAnnotations
)
throw new Error('DocsRender not ready to render');

const { docs } = this.story?.parameters || this.store.projectAnnotations.parameters;
const { docs } = this.story?.parameters || this.store.projectAnnotations.parameters || {};

if (!docs) {
throw new Error(
Expand All @@ -170,14 +181,16 @@ export class DocsRender<TFramework extends AnyFramework> implements Render<TFram
this.docsContext,
{
...docs,
...(!this.legacy && { page: this.exports.default }),
// exports must be defined in non-legacy mode (see check at top)
...(!this.legacy && { page: this.exports!.default }),
},
this.canvasElement,
() => this.channel.emit(DOCS_RENDERED, this.id)
);
this.teardown = async ({ viewModeChanged }: { viewModeChanged?: boolean } = {}) => {
if (!viewModeChanged || !this.canvasElement) return;
renderer.unmount(this.canvasElement);
this.torndown = true;
};
}

Expand Down
16 changes: 13 additions & 3 deletions lib/preview-web/src/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class Preview<TFramework extends AnyFramework> {

importFn?: ModuleImportFn;

renderToDOM: RenderToDOM<TFramework>;
renderToDOM?: RenderToDOM<TFramework>;

storyRenders: StoryRender<TFramework>[] = [];

Expand Down Expand Up @@ -156,6 +156,8 @@ export class Preview<TFramework extends AnyFramework> {
}

emitGlobals() {
if (!this.storyStore.globals || !this.storyStore.projectAnnotations)
throw new Error(`Cannot emit before initialization`);
this.channel.emit(SET_GLOBALS, {
globals: this.storyStore.globals.get() || {},
globalTypes: this.storyStore.projectAnnotations.globalTypes || {},
Expand All @@ -171,6 +173,9 @@ export class Preview<TFramework extends AnyFramework> {

// If initialization gets as far as the story index, this function runs.
initializeWithStoryIndex(storyIndex: StoryIndex): PromiseLike<void> {
if (!this.importFn)
throw new Error(`Cannot call initializeWithStoryIndex before initialization`);

return this.storyStore.initialize({
storyIndex,
importFn: this.importFn,
Expand Down Expand Up @@ -218,7 +223,7 @@ export class Preview<TFramework extends AnyFramework> {
// Update the store with the new stories.
await this.onStoriesChanged({ storyIndex });
} catch (err) {
this.renderPreviewEntryError('Error loading story index:', err);
this.renderPreviewEntryError('Error loading story index:', err as Error);
throw err;
}
}
Expand All @@ -235,6 +240,8 @@ export class Preview<TFramework extends AnyFramework> {
}

async onUpdateGlobals({ globals }: { globals: Globals }) {
if (!this.storyStore.globals)
throw new Error(`Cannot call onUpdateGlobals before initialization`);
this.storyStore.globals.update(globals);

await Promise.all(this.storyRenders.map((r) => r.rerender()));
Expand Down Expand Up @@ -295,6 +302,9 @@ export class Preview<TFramework extends AnyFramework> {
// we will change it to go ahead and load the story, which will end up being
// "instant", although async.
renderStoryToElement(story: Story<TFramework>, element: HTMLElement) {
if (!this.renderToDOM)
throw new Error(`Cannot call renderStoryToElement before initialization`);

const render = new StoryRender<TFramework>(
this.channel,
this.storyStore,
Expand All @@ -318,7 +328,7 @@ export class Preview<TFramework extends AnyFramework> {
{ viewModeChanged }: { viewModeChanged?: boolean } = {}
) {
this.storyRenders = this.storyRenders.filter((r) => r !== render);
await render?.teardown({ viewModeChanged });
await render?.teardown?.({ viewModeChanged });
}

// API
Expand Down
6 changes: 6 additions & 0 deletions lib/preview-web/src/PreviewWeb.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import global from 'global';
import { RenderContext } from '@storybook/store';
import addons, { mockChannel as createMockChannel } from '@storybook/addons';
import { DocsRenderer } from '@storybook/addon-docs';
import { mocked } from 'ts-jest/utils';
import { expect } from '@jest/globals';

import { PreviewWeb } from './PreviewWeb';
import { WebView } from './WebView';
import {
componentOneExports,
importFn,
Expand Down Expand Up @@ -56,6 +59,9 @@ beforeEach(() => {

addons.setChannel(mockChannel as any);
addons.setServerChannel(createMockChannel());

mocked(WebView.prototype).prepareForDocs.mockReturnValue('docs-element' as any);
mocked(WebView.prototype).prepareForStory.mockReturnValue('story-element' as any);
});

describe('PreviewWeb', () => {
Expand Down
Loading