Back to Storybook

Your Component With Decorator With Context

docs/_snippets/your-component-with-decorator-with-context.md

10.5.53.3 KB
Original Source
svelte
<script module>
  import { setContext } from 'svelte';

  import { defineMeta } from '@storybook/addon-svelte-csf';

  import YourComponent from './YourComponent.svelte';
  import MarginDecorator from './MarginDecorator.svelte';

  const { Story } = defineMeta({
    component: YourComponent,
    decorators: [
      (story, { globals }) => {
        const marginSize = globals.marginSize === 'small' ? 'small' : 'medium';
        setContext('marginSize', marginSize);
        return { Component: MarginDecorator };
      },
    ],
  });
</script>
js
import { setContext } from 'svelte';

import YourComponent from './YourComponent.svelte';
import MarginDecorator from './MarginDecorator.svelte';

export default {
  component: YourComponent,
  decorators: [
    (story, { globals }) => {
      const marginSize = globals.marginSize === 'small' ? 'small' : 'medium';
      setContext('marginSize', marginSize);
      return { Component: MarginDecorator };
    },
  ],
};
svelte
<script>
  import { getContext } from 'svelte';

  let { children } = $props();

  const size = getContext('marginSize') || 'medium';
  const margin = size === 'small' ? '1rem' : '3rem';
</script>

<div style="margin: {margin};">
  {@render children?.()}
</div>
svelte
<script module lang="ts">
  import { setContext } from 'svelte';

  import { defineMeta } from '@storybook/addon-svelte-csf';

  import YourComponent from './YourComponent.svelte';
  import MarginDecorator from './MarginDecorator.svelte';

  const { Story } = defineMeta({
    component: YourComponent,
    decorators: [
      (story, { globals }) => {
        const marginSize = globals.marginSize === 'small' ? 'small' : 'medium';
        setContext('marginSize', marginSize);
        return { Component: MarginDecorator };
      },
    ],
  });
</script>
ts
import { setContext } from 'svelte';
// Replace your-framework with svelte-vite or sveltekit
import type { Meta } from '@storybook/your-framework';

import YourComponent from './YourComponent.svelte';
import MarginDecorator from './MarginDecorator.svelte';

const meta = {
  component: YourComponent,
  decorators: [
    (story, { globals }) => {
      const marginSize = globals.marginSize === 'small' ? 'small' : 'medium';
      setContext('marginSize', marginSize);
      return { Component: MarginDecorator };
    },
  ],
} satisfies Meta<typeof YourComponent>;

export default meta;
svelte
<script lang="ts">
  import { getContext, type Snippet } from 'svelte';

  interface Props {
    children?: Snippet;
  }

  let { children }: Props = $props();

  const size = getContext<'small' | 'medium'>('marginSize') ?? 'medium';
  const margin = size === 'small' ? '1rem' : '3rem';
</script>

<div style="margin: {margin};">
  {@render children?.()}
</div>