GithubHelp home page GithubHelp logo

addon-knobs's Introduction

Storybook Addon Knobs (deprecated)

We are deprecating Knobs in favor of @storybook/addon-controls.

Discussion: storybookjs/storybook#15060

Storybook Addon Knobs allow you to edit props dynamically using the Storybook UI. You can also use Knobs as a dynamic variable inside stories in Storybook.

Framework Support.

This is what Knobs looks like:

Storybook Knobs Demo

Checkout the above Live Storybook or watch this video.

Getting Started

First of all, you need to install Knobs into your project as a dev dependency.

yarn add @storybook/addon-knobs --dev

The latest version of this addon supports Storybook v7. If you're using a previous version of Storybook you need to install the matching version of this addon, eg @storybook/[email protected].

within .storybook/main.js:

module.exports = {
  addons: ['@storybook/addon-knobs'],
};

Now, write your stories with Knobs.

With React

import React from 'react';
import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';

export default {
  title: 'Storybook Knobs',
  decorators: [withKnobs],
};
// Add the `withKnobs` decorator to add knobs support to your stories.
// You can also configure `withKnobs` as a global decorator.

// Knobs for React props
export const withAButton = () => (
  <button disabled={boolean('Disabled', false)}>{text('Label', 'Hello Storybook')}</button>
);

// Knobs as dynamic variables.
export const asDynamicVariables = () => {
  const name = text('Name', 'James');
  const age = number('Age', 35);
  const content = `I am ${name} and I'm ${age} years old.`;

  return <div>{content}</div>;
};

With Vue.js

MyButton.story.js:

import { storiesOf } from '@storybook/vue';
import { withKnobs, text, boolean } from '@storybook/addon-knobs';

import MyButton from './MyButton.vue';

export default {
  title: 'Storybook Knobs',
  decorators: [withKnobs],
};

// Assign `props` to the story's component, calling
// knob methods within the `default` property of each prop,
// then pass the story's prop data to the component’s prop in
// the template with `v-bind:` or by placing the prop within
// the component’s slot.
export const exampleWithKnobs = () => ({
  components: { MyButton },
  props: {
    isDisabled: {
      default: boolean('Disabled', false),
    },
    text: {
      default: text('Text', 'Hello Storybook'),
    },
  },
  template: `<MyButton :isDisabled="isDisabled">{{ text }}</MyButton>`,
});

MyButton.vue:

<template>
  <button :disabled="isDisabled">
    <slot></slot>
  </button>
</template>

<script>
export default {
  props: {
    isDisabled: {
      type: Boolean,
      default: false,
    },
  },
};
</script>

With Angular

import { storiesOf } from '@storybook/angular';
import { boolean, number, text, withKnobs } from '@storybook/addon-knobs';

import { Button } from '@storybook/angular/demo';

export default {
  title: 'Storybook Knobs',
  decorators: [withKnobs],
};

export const withKnobs = () => ({
  component: Button,
  props: {
    text: text('text', 'Hello Storybook'), // The first param of the knob function has to be exactly the same as the component input.
  },
});

With Ember

import { withKnobs, text, boolean } from '@storybook/addon-knobs';
import { hbs } from 'ember-cli-htmlbars';

export default {
  title: 'StoryBook with Knobs',
  decorators: [withKnobs],
};

export const button = () => ({
  template: hbs`
    <button disabled={{disabled}}>{{label}}</button>
  `,
  context: {
    label: text('label', 'Hello Storybook'),
    disabled: boolean('disabled', false),
  },
});

Categorization

Categorize your Knobs by assigning them a groupId. When a groupId exists, tabs will appear in the Knobs storybook panel to filter between the groups. Knobs without a groupId are automatically categorized into the ALL group.

export const inGroups = () => {
  const personalGroupId = 'personal info';
  const generalGroupId = 'general info';

  const name = text('Name', 'James', personalGroupId);
  const age = number('Age', 35, { min: 0, max: 99 }, personalGroupId);
  const message = text('Hello!', 35, generalGroupId);
  const content = `
    I am ${name} and I'm ${age} years old.
    ${message}
  `;

  return <div>{content}</div>;
};

You can see your Knobs in a Storybook panel as shown below.

Available Knobs

These are the Knobs available for you to use. You can import these Knobs from the @storybook/addon-knobs module. Here's how to import the text Knob.

import { text } from '@storybook/addon-knobs';

Just like that, you can import any other following Knobs:

text

Allows you to get some text from the user.

import { text } from '@storybook/addon-knobs';

const label = 'Your Name';
const defaultValue = 'James';
const groupId = 'GROUP-ID1';

const value = text(label, defaultValue, groupId);

boolean

Allows you to get a boolean value from the user.

import { boolean } from '@storybook/addon-knobs';

const label = 'Agree?';
const defaultValue = false;
const groupId = 'GROUP-ID1';

const value = boolean(label, defaultValue, groupId);

number

Allows you to get a number from the user.

import { number } from '@storybook/addon-knobs';

const label = 'Age';
const defaultValue = 78;
const groupId = 'GROUP-ID1';

const value = number(label, defaultValue);

For use with groupId, pass the default options as the third argument.

const value = number(label, defaultValue, {}, groupId);

number bound by range

Allows you to get a number from the user using a range slider.

import { number } from '@storybook/addon-knobs';

const label = 'Temperature';
const defaultValue = 73;
const options = {
  range: true,
  min: 60,
  max: 90,
  step: 1,
};
const groupId = 'GROUP-ID1';

const value = number(label, defaultValue, options, groupId);

color

Allows you to get a colour from the user.

import { color } from '@storybook/addon-knobs';

const label = 'Color';
const defaultValue = '#ff00ff';
const groupId = 'GROUP-ID1';

const value = color(label, defaultValue, groupId);

object

Allows you to get a JSON object or array from the user.

import { object } from '@storybook/addon-knobs';

const label = 'Styles';
const defaultValue = {
  backgroundColor: 'red',
};
const groupId = 'GROUP-ID1';

const value = object(label, defaultValue, groupId);

Make sure to enter valid JSON syntax while editing values inside the knob.

array

Allows you to get an array of strings from the user.

import { array } from '@storybook/addon-knobs';

const label = 'Styles';
const defaultValue = ['Red'];
const groupId = 'GROUP-ID1';

const value = array(label, defaultValue);

While editing values inside the knob, you will need to use a separator. By default it is a comma, but this can be overridden by passing a separator variable.

import { array } from '@storybook/addon-knobs';

const label = 'Styles';
const defaultValue = ['Red'];
const separator = ':';
const value = array(label, defaultValue, separator);

For use with groupId, pass the default separator as the third argument.

const value = array(label, defaultValue, ',', groupId);

select

It allows you to get a value from a select box from the user.

import { select } from '@storybook/addon-knobs';

const label = 'Colors';
const options = {
  Red: 'red',
  Blue: 'blue',
  Yellow: 'yellow',
  Rainbow: ['red', 'orange', 'etc'],
  None: null,
};
const defaultValue = 'red';
const groupId = 'GROUP-ID1';

const value = select(label, options, defaultValue, groupId);

Options can also be an array:

import { select } from '@storybook/addon-knobs';
const label = 'Cats';
const options = ['linus', 'eleanor', 'lover'];
const defaultValue = 'eleanor';
const groupId = 'GROUP-ID2';
const value = select(label, options, defaultValue, groupId);

Options can also be an array OF objects:

const label = 'Dogs';
const arrayOfObjects = [
  {
    label: 'Sparky',
    dogParent: 'Matthew',
    location: 'Austin',
  },
  {
    label: 'Juniper',
    dogParent: 'Joshua',
    location: 'Austin',
  },
];
const defaultValue = arrayOfObjects[0];
const groupId = 'GROUP-ID3';
const value = select(label, arrayOfObjects, defaultValue, groupId);

radio buttons

It allows you to get a value from a list of radio buttons from the user.

import { radios } from '@storybook/addon-knobs';

const label = 'Fruits';
const options = {
  Kiwi: 'kiwi',
  Guava: 'guava',
  Watermelon: 'watermelon',
};
const defaultValue = 'kiwi';
const groupId = 'GROUP-ID1';

const value = radios(label, options, defaultValue, groupId);

options

Configurable UI for selecting a value from a set of options.

import { optionsKnob } from '@storybook/addon-knobs';

const label = 'Fruits';
const valuesObj = {
  Kiwi: 'kiwi',
  Guava: 'guava',
  Watermelon: 'watermelon',
};
const defaultValue = 'kiwi';
const optionsObj = {
  display: 'inline-radio',
};
const groupId = 'GROUP-ID1';

const value = optionsKnob(label, valuesObj, defaultValue, optionsObj, groupId);

Alternatively you can use this import:

import { optionsKnob as options } from '@storybook/addon-knobs';

...

const value = options(label, valuesObj, defaultValue, optionsObj, groupId);

The display property for optionsObj accepts:

  • radio
  • inline-radio
  • check
  • inline-check
  • select
  • multi-select

files

It allows you to get a value from a file input from the user.

import { files } from '@storybook/addon-knobs';

const label = 'Images';
const accept = '.xlsx, .pdf';
const defaultValue = [];
const groupId = 'GROUP-ID1';

const value = files(label, accept, defaultValue, groupId);

You can optionally specify a list of file types which the file input should accept. Multiple files can be selected, and will be returned as an array of Data URLs.

date

Allows you to get date (and time) from the user.

import { date } from '@storybook/addon-knobs';

const label = 'Event Date';
const defaultValue = new Date('Jan 20 2017');
const groupId = 'GROUP-ID1';

const value = date(label, defaultValue, groupId);

Note: the default value must not change - e.g., do not do date('Label', new Date()) or date('Label').

The date knob returns the selected date as stringified Unix timestamp (e.g. "1510913096516"). If your component needs the date in a different form you can wrap the date function:

function myDateKnob(name, defaultValue) {
  const stringTimestamp = date(name, defaultValue);
  return new Date(stringTimestamp);
}

button

It allows you to include a button and associated handler.

import { button } from '@storybook/addon-knobs';

const label = 'Do Something';
const handler = () => doSomething('foobar');
const groupId = 'GROUP-ID1';

button(label, handler, groupId);

Button knobs cause the story to re-render after the handler fires. You can prevent this by having the handler return false.

withKnobs options

withKnobs also accepts two optional options as story parameters. Usage:

import { withKnobs } from '@storybook/addon-knobs';

export default {
  title: 'Storybook Knobs',
  decorators: [withKnobs],
};

export const defaultView = () => <div />;
defaultView.parameters = {
  knobs: {
    // Doesn't emit events while user is typing.
    timestamps: true,

    // Escapes strings to be safe for inserting as innerHTML. This option is true by default. It's safe to set it to `false` with frameworks like React which do escaping on their side.
    // You can still set it to false, but it's strongly discouraged to set to true in cases when you host your storybook on some route of your main site or web app.
    escapeHTML: true,
  },
};

Typescript

If you are using Typescript, make sure you have the type definitions installed for the following libs:

  • node
  • react

You can install them using: (assuming you are using Typescript >2.0.)

yarn add @types/node @types/react --dev

addon-knobs's People

Contributors

hydrosquall avatar jonniebigodes avatar jreinhold avatar literalpie avatar shilman avatar silic0ns0ldier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

addon-knobs's Issues

addon-knobs select typedef missing Record

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @storybook/[email protected] for the project I'm working on.

The select knob typedefs are missing an option for including Record types. This fixes the problem

Here is the diff that solved my problem:

diff --git a/node_modules/@storybook/addon-knobs/dist/ts3.9/components/types/Select.d.ts b/node_modules/@storybook/addon-knobs/dist/ts3.9/components/types/Select.d.ts
index 41b5844..60527a4 100644
--- a/node_modules/@storybook/addon-knobs/dist/ts3.9/components/types/Select.d.ts
+++ b/node_modules/@storybook/addon-knobs/dist/ts3.9/components/types/Select.d.ts
@@ -1,6 +1,6 @@
 import { FunctionComponent } from 'react';
 import { KnobControlConfig, KnobControlProps } from './types';
-export declare type SelectTypeKnobValue = string | number | boolean | null | undefined | PropertyKey[];
+export declare type SelectTypeKnobValue = string | number | boolean | null | undefined | PropertyKey[] | Record<string, unknown>;
 export declare type SelectTypeOptionsProp<T extends SelectTypeKnobValue = SelectTypeKnobValue> = Record<PropertyKey, T> | Record<Extract<T, PropertyKey>, T[keyof T]> | T[] | readonly T[];
 export interface SelectTypeKnob<T extends SelectTypeKnobValue = SelectTypeKnobValue> extends KnobControlConfig<T> {
     options: SelectTypeOptionsProp<T>;

This issue body was partially generated by patch-package.

Storybook Knob: Color knob allowing output be RGB or Hex

Is your feature request related to a problem? Please describe
Color knob always returning RGB and not hexcode color.

Describe the solution you'd like
Would like to have an option (or some way) to select which output is selected

Are you able to assist to bring the feature to reality?
yes, I can...

v5.2.5: Only first change of a knob is registered

Describe the bug
Only the first change to a text or number field (probably other types as well) registers and causes the component to update. It seems to be caused by there being a single set event (for which there is a listener) and no listeners for the subsequent change events.

To Reproduce
Steps to reproduce the behavior:

  1. Add a string knob to any component
  2. See it render on the storybook
  3. Change the value
  4. See it update. The console will say something about storybookjs/knobs/set
  5. Change the value again
  6. Assert there has been no change/rerender. The console will say something about storybookjs/knobs/change for each subsequent change

Expected behavior
The console should rerender

Screenshots
This screenshot shows there are 0 listeners registered for the change event:
screenshot

Code snippets

    <ConversationSummary
        mostRecentMessage={text('Most recent message', "hey, there, is it me you're looking for?")}
        numberOfUnreadMessages={number('Unread messages', 2)}
      })}
    />

System:
npx -p @storybook/cli@next sb info just hangs and never gets past this output:

Environment Info:

My manual way:

$ jq .dependencies package.json  | egrep 'react|storybook' | pbcopy; pbpaste
  "react": "^16.11.0",
  "react-addons-deep-compare": "0.0.1",
  "react-autosuggest": "^9.4.3",
  "react-dom": "^16.11.0",
  "react-idle-timer": "^4.2.11",
  "react-json-view": "^1.19.1",
  "react-jss": "^8.6.1",
  "react-redux": "^7.1.1",
  "react-router": "^5.1.2",
  "react-router-dom": "^5.1.2",
  "tcomb-react": "^0.9.3",

$ jq .devDependencies package.json  | egrep 'react|storybook' | pbcopy; pbpaste
  "@babel/plugin-transform-react-jsx": "^7.3.0",
  "@storybook/addon-actions": "^5.2.5",
  "@storybook/addon-knobs": "^5.2.5",
  "@storybook/addon-links": "^5.2.5",
  "@storybook/react": "^5.2.5",
  "@storybook/ui": "^5.2.5",
  "@testing-library/react": "^9.3.0",
  "enzyme-adapter-react-16": "^1.15.1",
  "eslint-plugin-react": "^7.16.0",

Additional context
Reverting @storybook/* to v5.1.9 will fix the issue.

Unable to change knobs when following CONTRIBUTING guidelines for reproducing a bug

Describe the bug
This may just be missing information in the CONTRIBUTING.md file, but I followed the steps in the CONTRIBUTING.md for reproductions. I opened the /examples/official-storybook folder and ran storybook, and got an error when trying to change a knob. I am seeing an error that the dotenv file is not loaded, not sure if this is related, but guessing that it is unrelated.

This may just be an issue of needing more documentation in the CONTRIBUTING.md - is there an extra step that needs to be taken to use addons?

To Reproduce
Steps to reproduce the behavior:

  1. git clone https://github.com/storybookjs/storybook.git
  2. cd storybook
  3. yarn bootstrap --core2. Click on '....'
  4. cd examples/official-storybook
  5. yarn storybook
  6. open the story addons -> knobs -> withknobs -> select-knob
  7. try to change the value knob
  8. get an error message (see below) and the value doesn't change

Expected behavior
A clear and concise description of what you expected to happen.
The knob changes and the corresponding value changes

** Screenshots **
image

Code snippets
If applicable, add code samples to help explain your problem.

TypeError: Cannot set property 'value' of undefined
    at Object.knobChanged (registerKnobs.js:38)
    at index.js:188
    at Array.forEach (<anonymous>)
    at Channel.handleEvent (index.js:187)
    at PostmsgTransport.<anonymous> (index.js:77)
    at PostmsgTransport.handler (index.js:126)
    at PostmsgTransport.handleEvent (index.js:300)
error @ index.js:60

System
Please paste the results of npx sb@next info here.

Additional context
Add any other context about the problem here.

Code Preview for Knobs

We are producing WebComponents with several options. The Addon "Knobs" is perfect to show the result of the combination of these knobs.
Our customers wants to compose their combination of knobs they want and copy that sourcecode. Our goal would be to show that code as a preview and give the possibility to copy that with one click.

For example we have the component "axa-button":
The code of the story is like
<axa-button variant="${allVariants}"</axa-button>

and if the user choose "red" from knobs addon, he wants to get that code-snippet to copy:
<axa-button variant="red"</axa-button>

You can find that button showcase for our project here.

Is or would that be possible?

Thanks
Daniel

Invalid hook call error when using addon Knobs "text" knob

Describe the bug
Related to:

Screen Shot 2020-09-04 at 2 56 38 PM

When using addon knobs, any use of the text knob with causes the above error. Removing knobs of this type while keeping other types do not cause the error

To Reproduce
"@storybook/addon-knobs": "^6.0.21",

Company source code, so cannot link.

  1. Create a normal story for a component
  2. use withKnobs decorator
  3. add a knob control of type text
  4. run storybook

Expected behavior
Story for component loads with knob

Code snippets

Default.args = {
    options,
    disabled: boolean('disabled', false),
    platform: select('platform', ['P1','P2'], 'P1'),
    text1: text('text1', ''),
};

....or ....
<MyComponent
    options={options}
    disabled={boolean('disabled', false)}
    platform={select('platform', ['P1','P2'], 'P1')}
    text1={text('text1', '')}
/>

System:

Environment Info:
System:
OS: macOS 10.15.6
CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
Binaries:
Node: 12.6.0 - ~/.nvm/versions/node/v12.6.0/bin/node
Yarn: 1.22.4 - ~/.yarn/bin/yarn
npm: 6.13.7 - ~/.nvm/versions/node/v12.6.0/bin/npm
Browsers:
Chrome: 85.0.4183.83
Safari: 13.1.2
npmPackages:
@storybook/addon-actions: ^6.0.21 => 6.0.21
@storybook/addon-console: ^1.2.1 => 1.2.1
@storybook/addon-docs: ^6.0.21 => 6.0.21
@storybook/addon-info: ^5.3.21 => 5.3.21
@storybook/addon-jest: ^6.0.21 => 6.0.21
@storybook/addon-knobs: ^6.0.21 => 6.0.21
@storybook/addon-links: ^6.0.21 => 6.0.21
@storybook/addon-options: ^5.3.21 => 5.3.21
@storybook/addon-storyshots: ^6.0.21 => 6.0.21
@storybook/addon-storysource: ^6.0.21 => 6.0.21
@storybook/addon-viewport: ^6.0.21 => 6.0.21
@storybook/addons: 6.0.21 => 6.0.21
@storybook/channels: 6.0.21 => 6.0.21
@storybook/preset-create-react-app: ^3.1.4 => 3.1.4
@storybook/preset-typescript: ^3.0.0 => 3.0.0
@storybook/react: 6.0.21 => 6.0.21
@storybook/source-loader: ^6.0.21 => 6.0.21
@storybook/storybook-deployer: ^2.8.6 => 2.8.6

Addon Knobs - Add function type

Is your feature request related to a problem? Please describe
I am discovering Knobs, I see many supported types (text, bool, number...) but nothing for functions.

How to create a knobs for a function ?
showModal={() => {}}

I tried to pass it as object but get a console error (Invalid prop knob.value supplied)
I also tried to pass as text with "() => {}" but of course it generates an error as the component propType want a function, not a string.

Describe the solution you'd like
Maybe we could have something like
showModal=func("showModal", () => {})
And the UI would convert it with an eval, but I am afraid this eval would bring security issues. Maybe something equivalent ?

Describe alternatives you've considered
None.

Are you able to assist to bring the feature to reality?
no

Additional context
Storybook 6

Reopening of storybookjs/storybook#9265

SO: https://stackoverflow.com/questions/54072656/storybook-addon-knobs-callback-function-knob

Allow setting individual values

I'd like to be able to manually set knob values after initialization.
eg:

import { setValue, boolean } from '@storybook/addon-knobs'
....
const isShown = boolean('isShown', false)
<button onClick={() => { setValue('isShown', true) }}>Show Modal</button>
<Modal isShown(isShown)>...</Modal>

Is this something you all are planning on supporting?

Knobs not updating and sometimes not showing

Describe the bug
I am using the knobs addon and only occasionally do the knobs appear in the 'Knobs' panel. When they do appear, changing them seems to have no affect on the component.

I know that they much be linked to the component as the default values are what show in the component that renders on the screen

To Reproduce
Steps to reproduce the behavior:
I have installed storybook and the knobs addon.
Add the decorator in the global config.
Import the addon in addons.js
Add the knobs within the story
Run yarn run storybook
View the storybook page

Expected behavior
I expect to see the knobs for each story in the knobs panel. I expect the content in the component to update in real time. The example sites that I've played around with do this.

Screenshots
This story has knobs
screen shot 2019-02-01 at 12 06 33 pm

The knobs here are showing, but have not updated the component
screen shot 2019-02-01 at 12 07 32 pm

Code snippets
// config.js

import { withKnobs } from '@storybook/addon-knobs/react';
...
addDecorator(
  withKnobs({
    escapeHTML: false
  })
);
...
configure(loadStories, module);

// addons.js

import '@storybook/addon-knobs/register';

// story

import React from 'react';
import { storiesOf } from '@storybook/react';
import { CenterDecorator } from 'Storybook/decorators';
import {
  object, text, select
} from '@storybook/addon-knobs/react';
import ContestCard from '..';

const group = 'ContestCard ownership';

const ownershipShape = {
  id: 'bbe9b07c-4b75-4eb4-82b6-b330aa4a895d',
  name: '3 Person Fast Best Ball',
  entry: 5,
  type: 'bestBall'
};

const sport = text('sport', 'NBA', group);
const id = text('id', ownershipShape.id, group);
const money = object('money', { cost: 5 }, group);
const type = text('type', ownershipShape.type, group);
const title = text('title', '3 Person Fast Best Ball', group);
const cardType = select('cardType', ['live', 'upcoming', 'results'], 'live', group);

storiesOf('Molecules/ContestCard', module)
  .addDecorator(CenterDecorator)
  .addWithJSX('props for Ownership', () => (
    <ContestCard
      sport={sport}
      id={id}
      money={money}
      type={type}
      title={title}
      cardType={cardType}
    />
  ));

System:

  • OS: MacOS Mojave 10.14.2
  • Device: Macbook Pro 2017
  • Browser: Chrome 71.0.3578.98
  • Framework: React
  • Addons: Knobs
  • Version: 4.1.11

Additional context
I have a custom webpack file, I'm not sure if that would matter, I need it for styles

Knobs panel is very broken after latest round of Storybook upgrades

Describe the bug
After upgrading all my Storybook packages to the latest versions, the Knobs panel is very broken. As I click through my stories, the number of knobs is always increasing, almost like Storybook is aggregating the knobs from multiple stories as I navigate the app. Even if I revert to 6.3.1 of @storybook/addon-knobs, I still see the problem, so evidently the other Storybook dependencies are not playing nicely.

To Reproduce
Upgrade all Storybook dependencies from 6.3.x to 6.4.x.

System

Environment Info:

  System:
    OS: Windows 10 10.0.19044
    CPU: (4) x64 Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz
  Binaries:
    Node: 16.13.0 - C:\Program Files\Node.js\node.EXE
    npm: 8.1.4 - C:\Program Files\Node.js\npm.CMD
  Browsers:
    Chrome: 96.0.4664.45
    Edge: Spartan (44.19041.1266.0), Chromium (96.0.1054.41)
  npmPackages:
    @storybook/addon-actions: 6.4.8 => 6.4.8
    @storybook/addon-docs: 6.4.8 => 6.4.8
    @storybook/addon-knobs: 6.3.1 => 6.3.1
    @storybook/addons: 6.4.8 => 6.4.8
    @storybook/api: 6.4.8 => 6.4.8
    @storybook/components: 6.4.8 => 6.4.8
    @storybook/core: 6.4.8 => 6.4.8
    @storybook/core-events: 6.4.8 => 6.4.8
    @storybook/react: 6.4.8 => 6.4.8
    @storybook/theming: 6.4.8 => 6.4.8

Copy knob state URL looses value type

Describe the bug
The knobs addon supports copying a URL with existing knob states. Some knobs may use a number as the value, however they are casted to a string when restoring knob state using the copied URL.

To Reproduce
https://github.com/Silic0nS0ldier/storybook-knobs-copy-bug

System

System:
  OS: macOS 10.15.7
  CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Binaries:
  Node: 12.22.1 - /usr/local/opt/node@12/bin/node
  Yarn: 1.22.10 - /usr/local/bin/yarn
  npm: 6.14.12 - /usr/local/opt/node@12/bin/npm
Browsers:
  Chrome: 90.0.4430.85
  Edge: 90.0.818.49
  Safari: 14.1
npmPackages:
  @storybook/addon-a11y: ^6.1.21 => 6.1.21 
  @storybook/addon-actions: ^6.1.21 => 6.1.21 
  @storybook/addon-knobs: ^6.1.21 => 6.1.21 
  @storybook/addon-viewport: ^6.1.21 => 6.1.21 
  @storybook/addons: ^6.1.21 => 6.1.21 
  @storybook/react: ^6.1.21 => 6.1.21

Additional context
NA

Getting RangeError: Maximum call stack size exceeded

Describe the bug
After upgrading to v6. When run yarn test -u i am getting below error.

RangeError: Maximum call stack size exceeded

  at node_modules/@storybook/addon-knobs/dist/KnobManager.js:84:17
      at Array.reduce (<anonymous>)
  at escapeStrings (node_modules/@storybook/addon-knobs/dist/KnobManager.js:83:30)
  at node_modules/@storybook/addon-knobs/dist/KnobManager.js:88:20
      at Array.reduce (<anonymous>)

Here is my story component:

export const Default = () => {
const children = (


This is a child i think. The hope is that by me typing with a ton of new lines that i'll bring up the custom
Scrollbar Do you see it? I'm not sure yet so i'm going to keep typing. Don't judge this stream of typing

);

return (
    <Scrollbar
        width={number('Width', 150)}
        height={number('Height', 120)}
        className={text('css classes', '')}
        children={object('Child node', children)}
        autoHide={boolean('Auto hide', false)}
    />
);

};

Count in the Knobs tab is "behind by one" when clicking through stories

Describe the bug
When clicking through stories, the count (of knobs) in the Knobs tab is wrong. More specifically, it's always "behind by one", meaning that it's showing the count from the previous story that was selected.

To Reproduce
Steps to reproduce the behavior:

  1. Have multiple stories with differing counts of knobs
  2. Click through the stories

Expected behavior
The knob count should be correct.

System

Environment Info:

  System:
    OS: Windows 10 10.0.19042
    CPU: (4) x64 Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz
  Binaries:
    Node: 14.15.0 - C:\Program Files\Node.js\node.EXE
    Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.8 - C:\Program Files\Node.js\npm.CMD
  Browsers:
    Chrome: 87.0.4280.88
    Edge: Spartan (44.19041.423.0), Chromium (87.0.664.55)

@storybook/addon-knobs install in devDependencies

The storybook documentation tells you to install it in'devDependency',
but if you install it in'devDependency',
it says" '@storybook/addon-knobs' should be listed in the project's dependencies, not devDependencies. "

Looking at the packages, it seems that there are some packages that are used in production mode.
Is it correct to install it on devDependency?

Knobs array of objects does not work with a function property

Support request summary

I have a story that uses the object knob with an array of objects. These objects have an "onSort" property:

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name",
    width: "50%",
    onSort: () => console.log("onSort was called")
  },  ...
]


storiesOf("Table", module).add("simple Table", () => {
  return (
    <Table columns={object("columns", columns)} data={object("data", data)} />
  );
});

This is valid javascript, but serializing it strips out the function property because it's not valid JSON:
image

Is there a workaround for this?

Steps to reproduce

  • Create a story with a prop that is an array of objects, and includes a function as a property value, as shown above.
  • Use the objects knob
  • Notice that the function prop is missing

Please specify which version of Storybook and optionally any affected addons that you're running

  • @storybook/react 3.4.10
  • @storybook/addon-knobs 3.4.10

date knob incorrectly deserializes value

Describe the bug
https://github.com/storybookjs/storybook/blob/next/addons/knobs/src/converters.ts#L18 has this deserialization code:

 (value: any): number => new Date(value).getTime() || new Date().getTime(),

However, since value is a Date when used in the iframe, but is a number when used in a new tab (by clicking on the open Canvas in new tab button), it always initializes to the current date.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

When deserializing, the value is a string instead of a number, and so will be the string representation of the timestamp. The Date object then tries to parse this string as a date string, fails, and falls back to today's date.

fix is straightforward:

 (value: string | number): number => new Date(+value).getTime() || new Date().getTime(),

To Reproduce
Steps to reproduce the behavior:

  1. add a date knob
  2. set a value
  3. open the canvas in a new tab

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Code snippets
If applicable, add code samples to help explain your problem.

System
Please paste the results of npx sb@next info here.

Additional context
Add any other context about the problem here.

[knobs] Knobs don't appear on refresh when a decorator includes a suspense boundary

Describe the bug

When hittin

Note: May also apply to stories with suspense boundaries. Not tested.

To Reproduce

Consider the following application code

const Child = lazy(() => import("./Child"));

export const SomeComponent = ({ children }) => {
  return (
    <Suspense fallback={null}>
      <Child>
        {children}
      </Child>
    </Suspense>
  )
};

Consider the following decorator

const lazyDecorator = (Story, context) => {
  const someknob = Select("Something", ["A", "B"], "A");

  return (
    <SomeComponent>
      <Story {...context} />
    </SomeComponent>
  )
};

addDecorator(lazyDecorator);

Expected behavior

A decorator with a suspense boundary has no impact on how knobs work.

Screenshots

Kapture 2020-11-16 at 13 18 08

System

6.1.0-rc.3

Add peer dependency for React 18 [Bug]

Describe the bug

A clear and concise description of what the bug is.

Steps to reproduce the behavior

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

peer dependency for React 18

A clear and concise description of what you expected to happen.

Screenshots and/or logs

If applicable, add screenshots and/or logs to help explain your problem.

Environment

  • Node.js version: 16
  • NPM version: [e.g. 6.14.4]
  • Browser any
  • Browser version any
  • Device command line error

Additional context

At the moment this bug is causing our library of react components to still be reactc17.

This is a breaking issue for us!

Add any other context about the problem here.

Knobs & Backgrounds addons cause React hooks render error

Describe the bug
Error message: "Rendered more hooks than during the previous render." displayed instead of stories

To Reproduce
Steps to reproduce the behavior:

  1. Setup Storybook with Knobs and/or Background addons registered
  2. Add a global decorator (even a basic empty div)
  3. Run Storybook
  4. See error

Expected behavior
Story works as expected

Screenshots
image

Code snippets
preview.tsx

import type { Story } from '@storybook/react'

export const decorators = [
    (Story: Story) => (
        <div>
            <Story />
        </div>
    ),
]

System
Environment Info:

System:
OS: Windows 10 10.0.19042
CPU: (16) x64 Intel(R) Core(TM) i9-10980HK CPU @ 2.40GHz
Binaries:
Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.10 - C:\Program Files\nodejs\yarn.CMD
npm: 6.14.11 - C:\Program Files\nodejs\npm.CMD
Browsers:
Chrome: 89.0.4389.114
Edge: Spartan (44.19041.423.0), Chromium (89.0.774.68)
npmPackages:
@storybook/addon-essentials: ^6.2.2 => 6.2.2
@storybook/addon-knobs: ^6.2.2 => 6.2.2
@storybook/react: ^6.2.2 => 6.2.2

Additional context
I have verified that all hooks being used follow all rules of React hook standards. The error only occurs if these addons are registered. I verified these are the offending addons by isolating them as the only addons installed (one at a time) and with a single basic component story.

react: ^17.0.2
react-dom: ^17.0.2

.babelrc

{
    "presets": [
        [
            "@babel/preset-react",
            {
                "runtime": "automatic",
                "importSource": "@emotion/react"
            }
        ]
    ],
    "plugins": ["@emotion/babel-plugin"]
}

Knobs reset local state in storybook 6

Describe the bug
In Storybook 6, changing a knob's value causes local state to reset to default. Repro:

To Reproduce

import React, { useState } from 'react';
import { number, withKnobs } from '@storybook/addon-knobs';

export const Test = () => {
  number(`num`, 0);
  const [state, setState] = useState(0);
  return <div onClick={() => setState((s) => s + 1)}>{state}</div>;
};

export default { title: `testing`, component: Test, decorators: [withKnobs] };

clicking the div above will increment the output value, but then if you change the num knob, the value resets to 0. This does not happen in storybook 5.

escapeHTML option isn't respected in v6 with storiesOf

Describe the bug
Since updating to v6, my stories using the storiesOf api that configure the escapeHTML addon-knobs option present an error.

Config at the story level:

{
  knobs: {
    escapeHTML: false, // needed for greater than less than
  },
}

Error I see that relates to invalid props being passed on storyshot generation due to being HTML escaped:

Failed: "Warning: Failed prop type: Invalid prop `comparison` of value `&lt;` supplied to `Threshold`, expected one of [\"<\",\">\",\"=\",\"<=\",\">=\"].

I know I can migrate these stories to CSF and it will probably fix it, but it's my understanding that storiesOf is intended to be supported for the time being.

Props in a story are not passed if they're named the same way as in the Vue component

Describe the bug
Naming a prop in a story the same way the component's prop is named leads to a broken state where the property value is not passed to the component.
Both the story and the vue component use TypeScript.

Workaround
Naming the prop in the story differently from the respective prop in the component works.

To Reproduce

  1. Create a story in TypeScript for a Vue component that has properties.
  2. Define the property name in the story to be the same as the prop name in the component
  3. Pass the property in the template like template: '<Button :type="type" />'

Expected behavior
The prop value is passed to the component.

Code snippets

// Button.vue
<template>
	<button :class="[ 'wikit', 'wikit-Button', `wikit-Button--${ type }` ]">
		<slot />
	</button>
</template>

<script lang="ts">
import Vue from 'vue';
export default Vue.extend( {
	name: 'Button',
	props: {
		/**
		 * The type of the button
		 */
		type: {
			type: String,
			validator( value: string ): boolean {
				return [ 'neutral', 'progressive', 'destructive' ].includes( value );
			},
			default: 'neutral',
		},
	},
} );
</script>
// Button.stories.ts
import Button from '@/components/Button';
import { select } from '@storybook/addon-knobs';
import { Component } from 'vue';

export default {
	component: Button,
	title: 'Button',
};

export function normal(): Component {
	return {
		components: { Button },
		props: {
			// naming a prop the same way the component's prop is named leads to
			// a broken state where the property value is not passed to the component
			type: {
				default: select(
					'Type',
					[ 'neutral', 'progressive', 'destructive' ],
					'neutral',
				),
			},
		},
		template: '<Button v-html="content" :disabled="disabled" :type="type" />',
	};
}

System:

  System:
    OS: Linux 5.4 Ubuntu 18.04.4 LTS (Bionic Beaver)
  Binaries:
    Node: 12.17.0
    npm: 6.14.4
  Browsers:
    Chrome: 83.0.4103.116
    Firefox: 79.0
  npmPackages:
    @storybook/addon-a11y: ^6.0.4 => 6.0.4 
    @storybook/addon-docs: ^6.0.4 => 6.0.4 
    @storybook/addon-knobs: ^6.0.4 => 6.0.4 
    @storybook/vue: ^6.0.4 => 6.0.4 

I cannot think of anything wrong with either the Vue component or the story itself.

Knobs don't handle dynamic default value

Describe the bug
I update the storybook in 5.0.11 to 5.2.3 and have a regression bug with knobs. When changing values in knobs, react component not reloading with the correct value

To Reproduce
Steps to reproduce the behavior:

  1. Clone repo https://github.com/Tom910/storybook-knob-regression
  2. npm run storybook
  3. go to "as-dynamic-variables"
  4. Change knobs

Expected behavior
Knobs change props

System:

  System:
    OS: macOS 10.15
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
  Binaries:
    Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
    Yarn: 1.19.0 - /usr/local/bin/yarn
    npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm
  Browsers:
    Chrome: 77.0.3865.90
    Firefox: 68.0.2
    Safari: 13.0.2

Additional context
in storybook 5.0.11 work fine

[Bug] Semver breaking change in last release

Version 6.3.0 removes @storybook/addon-knobs/register entrypoint which was present in version 6.2.9, and needed for older versions of storybook. This caused an unexpected breaking of the build on my app.

I think the appropriate way to handle this would be to deprecate 6.3.0 (via npm deprecate) to avoid consumers accidentally upgrading to this version, and releasing either 6.3.1 with the register file included, or 7.0.0 with the package as it is.

Storybook Select knobs with long list is crashing

Select knob with long list options when an option is selected then the page is crashing, will need to reload.

To Reproduce

<Meta
title="Foundations/Icons/Iconography"
decorators={[
withKnobs({
escapeHTML: false
}),
moduleMetadata({
imports: [CommonModule, IconModule]
})
]}
parameters={{
a11y: { ...a11yConfig, element: 'icon' }
}}
/>

export const iconsList = [
{
label: 'vanguardLargeLogo white',
name: 'vanguardLargeLogo',
class: 'vanguardLogoWhite'
}, ........................
]

<Canvas mdxSource={<icon [icon]="iconData"></icon>}>

{{
template: <icon [icon]="iconData"></icon>,
props: {
iconData: select('Icon', iconsList, iconsList[0])
}
}}

System
"@storybook/addon-knobs": "~6.2.3",
Angular - v11.2

Additional context
This code is crashing only after upgrading to Angular 11 from angular 9 and storybook 6.2

Knobs : categorization doesn't work for object nested number prop

Describe the bug
When trying to categorize a prop with a number type, which is nested in an object, categorization doesn't work. It still appears in the "all" tab but not in the one indicated.

To Reproduce
Steps to reproduce the behavior:

  1. Edit a *.stories js with this knob
const personalGroupId = 'personal info';
const config  = { 
    numberProp: number('palindromeSize', 3, personalGroupId)
}
  1. numberProp appears in the "All" tab but not in the "personalGroupId" one

Expected behavior
numberProp appears in the "All" tab AND in the "personalGroupId" one

Screenshots
If applicable, add screenshots to help explain your problem.

Code snippets


const age = number('Age', 35, { min: 0, max: 99 }, personalGroupId); // works

const config  = { 
    	numberProp: number('palindromeSize', 3, personalGroupId); // doesn't work
}

Sharing knob values across stories

I've scoured the forum here as well as resources online, but can't seem to find an answer. How would I go about sharing knob values across different COMPONENTS? (ex. User navigates to a button component in Storybook and chooses to make it green, they then navigate to a form component -which includes the prev button as a subcomponent- and the button in there appears green).

I do not wish to use Storybook Controls as they do not support groups and thus make the interface very cumbersome for components with many settings.

Thanks so much guys!

Reopen of 9472: Addons / Knobs - When type is Number using the number knob, throws an error on delete and field is null

Quoting from storybookjs/storybook#9472 (closed as stale). I am still experiencing this issue, so I am reopening.

You have a knob, the prop type is Number and the default is number('something', 0). If the user deletes the 0 (or all digits in the field), an error is thrown in the console because the value cannot be null

vendors~main.5317d89c4b17337a8714.bundle.js:103113 Warning: value prop on input should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components.

To Reproduce
Steps to reproduce the behavior:

  1. Set a prop using a number knob in a story

    hello: {
    type: Number,
    default: number('hello', 0),
    },

    Use it in the template
    Run the Storybook
    Navigate to the story, delete the value in that knob field
    See error in console

Expected behavior
There is no error when the text in a number input is deleted. I believe the value of the input is being set to null when it should be set to an empty string instead. The value of the knob could be null, but the value of the input element should be an empty string.

Additonal Small Requested Change
In TypeScript the value of a number knob is typed as number, leaving no way to initialize the number input as empty. It would be nice to allow an option to initialize the value of the knob as null .

System

Environment Info:

  System:
    OS: Linux 5.4 Ubuntu 20.04.2 LTS (Focal Fossa)
    CPU: (12) x64 Intel(R) Core(TM) i7-9850H CPU @ 2.60GHz
  Binaries:
    Node: 14.15.3 - ~/.nvm/versions/node/v14.15.3/bin/node
    Yarn: 1.22.10 - ~/.nvm/versions/node/v14.15.3/bin/yarn
    npm: 6.14.9 - ~/.nvm/versions/node/v14.15.3/bin/npm
  Browsers:
    Chrome: 88.0.4324.96
    Firefox: 85.0
  npmGlobalPackages:
    @storybook/addon-knobs: 6.2.0-alpha.23

Additional context
It looks like this issue has been brought up a few times, and possibly fixed.

storybookjs/storybook#9472 (closed as stale)
storybookjs/storybook#8882 (closed as stale)
storybookjs/storybook#5912 (closed as fixed)
storybookjs/storybook#2475 (closed as fixed)

Knobs not working for iframe (Storybook v6)

Describe the bug
Knobs via url are not being set for iframe view on storybook. Tested in safari and chrome, the bug happens intermittently.

To Reproduce
Steps to reproduce the behavior:

  1. Go to any story with knobs
  2. Change some knobs for that story
  3. Open iframe view
  4. Knobs changed are not reflected on iframe view

Expected behavior
Knobs changed are reflected on iframe view

System:

Environment Info:

System:
OS: macOS 10.15.4
CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
Binaries:
Node: 12.18.2 - ~/.nvm/versions/node/v12.18.2/bin/node
Yarn: 1.22.4 - ~/.yarn/bin/yarn
npm: 6.14.6 - ~/.nvm/versions/node/v12.18.2/bin/npm
Browsers:
Chrome: 84.0.4147.135
Firefox: 77.0.1
Safari: 13.1
npmPackages:
@storybook/addon-a11y: ~6.0.13 => 6.0.19
@storybook/addon-console: ~1.2.1 => 1.2.1
@storybook/addon-essentials: ~6.0.13 => 6.0.19
@storybook/addon-events: ~6.0.13 => 6.0.19
@storybook/addon-knobs: ~6.0.13 => 6.0.19
@storybook/addon-links: ~6.0.13 => 6.0.19
@storybook/addon-storysource: ~6.0.13 => 6.0.19
@storybook/addons: ~6.0.13 => 6.0.19
@storybook/client-logger: ~6.0.13 => 6.0.19
@storybook/react: ~6.0.13 => 6.0.19
@storybook/theming: ~6.0.13 => 6.0.19

Knobs on iframe were working with the first migration to version 6

Use the new Framework API

Opening this issue so we can address the upcoming changes on how addons are built/updated for the upcoming 7.0 release. If anyone is interested in making the changes required and continuing to support and maintain the addon, let us know so that we're aware and help/guide the community moving forward. To help with this process, we've built an abridged guide here, and should any questions or issues, please reach out to us in the prerelease channel in our Discord Server.

Preview story in docs doesn't work if story uses knobs

Describe the bug
When I try to use multiple Story components that are using knobs inside my docs file, only the default data of the knob from the first story is displaying

To Reproduce
I have put up a small reproducible example that you can find here: https://github.com/justman00/next-js-storybook-docs-knobs-issue.

Expected behavior
Expected behavior is that even if I have multiple stories with different knobs default value I should see the components accordingly in the docs as they are displayed in canvas:

export const firstStory = () => (
  <Demo content={text('content', 'This always shows')} />
);

export const secondStory = () => (
  <Demo content={text('content', 'this shows only in canvas')} />
);

export const thirdStory = () => (
  <Demo content={text('content', 'this shows also only in canvas')} />
);

From the code above in docs I should be able to see the same component with different content. However it is displayed with the value from the first story.

Here is the code from the docs:

<Preview withSource="none">
  <Story id="demo--first-story" />
</Preview>

<Preview withSource="none">
  <Story id="demo--second-story" />
</Preview>

<Preview withSource="none">
  <Story id="demo--third-story" />
</Preview>

Screenshots
Screen Shot 2021-02-02 at 17 15 37

Screen Shot 2021-02-02 at 17 15 25

Getting warning with select Knobs: Warning: Failed prop type: Invalid prop `knob.value` of type `number` supplied to `SelectType`, expected `string`.

If you are reporting a bug or requesting support, start here:

Bug or support request summary

I'm trying to use select and lately selectv2 as the first one is deprecated but I'm still getting this warning:

Warning: Failed prop type: Invalid prop `knob.value` of type `number` supplied to `SelectType`, expected `string`.

I should not have this warning at all.

Steps to reproduce

Create a new story file with this basics content:

import React from 'react';
import { storiesOf } from '@storybook/react';
import { selectV2, withKnobs } from '@storybook/addon-knobs';

const stories = storiesOf('Select', module);
stories.addDecorator(withKnobs);

// Basic items I used for each of my story
const items = [0, 1, 2]
  .map(item => ({
    title: `Item ${item}`,
    key: item
  }));

// Then the story I use the select and it gets the warning
stories.add('with item already selected', () => {
  //  I create an object like { ITEM_0: 0, ITEM_1: 1, ...). Didnt find another way to directly use my array of objects
  const selected = selectV2(
    'Selected Items',
    items.reduce((options, item) => ({ ...options, [item.title]: item.key }), {}),
    1
  );
  return (
    <Select
      name="select"
      items={items}
      selected={items[selected]}
      onListSelect={() => null}
    />
  );
});

Please specify which version of Storybook and optionally any affected addons that you're running

  • @storybook/react 3.4.10
  • @storybook/addon-knobs": "^3.4.10",

Affected platforms

Nop

Screenshots / Screencast / Code Snippets (Optional)

See above the code

screen shot 2018-09-02 at 11 27 14

Work summary

Not sure, but maybe allow any value from the select as we could use and need an Object or array list as a value.

Where to start

heu?

Acceptance criteria

Allow any type for the select value

Who to contact

No idea

[Request] Undeprecate knobs.

Looks like the addon still works fine in version 7 and it's still a better offering than controls. Why don't you undeprecate it and start accepting incoming PRs again?

[addon-knobs]: options knob with display: multi-select inferring wrong type info

Just copied from this very nice detailed explanation in storybookjs/storybook#10692

Until storybookjs/storybook#12561 is resolved, a fix for the type error should be added to v5 🙏


Describe the bug
When using the options knob with {display: multi-select}, it is inferring the return type from the values of the valuesObj, which need to be strings in order for the multi-select to work. The return type is being inferred as string when the multi-select actually returns an array of strings, so string[].

To Reproduce
Steps to reproduce the behavior:

  1. Create a optionsKnob with the display set to multi-select
  2. pass in a values object with the labels and values you expect to see in the dropdown.
  3. pass in a default value, an array of the values you expect to be auto-selected.
  4. check the return value that optionsKnob returns

Expected behavior
Given that the optionsKnob returns an array of strings when it is being used as a multi-select, it should return the correct type information: string[]

Screenshots
The implementation:
Screen Shot 2020-05-08 at 11 46 18 AM

The resulting console log of what options is returning:
Screen Shot 2020-05-08 at 11 58 25 AM

The type error:
Screen Shot 2020-05-08 at 11 47 03 AM

The knob used in the UI is correct:
Screen Shot 2020-05-08 at 12 05 21 PM

Code snippets

      const valueOptions = {
        facebook: "facebook",
        twitter: "twitter",
        email: "email",
        link: "link"
      };
      const defaultNetworks: string[] = [
        "facebook",
        "twitter",
        "email",
        "link"
      ];

      const networks: string[] = options( //should return an array of strings
        "Networks",
        valueOptions,
        defaultNetworks,
        {
          display: "multi-select"
        }
      );

System:

  System:
    OS: macOS 10.15.4
    CPU: (8) x64 Intel(R) Core(TM) i7-8559U CPU @ 2.70GHz
  Binaries:
    Node: 10.16.3 - /usr/local/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm
  Browsers:
    Chrome: 81.0.4044.138
    Safari: 13.1
  npmPackages:
    @storybook/addon-actions: 5.3.10 => 5.3.10 
    @storybook/addon-docs: 5.3.10 => 5.3.10 
    @storybook/addon-info: 5.3.10 => 5.3.10 
    @storybook/addon-knobs: 5.3.10 => 5.3.10 
    @storybook/addon-links: 5.3.10 => 5.3.10 
    @storybook/addon-options: 5.3.10 => 5.3.10 
    @storybook/addon-storysource: ^5.3.13 => 5.3.18 
    @storybook/addons: 5.3.10 => 5.3.10 
    @storybook/react: 5.3.10 => 5.3.10 

[addon-knobs] Seeing knobs from previously selected story

Describe the bug
When I select the first story after starting storybook, I see its knobs just fine. Then when I select another story, its knobs are added to the knobs that were there from the previously selected knobs.

Worse even, if the previously selected story had knobs in categories (tabs), the non-categorized knobs from the newly selected story are now tucked away in a "Other" tab.

To Reproduce
Upgrading/migrating from storybook 5.3 to 6.0, I suppose. That's the only thing that happened that made this break. I am already using the knobs preset in main.js, rather than its "register" notation in addons.js. And of course, everything is at the same 6.0.28 version.

Expected behavior
Knobs panel should only ever display knobs from the currently selected story.

Screenshots
image
1 - These are from the previously selected story and do not belong here. They never go away, even after having selected a docs-only story where the side panel goes away entirely.
2 - This is from the currently selected story, and should not be a tab. The currently selected does not have its knobs in categories, so I expect no tabs at all.

Code snippets
Relevant part of main.js:

module.exports = {
  stories: ['../../src/**/*.stories.@(jsx|mdx)'],
  addons: [
    '@storybook/addon-options',
    '@storybook/addon-knobs',
    '@storybook/addon-a11y',
    '@storybook/addon-docs',
  ]
};

Relevant part of manager.js:

import { addons } from '@storybook/addons';

// Option defaults:
addons.setConfig({
  name: 'Mijn Enexis',
  showNav: true,
  showPanel: true,
  panelPosition: 'right',
});

I don't know what else. There's no reference to knobs in preview.jsx, nor in theme.js.

System
Results of npx sb@next info:

  System:
    OS: Windows 10 10.0.19041
    CPU: (12) x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
  Binaries:
    Node: 12.19.0 - C:\Program Files\nodejs\node.EXE
    npm: 6.14.8 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 86.0.4240.183
    Edge: Spartan (44.19041.423.0)
  npmPackages:
    @storybook/addon-a11y: 6.0.28 => 6.0.28
    @storybook/addon-actions: 6.0.28 => 6.0.28
    @storybook/addon-docs: 6.0.28 => 6.0.28
    @storybook/addon-knobs: 6.0.28 => 6.0.28
    @storybook/react: 6.0.28 => 6.0.28
    @storybook/theming: 6.0.28 => 6.0.28

It doesn't see my actual browser, Firefox 82.

[addon-knobs] Add onChange callback in options

I need to be able to trigger a function on every value changed in knobs.

Here is my use case :

storiesOf('SomeComponent', module)
  .addDecorator(getStory => {
    const story = getStory()
    const themeSelector = select(
      'Theme',
      Object.keys(themes),
      'defaultTheme',
      null,
      { onChange: knob => { themes[knob.value].injectGlobal() } }
    )
    return (
      <ThemeProvider theme={themes[themeSelector]}>
        {story}
      </ThemeProvider>
    )
  })
  .addDecorator(withKnobs)
  • @storybook/react 3.4.8
  • @storybook/addon-something 3.4.8

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.