Skip to content

Commit

Permalink
Fix forwarding of actions handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
j3rem1e committed Sep 21, 2023
1 parent 56aa308 commit 2c47fae
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ It supports:
</script>
<Template let:args>
<Button {...args} on:click={handleClick}>
<!--👇 'on:click' allows to forward event to addon-actions -->
<Button {...args}
on:click
on:click={handleClick}>
You clicked: {count}
</Button>
</Template>
Expand All @@ -48,6 +51,9 @@ It supports:
</Story>
```

Actions are automatically registered by Storybook. To be used by this addon, you just have to forward the event (`on:click` in the previous example).


## Getting Started

1. `npm install --save-dev @storybook/addon-svelte-csf` or `yarn add --dev @storybook/addon-svelte-csf`
Expand Down
18 changes: 17 additions & 1 deletion src/components/RenderContext.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,25 @@
export let args = {};
export let storyContext = {};
/** @type {import('svelte').SvelteComponent} */
let instance;
createRenderContext($$props);
// events are static and don't need to be reactive
const eventsFromArgTypes = Object.fromEntries(
Object.entries(storyContext.argTypes)
.filter(([k, v]) => v.action && args[k] != null)
.map(([k, v]) => [v.action, args[k]])
);
$: setStoryRenderContext(args, storyContext);
$: if (instance) {
Object.entries(eventsFromArgTypes).forEach(([event, handler]) => instance.$on(event, handler));
}
</script>

<svelte:component this={Stories} />
<svelte:component this={Stories} bind:this={instance}/>
2 changes: 1 addition & 1 deletion stories/button.stories.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<Meta component={Button}/>

<Template let:args>
<Button {...args} on:click={handleClick}>
<Button {...args} on:click={handleClick} on:click>
You clicked: {count}
</Button>
</Template>
Expand Down

0 comments on commit 2c47fae

Please sign in to comment.