Skip to content

Commit

Permalink
Allow a Story to access its context
Browse files Browse the repository at this point in the history
  • Loading branch information
j3rem1e committed Apr 6, 2022
1 parent f72b8f2 commit be57bc3
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/components/Story.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
});
$: render = context.render && !context.templateName && context.storyName == name;
</script>

{#if render}
<slot args={context.args} {...context.args}/>
<slot {...context.args} context={context.storyContext} args={context.args}/>
{/if}
2 changes: 1 addition & 1 deletion src/components/Template.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
</script>

{#if render}
<slot args={context.args} {...context.args}/>
<slot {...context.args} context={context.storyContext} args={context.args}/>
{/if}
3 changes: 2 additions & 1 deletion src/parser/collect-stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export default (StoriesComponent, { stories = {}, allocatedIds }) => {

const unknownTemplate = template != null && templatesId.indexOf(template) < 0;

const storyFn = (args) => {
const storyFn = (args, storyContext) => {
if (unknownTemplate) {
throw new Error(`Story ${name} is referencing an unknown template ${template}`);
}
Expand All @@ -91,6 +91,7 @@ export default (StoriesComponent, { stories = {}, allocatedIds }) => {
storyName: name,
templateId: template,
args,
storyContext,
sourceComponent: component || globalComponent,
},
};
Expand Down
20 changes: 20 additions & 0 deletions stories/__snapshots__/context.stories.storyshot
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Storyshots StoryContext StoryContext 1`] = `
<section
class="storybook-snapshot-container"
>

<div>
StoryContext.name =
StoryContext
</div>

<div>
StoryContext.id =
storycontext--story-context
</div>


</section>
`;
11 changes: 11 additions & 0 deletions stories/context.stories.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<script>
import { Meta, Story } from '../src/index';
import Button from './Button.svelte';
</script>

<Meta title="StoryContext" component={Button} />

<Story name="StoryContext" let:context>
<div>StoryContext.name = {context.name}</div>
<div>StoryContext.id = {context.id}</div>
</Story>

0 comments on commit be57bc3

Please sign in to comment.