Skip to content

Commit

Permalink
Merge pull request #18737 from storybookjs/fix-react-18-docs-tests
Browse files Browse the repository at this point in the history
React: Fix callback behavior in `react@18`
  • Loading branch information
tmeasday authored and shilman committed Aug 17, 2022
1 parent 126054d commit f17999b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
31 changes: 25 additions & 6 deletions app/react/src/client/preview/render.tsx
@@ -1,10 +1,13 @@
import global from 'global';

import React, {
Component as ReactComponent,
FunctionComponent,
FC,
ReactElement,
StrictMode,
Fragment,
useLayoutEffect,
useRef,
} from 'react';
import ReactDOM, { version as reactDomVersion } from 'react-dom';
import type { Root as ReactRoot } from 'react-dom/client';
Expand All @@ -31,16 +34,32 @@ export const render: ArgsStoryFn<ReactFramework> = (args, context) => {
return <Component {...args} />;
};

const WithCallback: FC<{ callback: () => void; children: ReactElement }> = ({
callback,
children,
}) => {
// See https://github.com/reactwg/react-18/discussions/5#discussioncomment-2276079
const once = useRef(false);
useLayoutEffect(() => {
if (once.current) return;
once.current = true;
callback();
}, [callback]);

return children;
};

const renderElement = async (node: ReactElement, el: Element) => {
// Create Root Element conditionally for new React 18 Root Api
const root = await getReactRoot(el);

return new Promise((resolve) => {
if (root) {
root.render(node);
setTimeout(() => {
resolve(null);
}, 0);
root.render(
<WithCallback key={Math.random()} callback={() => resolve(null)}>
{node}
</WithCallback>
);
} else {
ReactDOM.render(node, el, () => resolve(null));
}
Expand Down Expand Up @@ -126,7 +145,7 @@ export async function renderToDOM(
}: RenderContext<ReactFramework>,
domElement: HTMLElement
) {
const Story = unboundStoryFn as FunctionComponent<StoryContext<ReactFramework>>;
const Story = unboundStoryFn as FC<StoryContext<ReactFramework>>;

const content = (
<ErrorBoundary showMain={showMain} showException={showException}>
Expand Down
30 changes: 30 additions & 0 deletions code/cypress/generated/addon-docs.spec.ts
@@ -0,0 +1,30 @@
import { skipOn } from '@cypress/skip-test';

describe('addon-docs', () => {
beforeEach(() => {
cy.visitStorybook();
cy.navigateToStory('example-button', 'docs');
});

skipOn('vue3', () => {
skipOn('html', () => {
it('should provide source snippet', () => {
cy.getDocsElement()
.find('.docblock-code-toggle')
.each(($div) => {
cy.wrap($div)
.should('contain.text', 'Show code')
// use force click so cypress does not automatically scroll, making the source block visible on this step
.click({ force: true });
});

cy.getDocsElement()
.find('pre.prismjs')
.each(($div) => {
const text = $div.text();
expect(text).not.match(/^\(args\) => /);
});
});
});
});
});

0 comments on commit f17999b

Please sign in to comment.