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

Build: Migrate @storybook/manager-api to strict TS #24069

Merged
merged 6 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
22 changes: 11 additions & 11 deletions code/lib/manager-api/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export { default as merge } from './lib/merge';
export type { Options as StoreOptions, Listener as ChannelListener };
export { ActiveTabs };

export const ManagerContext = createContext({ api: undefined, state: getInitialState({}) });
export const ManagerContext = createContext({ api: undefined!, state: getInitialState({}!) });

export type State = layout.SubState &
stories.SubState &
Expand Down Expand Up @@ -167,7 +167,7 @@ class ManagerProvider extends Component<ManagerProviderProps, State> {

const store = new Store({
getState: () => this.state,
setState: (stateChange: Partial<State>, callback) => this.setState(stateChange, callback),
setState: (stateChange: Partial<State>, callback) => this.setState(stateChange, callback)!,
});

const routeData = { location, path, viewMode, singleStory, storyId, refId };
Expand Down Expand Up @@ -200,7 +200,7 @@ class ManagerProvider extends Component<ManagerProviderProps, State> {
);

// Create our initial state by combining the initial state of all modules, then overlaying any saved state
const state = getInitialState(this.state, ...this.modules.map((m) => m.state));
const state = getInitialState(this.state, ...this.modules.map((m) => m.state!));

// Get our API by combining the APIs exported by each module
const api: API = Object.assign(this.api, { navigate }, ...this.modules.map((m) => m.api));
Expand All @@ -217,10 +217,10 @@ class ManagerProvider extends Component<ManagerProviderProps, State> {
path: props.path,
refId: props.refId,
viewMode: props.viewMode,
storyId: props.storyId,
storyId: props.storyId!,
};
}
return null;
return null!;
}

shouldComponentUpdate(nextProps: ManagerProviderProps, nextState: State): boolean {
Expand All @@ -239,7 +239,7 @@ class ManagerProvider extends Component<ManagerProviderProps, State> {
initModules = () => {
// Now every module has had a chance to set its API, call init on each module which gives it
// a chance to do things that call other modules' APIs.
this.modules.forEach((module) => {
this.modules.forEach((module: any) => {
if ('init' in module) {
module.init();
}
Expand Down Expand Up @@ -299,11 +299,11 @@ function ManagerConsumer<P = Combo>({
const data = filterer.current(c);

const l = useMemo(() => {
return [...Object.entries(data).reduce((acc, keyval) => acc.concat(keyval), [])];
return [...Object.entries(data!).reduce((acc, keyval: any) => acc.concat(keyval), [])];
}, [c.state]);

return useMemo(() => {
const Child = renderer.current as FC<P>;
const Child: any = renderer.current as FC<P>;

return <Child {...data} />;
}, l);
Expand Down Expand Up @@ -375,14 +375,14 @@ export const useChannel = (eventMap: API_EventMap, deps: any[] = []) => {

export function useStoryPrepared(storyId?: StoryId) {
const api = useStorybookApi();
return api.isPrepared(storyId);
return api.isPrepared(storyId!);
}

export function useParameter<S>(parameterKey: string, defaultValue?: S) {
const api = useStorybookApi();

const result = api.getCurrentParameter<S>(parameterKey);
return orDefault<S>(result, defaultValue);
return orDefault<S>(result, defaultValue!);
}

// cache for taking care of HMR
Expand Down Expand Up @@ -478,7 +478,7 @@ export function useArgs(): [Args, (newArgs: Args) => void, (argNames?: string[])
[data, resetStoryArgs]
);

return [args, updateArgs, resetArgs];
return [args!, updateArgs, resetArgs];
}

export function useGlobals(): [Args, (newGlobals: Args) => void] {
Expand Down
7 changes: 3 additions & 4 deletions code/lib/manager-api/src/lib/addons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class AddonStore {
this.setChannel(mockChannel());
}

return this.channel;
return this.channel!;
};

/**
Expand Down Expand Up @@ -105,11 +105,10 @@ export class AddonStore {
| Addon_TypesEnum.experimental_PAGE
| Addon_TypesEnum.experimental_SIDEBAR_BOTTOM
| Addon_TypesEnum.experimental_SIDEBAR_TOP
>(type: T): Addon_Collection<Addon_TypesMapping[T]> {
>(type: T): Addon_Collection<Addon_TypesMapping[T]> | any {
if (!this.elements[type]) {
this.elements[type] = {};
}
// @ts-expect-error (Kaspar told me to do this)
return this.elements[type];
}

Expand Down Expand Up @@ -185,7 +184,7 @@ export class AddonStore {
};

loadAddons = (api: any) => {
Object.values(this.loaders).forEach((value) => value(api));
Object.values(this.loaders).forEach((value: any) => value(api));
};
}

Expand Down
4 changes: 2 additions & 2 deletions code/lib/manager-api/src/lib/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ interface Meta {

export const getEventMetadata = (context: Meta, fullAPI: API) => {
const { source, refId, type } = context;
const [sourceType, sourceLocation] = getSourceType(source, refId);
const [sourceType, sourceLocation] = getSourceType(source!, refId);

const ref =
refId && fullAPI.getRefs()[refId] ? fullAPI.getRefs()[refId] : fullAPI.findRef(sourceLocation);
refId && fullAPI.getRefs()[refId] ? fullAPI.getRefs()[refId] : fullAPI.findRef(sourceLocation!);

const meta = {
source,
Expand Down
2 changes: 1 addition & 1 deletion code/lib/manager-api/src/lib/shortcut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const eventMatchesShortcut = (
e: KeyboardEventLike,
shortcut: API_KeyCollection
): boolean => {
return shortcutMatchesShortcut(eventToShortcut(e), shortcut);
return shortcutMatchesShortcut(eventToShortcut(e)!, shortcut);
};

export const keyToSymbol = (key: string): string => {
Expand Down
27 changes: 14 additions & 13 deletions code/lib/manager-api/src/lib/stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
API_HashEntry,
SetStoriesPayload,
StoryIndexV2,
Renderer,
} from '@storybook/types';
// eslint-disable-next-line import/no-cycle
import { type API, combineParameters, type State } from '../index';
Expand Down Expand Up @@ -71,7 +72,7 @@ const transformSetStoriesStoryDataToPreparedStoryIndex = (
...base,
};
} else {
const { argTypes, args, initialArgs } = story;
const { argTypes, args, initialArgs }: any = story;
acc[id] = {
type: 'story',
...base,
Expand Down Expand Up @@ -109,7 +110,7 @@ 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) => {
entries: Object.values(index.stories).reduce((acc, entry: any) => {
let type: IndexEntry['type'] = 'story';
if (
entry.parameters?.docsOnly ||
Expand Down Expand Up @@ -143,7 +144,7 @@ type ToStoriesHashOptions = {
export const transformStoryIndexToStoriesHash = (
input: API_PreparedStoryIndex | StoryIndexV2 | StoryIndexV3,
{ provider, docsOptions, filters, status }: ToStoriesHashOptions
): API_IndexHash => {
): API_IndexHash | any => {
if (!input.v) {
throw new Error('Composition: Missing stories.json version');
}
Expand All @@ -153,10 +154,10 @@ export const transformStoryIndexToStoriesHash = (
index = index.v === 3 ? transformStoryIndexV3toV4(index as any) : index;
index = index as API_PreparedStoryIndex;

const entryValues = Object.values(index.entries).filter((entry) => {
const entryValues = Object.values(index.entries).filter((entry: any) => {
let result = true;

Object.values(filters).forEach((filter) => {
Object.values(filters).forEach((filter: any) => {
if (result === false) {
return;
}
Expand All @@ -167,11 +168,11 @@ export const transformStoryIndexToStoriesHash = (
});

const { sidebar = {} } = provider.getConfig();
const { showRoots, collapsedRoots = [], renderLabel } = sidebar;
const { showRoots, collapsedRoots = [], renderLabel }: any = sidebar;

const setShowRoots = typeof showRoots !== 'undefined';

const storiesHashOutOfOrder = entryValues.reduce((acc, item) => {
const storiesHashOutOfOrder = entryValues.reduce((acc: any, item: any) => {
if (docsOptions.docsMode && item.type !== 'docs') {
return acc;
}
Expand All @@ -185,7 +186,7 @@ export const transformStoryIndexToStoriesHash = (
// Now create a "path" or sub id for each name
const paths = names.reduce((list, name, idx) => {
const parent = idx > 0 && list[idx - 1];
const id = sanitize(parent ? `${parent}-${name}` : name);
const id = sanitize(parent ? `${parent}-${name}` : name!);

if (parent === id) {
throw new Error(
Expand All @@ -201,7 +202,7 @@ export const transformStoryIndexToStoriesHash = (
}, [] as string[]);

// Now, let's add an entry to the hash for each path/name pair
paths.forEach((id, idx) => {
paths.forEach((id: any, idx: any) => {
// The child is the next path, OR the story/docs entry itself
const childId = paths[idx + 1] || item.id;

Expand Down Expand Up @@ -284,7 +285,7 @@ export const transformStoryIndexToStoriesHash = (
}, {} as API_IndexHash);

// This function adds a "root" or "orphan" and all of its descendents to the hash.
function addItem(acc: API_IndexHash, item: API_HashEntry) {
function addItem(acc: API_IndexHash | any, item: API_HashEntry | any) {
// If we were already inserted as part of a group, that's great.
if (acc[item.id]) {
return acc;
Expand All @@ -293,18 +294,18 @@ export const transformStoryIndexToStoriesHash = (
acc[item.id] = item;
// Ensure we add the children depth-first *before* inserting any other entries
if (item.type === 'root' || item.type === 'group' || item.type === 'component') {
item.children.forEach((childId) => addItem(acc, storiesHashOutOfOrder[childId]));
item.children.forEach((childId: any) => addItem(acc, storiesHashOutOfOrder[childId]));
}
return acc;
}

// We'll do two passes over the data, adding all the orphans, then all the roots
const orphanHash = Object.values(storiesHashOutOfOrder)
.filter((i) => i.type !== 'root' && !i.parent)
.filter((i: any) => i.type !== 'root' && !i.parent)
.reduce(addItem, {});

return Object.values(storiesHashOutOfOrder)
.filter((i) => i.type === 'root')
.filter((i: any) => i.type === 'root')
.reduce(addItem, orphanHash);
};

Expand Down
8 changes: 4 additions & 4 deletions code/lib/manager-api/src/modules/addons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export interface SubAPI {
export function ensurePanel(panels: API_Panels, selectedPanel?: string, currentPanel?: string) {
const keys = Object.keys(panels);

if (keys.indexOf(selectedPanel) >= 0) {
if (keys.indexOf(selectedPanel!) >= 0) {
return selectedPanel;
}

Expand All @@ -95,7 +95,7 @@ export function ensurePanel(panels: API_Panels, selectedPanel?: string, currentP
return currentPanel;
}

export const init: ModuleFn<SubAPI, SubState> = ({ provider, store, fullAPI }) => {
export const init: ModuleFn<SubAPI, SubState> = ({ provider, store, fullAPI }): any => {
const api: SubAPI = {
getElements: (type) => provider.getElements(type),
getPanels: () => api.getElements(Addon_TypesEnum.PANEL),
Expand All @@ -112,7 +112,7 @@ export const init: ModuleFn<SubAPI, SubState> = ({ provider, store, fullAPI }) =

const filteredPanels: Addon_Collection<Addon_BaseType> = {};
Object.entries(allPanels).forEach(([id, panel]) => {
const { paramKey } = panel;
const { paramKey }: any = panel;
if (paramKey && parameters && parameters[paramKey] && parameters[paramKey].disable) {
return;
}
Expand All @@ -121,7 +121,7 @@ export const init: ModuleFn<SubAPI, SubState> = ({ provider, store, fullAPI }) =

return filteredPanels;
},
getSelectedPanel: () => {
getSelectedPanel: (): any => {
const { selectedPanel } = store.getState();
return ensurePanel(api.getElements(Addon_TypesEnum.PANEL), selectedPanel, selectedPanel);
},
Expand Down
8 changes: 4 additions & 4 deletions code/lib/manager-api/src/modules/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export const init: ModuleFn<SubAPI, SubState> = ({ store, fullAPI, provider }) =

provider.channel.on(
GLOBALS_UPDATED,
function handleGlobalsUpdated({ globals }: { globals: Globals }) {
const { ref } = getEventMetadata(this, fullAPI);
function handleGlobalsUpdated(this: any, { globals }: { globals: Globals }) {
const { ref } = getEventMetadata(this, fullAPI)!;

if (!ref) {
updateGlobals(globals);
Expand All @@ -80,8 +80,8 @@ export const init: ModuleFn<SubAPI, SubState> = ({ store, fullAPI, provider }) =
// Emitted by the preview on initialization
provider.channel.on(
SET_GLOBALS,
function handleSetStories({ globals, globalTypes }: SetGlobalsPayload) {
const { ref } = getEventMetadata(this, fullAPI);
function handleSetStories(this: any, { globals, globalTypes }: SetGlobalsPayload) {
const { ref } = getEventMetadata(this, fullAPI)!;
const currentGlobals = store.getState()?.globals;

if (!ref) {
Expand Down
20 changes: 10 additions & 10 deletions code/lib/manager-api/src/modules/refs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,13 @@ export const getSourceType = (source: string, refId?: string) => {
return [null, null];
};

export const defaultStoryMapper: API_StoryMapper = (b, a) => {
export const defaultStoryMapper: API_StoryMapper = (b: any, a: any) => {
return { ...a, kind: a.kind.replace('|', '/') };
};

const addRefIds = (input: API_IndexHash, ref: API_ComposedRef): API_IndexHash => {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: { ...item, refId: ref.id } };
return { ...acc, [id]: { ...item!, refId: ref.id } };
}, {} as API_IndexHash);
};

Expand All @@ -114,7 +114,7 @@ async function handleRequest(
}

return json as API_SetRefData;
} catch (err) {
} catch (err: any) {
return { indexError: err };
}
}
Expand Down Expand Up @@ -159,10 +159,10 @@ export const init: ModuleFn<SubAPI, SubState> = (
{ runCheck = true } = {}
) => {
const api: SubAPI = {
findRef: (source) => {
findRef: (source): any => {
const refs = api.getRefs();

return Object.values(refs).find(({ url }) => url.match(source));
return Object.values(refs).find(({ url }: any) => url.match(source));
},
changeRefVersion: (id, url) => {
const { versions, title } = api.getRefs()[id];
Expand Down Expand Up @@ -199,7 +199,7 @@ export const init: ModuleFn<SubAPI, SubState> = (
const loadedData: API_SetRefData = {};
const query = version ? `?version=${version}` : '';
const credentials = isPublic ? 'omit' : 'include';
const urlParseResult = parseUrl(url);
const urlParseResult = parseUrl(url!);

const headers: HeadersInit = {
Accept: 'application/json',
Expand Down Expand Up @@ -257,7 +257,7 @@ export const init: ModuleFn<SubAPI, SubState> = (
const versions =
ref.versions && Object.keys(ref.versions).length ? ref.versions : loadedData.versions;

await api.setRef(id, {
await api.setRef(id!, {
id,
url: urlParseResult.url,
...loadedData,
Expand Down Expand Up @@ -293,9 +293,9 @@ export const init: ModuleFn<SubAPI, SubState> = (
status: {},
});
}
if (index) index = addRefIds(index, ref);
if (index!) index = addRefIds(index, ref);

api.updateRef(id, { index, ...rest });
api.updateRef(id, { index: undefined, ...rest });
},

updateRef: (id, data) => {
Expand All @@ -322,7 +322,7 @@ export const init: ModuleFn<SubAPI, SubState> = (

if (runCheck) {
Object.entries(refs).forEach(([id, ref]) => {
api.checkRef({ ...ref, stories: {} } as API_SetRefData);
api.checkRef({ ...ref!, stories: {} } as API_SetRefData);
});
}

Expand Down
2 changes: 1 addition & 1 deletion code/lib/manager-api/src/modules/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface SubState {
settings: API_Settings;
}

export const init: ModuleFn<SubAPI, SubState> = ({ store, navigate, fullAPI }) => {
export const init: ModuleFn<SubAPI, SubState> = ({ store, navigate, fullAPI }): any => {
const isSettingsScreenActive = () => {
const { path } = fullAPI.getUrlState();
return !!(path || '').match(/^\/settings/);
Expand Down
Loading