Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ import { useParameter } from "@storybook/preview-api";

import { PARAM_KEY } from "./constants";

export const withQuery: DecoratorFunction = (StoryFn) => {
const parameters = useParameter(PARAM_KEY, null);
export const withQuery: DecoratorFunction = (StoryFn, StoryContext) => {
let parameters = useParameter(PARAM_KEY, null);
const { location } = document;
const currentQuery = new URLSearchParams(location.search);

if (parameters) {
const additionalQuery =
typeof parameters === "string"
? new URLSearchParams(parameters)
: parameters;
if (typeof parameters === "string") {
parameters = new URLSearchParams(parameters);
}
else if (typeof parameters === "function") {
parameters = parameters(StoryContext);
}

const additionalQuery = parameters;

const newLocation = new URL(document.location.href);
newLocation.search = new URLSearchParams({
Expand Down
31 changes: 31 additions & 0 deletions src/stories/params.function.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Meta, StoryContext, StoryObj } from '@storybook/react';
import React from 'react';

const mapParams = (params: URLSearchParams) => {
const output: React.JSX.Element[] = [];
[...params.keys()].forEach((key: string) => {
output.push(<div key={key}><strong>{key}</strong>: {params.get(key)}</div>);
});
return output;
}

const meta: Meta<{}> = {
title: 'Example/Params-Function',
component: () => {
const urlParams = new URLSearchParams(document.location.search);
return <div>Mocked params: {mapParams(urlParams)}</div>;
},
parameters: {
query: (context: StoryContext) => {
return {
id: context.id,
mock: "Hello world from callback!",
};
}
},
};

export default meta;
type Story = StoryObj<{}>;

export const Playground: Story = {};