Skip to content

Commit

Permalink
Merge branch 'next' into update-story-globals-docs
Browse files Browse the repository at this point in the history
* next: (27 commits)
  apply fix for #28883
  fixes
  apply linting to scripts
  update snapshots
  cleanup
  remove duplicate comment
  more fixes
  jsdoc linting fixes
  misc fixes
  remove invalid syntax
  remove duplicate comment
  remove duplicate comment
  remove duplicate comment
  remove duplicate comment
  remove duplicate comment
  move comment
  move comment
  remove redundant comment
  fix linting of jsdoc comments example blocks
  fix snapshots
  ...
  • Loading branch information
kylegach committed Aug 15, 2024
2 parents b96bce0 + 010e68f commit 0e7489b
Show file tree
Hide file tree
Showing 575 changed files with 5,786 additions and 4,226 deletions.
26 changes: 16 additions & 10 deletions code/.storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {

import { DocsContext } from '@storybook/blocks';
import { global } from '@storybook/global';
import type { Decorator, ReactRenderer } from '@storybook/react';
import type { Decorator, Loader, ReactRenderer } from '@storybook/react';

import { MINIMAL_VIEWPORTS } from '@storybook/addon-viewport';

Expand Down Expand Up @@ -95,7 +95,6 @@ const StackContainer = ({ children, layout }) => (
height: '100%',
display: 'flex',
flexDirection: 'column',
// margin: layout === 'fullscreen' ? 0 : '-1rem',
}}
>
<style dangerouslySetInnerHTML={{ __html: 'html, body, #storybook-root { height: 100%; }' }} />
Expand Down Expand Up @@ -124,15 +123,21 @@ const preview = (window as any).__STORYBOOK_PREVIEW__ as PreviewWeb<ReactRendere
const channel = (window as any).__STORYBOOK_ADDONS_CHANNEL__ as Channel;
export const loaders = [
/**
* This loader adds a DocsContext to the story, which is required for the most Blocks to work.
* A story will specify which stories they need in the index with:
* This loader adds a DocsContext to the story, which is required for the most Blocks to work. A
* story will specify which stories they need in the index with:
*
* ```ts
* parameters: {
* relativeCsfPaths: ['../stories/MyStory.stories.tsx'], // relative to the story
* relativeCsfPaths: ['../stories/MyStory.stories.tsx'], // relative to the story
* }
* ```
*
* The DocsContext will then be added via the decorator below.
*/
async ({ parameters: { relativeCsfPaths, attached = true } }) => {
if (!relativeCsfPaths) return {};
if (!relativeCsfPaths) {
return {};
}
const csfFiles = await Promise.all(
(relativeCsfPaths as string[]).map(async (blocksRelativePath) => {
const projectRelativePath = `./lib/blocks/src/${blocksRelativePath.replace(
Expand Down Expand Up @@ -185,7 +190,8 @@ export const decorators = [
<Story />
),
/**
* This decorator renders the stories side-by-side, stacked or default based on the theme switcher in the toolbar
* This decorator renders the stories side-by-side, stacked or default based on the theme switcher
* in the toolbar
*/
(StoryFn, { globals, playFunction, args, storyGlobals, parameters }) => {
let theme = globals.sb_theme;
Expand Down Expand Up @@ -267,9 +273,9 @@ export const decorators = [
}
},
/**
* This decorator shows the current state of the arg named in the
* parameters.withRawArg property, by updating the arg in the onChange function
* this also means that the arg will sync with the control panel
* This decorator shows the current state of the arg named in the parameters.withRawArg property,
* by updating the arg in the onChange function this also means that the arg will sync with the
* control panel
*
* If parameters.withRawArg is not set, this decorator will do nothing
*/
Expand Down
5 changes: 1 addition & 4 deletions code/addons/a11y/src/a11yRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ let activeStoryId: string | undefined;

const defaultParameters = { config: {}, options: {} };

/**
* Handle A11yContext events.
* Because the event are sent without manual check, we split calls
*/
/** Handle A11yContext events. Because the event are sent without manual check, we split calls */
const handleRequest = async (storyId: string, input: A11yParameters | null) => {
if (!input?.manual) {
await run(storyId, input ?? defaultParameters);
Expand Down
4 changes: 3 additions & 1 deletion code/addons/a11y/src/components/A11yContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ export const A11yContextProvider: React.FC<React.PropsWithChildren<A11yContextPr
}
}, [active, handleClearHighlights, emit, storyEntry]);

if (!active) return null;
if (!active) {
return null;
}

return (
<A11yContext.Provider
Expand Down
8 changes: 3 additions & 5 deletions code/addons/actions/src/addArgsHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const isInInitialArgs = (name: string, initialArgs: Args) =>
typeof initialArgs[name] === 'undefined' && !(name in initialArgs);

/**
* Automatically add action args for argTypes whose name
* matches a regex, such as `^on.*` for react-style `onClick` etc.
* Automatically add action args for argTypes whose name matches a regex, such as `^on.*` for
* react-style `onClick` etc.
*/

export const inferActionsFromArgTypesRegex: ArgsEnhancer<Renderer> = (context) => {
Expand All @@ -39,9 +39,7 @@ export const inferActionsFromArgTypesRegex: ArgsEnhancer<Renderer> = (context) =
}, {} as Args);
};

/**
* Add action args for list of strings.
*/
/** Add action args for list of strings. */
export const addActionsFromArgTypes: ArgsEnhancer<Renderer> = (context) => {
const {
initialArgs,
Expand Down
6 changes: 5 additions & 1 deletion code/addons/actions/src/components/ActionLogger/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ export const ActionLogger = ({ actions, onClear }: ActionLoggerProps) => {

useEffect(() => {
// Scroll to bottom, when the action panel was already scrolled down
if (wasAtBottom) wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight;

// Scroll to bottom, when the action panel was already scrolled down
if (wasAtBottom) {
wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight;
}
}, [wasAtBottom, actions.length]);

return (
Expand Down
10 changes: 8 additions & 2 deletions code/addons/actions/src/loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ const logActionsWhenMockCalled: LoaderFunction = (context) => {
const {
parameters: { actions },
} = context;
if (actions?.disable) return;

if (actions?.disable) {
return;
}

if (
!subscribed &&
Expand All @@ -22,7 +25,10 @@ const logActionsWhenMockCalled: LoaderFunction = (context) => {
const onMockCall = global.__STORYBOOK_TEST_ON_MOCK_CALL__ as typeof onMockCallType;
onMockCall((mock, args) => {
const name = mock.getMockName();
if (name === 'spy') return;

if (name === 'spy') {
return;
}

// TODO: Make this a configurable API in 8.2
if (
Expand Down
5 changes: 4 additions & 1 deletion code/addons/actions/src/runtime/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import { config } from './configureActions';
type SyntheticEvent = any; // import('react').SyntheticEvent;
const findProto = (obj: unknown, callback: (proto: any) => boolean): Function | null => {
const proto = Object.getPrototypeOf(obj);
if (!proto || callback(proto)) return proto;

if (!proto || callback(proto)) {
return proto;
}
return findProto(proto, callback);
};
const isReactSyntheticEvent = (e: unknown): e is SyntheticEvent =>
Expand Down
11 changes: 8 additions & 3 deletions code/addons/controls/src/ControlsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,21 @@ export const ControlsPanel = ({ saveStory, createStory }: ControlsPanelProps) =>
// If the story is prepared, then show the args table
// and reset the loading states
useEffect(() => {
if (previewInitialized) setIsLoading(false);
if (previewInitialized) {
setIsLoading(false);
}
}, [previewInitialized]);

const hasControls = Object.values(rows).some((arg) => arg?.control);

const withPresetColors = Object.entries(rows).reduce((acc, [key, arg]) => {
const control = arg?.control;
if (typeof control !== 'object' || control?.type !== 'color' || control?.presetColors)

if (typeof control !== 'object' || control?.type !== 'color' || control?.presetColors) {
acc[key] = arg;
else acc[key] = { ...arg, control: { ...control, presetColors } };
} else {
acc[key] = { ...arg, control: { ...control, presetColors } };
}
return acc;
}, {} as ArgTypes);

Expand Down
9 changes: 7 additions & 2 deletions code/addons/controls/src/SaveStory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ export const SaveStory = ({ saveStory, createStory, resetArgs }: SaveStoryProps)
const [errorMessage, setErrorMessage] = React.useState(null);

const onSaveStory = async () => {
if (saving) return;
if (saving) {
return;
}
setSaving(true);
await saveStory().catch(() => {});
setSaving(false);
Expand All @@ -125,7 +127,10 @@ export const SaveStory = ({ saveStory, createStory, resetArgs }: SaveStoryProps)
};
const onSubmitForm = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (saving) return;

if (saving) {
return;
}
try {
setErrorMessage(null);
setSaving(true);
Expand Down
27 changes: 21 additions & 6 deletions code/addons/controls/src/manager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ function Title() {

const stringifyArgs = (args: Record<string, any>) =>
JSON.stringify(args, (_, value) => {
if (typeof value === 'function') return '__sb_empty_function_arg__';
if (typeof value === 'function') {
return '__sb_empty_function_arg__';
}
return value;
});

Expand All @@ -50,7 +52,10 @@ addons.register(ADDON_ID, (api) => {

const saveStory = async () => {
const data = api.getCurrentStoryData();
if (data.type !== 'story') throw new Error('Not a story');

if (data.type !== 'story') {
throw new Error('Not a story');
}

try {
const response = await experimental_requestResponse<
Expand All @@ -60,7 +65,9 @@ addons.register(ADDON_ID, (api) => {
// Only send updated args
args: stringifyArgs(
Object.entries(data.args || {}).reduce<Args>((acc, [key, value]) => {
if (!deepEqual(value, data.initialArgs?.[key])) acc[key] = value;
if (!deepEqual(value, data.initialArgs?.[key])) {
acc[key] = value;
}
return acc;
}, {})
),
Expand Down Expand Up @@ -98,7 +105,10 @@ addons.register(ADDON_ID, (api) => {

const createStory = async (name: string) => {
const data = api.getCurrentStoryData();
if (data.type !== 'story') throw new Error('Not a story');

if (data.type !== 'story') {
throw new Error('Not a story');
}

const response = await experimental_requestResponse<
SaveStoryRequestPayload,
Expand Down Expand Up @@ -146,9 +156,14 @@ addons.register(ADDON_ID, (api) => {
});

channel.on(SAVE_STORY_RESPONSE, (data: ResponseData<SaveStoryResponsePayload>) => {
if (!data.success) return;
if (!data.success) {
return;
}
const story = api.getCurrentStoryData();
if (story.type !== 'story') return;

if (story.type !== 'story') {
return;
}

api.resetStoryArgs(story);
if (data.payload.newStoryId) {
Expand Down
4 changes: 3 additions & 1 deletion code/addons/docs/src/plugins/mdx-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ export async function mdxPlugin(options: Options): Promise<Plugin> {
name: 'storybook:mdx-plugin',
enforce: 'pre',
async transform(src, id) {
if (!filter(id)) return undefined;
if (!filter(id)) {
return undefined;
}

const mdxLoaderOptions: CompileOptions = await presets.apply('mdxLoaderOptions', {
...mdxPluginOptions,
Expand Down
33 changes: 19 additions & 14 deletions code/addons/docs/src/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import rehypeSlug from 'rehype-slug';
import type { CompileOptions } from './compiler';

/**
* Get the resolvedReact preset, which points either to
* the user's react dependencies or the react dependencies shipped with addon-docs
* if the user has not installed react explicitly.
* Get the resolvedReact preset, which points either to the user's react dependencies or the react
* dependencies shipped with addon-docs if the user has not installed react explicitly.
*/
const getResolvedReact = async (options: Options) => {
const resolvedReact = (await options.presets.apply('resolvedReact', {})) as any;
Expand Down Expand Up @@ -66,10 +65,13 @@ async function webpack(

let alias;

/** Add aliases for `@storybook/addon-docs` & `@storybook/blocks`
* These must be singletons to avoid multiple instances of react & emotion being loaded, both would cause the components to fail to render.
/**
* Add aliases for `@storybook/addon-docs` & `@storybook/blocks` These must be singletons to avoid
* multiple instances of react & emotion being loaded, both would cause the components to fail to
* render.
*
* In the future the `@storybook/theming` and `@storybook/components` can be removed, as they should be singletons in the future due to the peerDependency on `storybook` package.
* In the future the `@storybook/theming` and `@storybook/components` can be removed, as they
* should be singletons in the future due to the peerDependency on `storybook` package.
*/
const cliPath = dirname(require.resolve('storybook/package.json'));
const themingPath = join(cliPath, 'core', 'theming', 'index.js');
Expand Down Expand Up @@ -193,10 +195,14 @@ export const viteFinal = async (config: any, options: Options) => {
...(isAbsolute(reactDom) && { 'react-dom/server': `${reactDom}/server.browser.js` }),
'react-dom': reactDom,
'@mdx-js/react': mdx,
/** Add aliases for `@storybook/addon-docs` & `@storybook/blocks`
* These must be singletons to avoid multiple instances of react & emotion being loaded, both would cause the components to fail to render.
/**
* Add aliases for `@storybook/addon-docs` & `@storybook/blocks` These must be singletons
* to avoid multiple instances of react & emotion being loaded, both would cause the
* components to fail to render.
*
* In the future the `@storybook/theming` and `@storybook/components` can be removed, as they should be singletons in the future due to the peerDependency on `storybook` package.
* In the future the `@storybook/theming` and `@storybook/components` can be removed, as
* they should be singletons in the future due to the peerDependency on `storybook`
* package.
*/
'@storybook/theming/create': themingCreatePath,
'@storybook/theming': themingPath,
Expand Down Expand Up @@ -224,11 +230,10 @@ const webpackX = webpack as any;
const docsX = docs as any;

/**
* If the user has not installed react explicitly in their project,
* the resolvedReact preset will not be set.
* We then set it here in addon-docs to use addon-docs's react version that always exists.
* This is just a fallback that never overrides the existing preset,
* but ensures that there is always a resolved react.
* If the user has not installed react explicitly in their project, the resolvedReact preset will
* not be set. We then set it here in addon-docs to use addon-docs's react version that always
* exists. This is just a fallback that never overrides the existing preset, but ensures that there
* is always a resolved react.
*/
export const resolvedReact = async (existing: any) => ({
react: existing?.react ?? dirname(require.resolve('react/package.json')),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ import * as ReactDomServer from 'react-dom/server';
import { expect, within } from '@storybook/test';

/**
* This component is used to display the resolved version of React and its related packages.
* As long as `@storybook/addon-docs` is installed, `react` and `react-dom` should be available to import from and should resolve to the same version.
* This component is used to display the resolved version of React and its related packages. As long
* as `@storybook/addon-docs` is installed, `react` and `react-dom` should be available to import
* from and should resolve to the same version.
*
* The autodocs here ensures that it also works in the generated documentation.
*
* - See the [MDX docs](/docs/addons-docs-docs2-resolvedreact--mdx) for how it resolves in MDX.
* - See the [Story](/story/addons-docs-docs2-resolvedreact--story) for how it resolves in the actual story.
* - See the [Story](/story/addons-docs-docs2-resolvedreact--story) for how it resolves in the actual
* story.
*
* **Note: There appears to be a bug in the _production_ build of `react-dom`, where it reports version `18.2.0-next-9e3b772b8-20220608` while in fact version `18.2.0` is installed.**
* **Note: There appears to be a bug in the _production_ build of `react-dom`, where it reports
* version `18.2.0-next-9e3b772b8-20220608` while in fact version `18.2.0` is installed.**
*/
export default {
title: 'Docs2/ResolvedReact',
Expand Down
12 changes: 3 additions & 9 deletions code/addons/docs/template/stories/docspage/basic.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,18 @@ export default {
parameters: { chromatic: { disable: true } },
};

/**
* A basic button
*/
/** A basic button */
export const Basic = {
args: { label: 'Basic' },
};

/**
* Won't show up in DocsPage
*/
/** Won't show up in DocsPage */
export const Disabled = {
args: { label: 'Disabled in DocsPage' },
parameters: { docs: { disable: true } },
};

/**
* Another button, just to show multiple stories
*/
/** Another button, just to show multiple stories */
export const Another = {
args: { label: 'Another' },
parameters: {
Expand Down
Loading

0 comments on commit 0e7489b

Please sign in to comment.