Skip to content

Commit

Permalink
fix WC source decorator to handle document fragment correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
bashmish committed May 11, 2023
1 parent 9029693 commit 7eb6f35
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
32 changes: 31 additions & 1 deletion code/renderers/web-components/src/docs/sourceDecorator.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { html } from 'lit';
import { html, render } from 'lit';
import { styleMap } from 'lit/directives/style-map.js';
import { addons, useEffect } from '@storybook/preview-api';
import { SNIPPET_RENDERED } from '@storybook/docs-tools';
Expand Down Expand Up @@ -85,4 +85,34 @@ describe('sourceDecorator', () => {
source: '<div>args story</div>',
});
});

it('should handle document fragment without removing its child nodes', async () => {
const storyFn = () =>
html`my
<div>args story</div>`;
const decoratedStoryFn = () => {
const fragment = document.createDocumentFragment();
render(storyFn(), fragment);
return fragment;
};
const context = makeContext('args', { __isArgsStory: true }, {});
const story = sourceDecorator(decoratedStoryFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'lit-test--args',
args: {},
source: `my
<div>args story</div>`,
});
expect(story).toMatchInlineSnapshot(`
<DocumentFragment>
<!---->
my
<div>
args story
</div>
</DocumentFragment>
`);
});
});
6 changes: 5 additions & 1 deletion code/renderers/web-components/src/docs/sourceDecorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ export function sourceDecorator(
});
if (!skipSourceRender(context)) {
const container = window.document.createElement('div');
render(renderedForSource, container);
if (renderedForSource instanceof DocumentFragment) {
render(renderedForSource.cloneNode(true), container);
} else {
render(renderedForSource, container);
}
source = container.innerHTML.replace(LIT_EXPRESSION_COMMENTS, '');
}

Expand Down
7 changes: 6 additions & 1 deletion code/renderers/web-components/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { StoryContext as StoryContextBase, WebRenderer } from '@storybook/types';
import type { TemplateResult, SVGTemplateResult } from 'lit';

export type StoryFnHtmlReturnType = string | Node | TemplateResult | SVGTemplateResult;
export type StoryFnHtmlReturnType =
| string
| Node
| DocumentFragment
| TemplateResult
| SVGTemplateResult;

export type StoryContext = StoryContextBase<WebComponentsRenderer>;

Expand Down

0 comments on commit 7eb6f35

Please sign in to comment.