Search code examples
sortingstorybook

Sort storybook stories by category and component


I'm looking for a sorting function for the ./storybook/preview.ts file, that would sort the categories and the component alphabetically (on the right side nav panel).

On version 6 I've used this function / hack which seemed to work:

    //preview.ts

    export const parameters = {
      ...
      storySort: (a, b) => {
        const sortFiles = (a, b) => {
          const letters = (fileName) => fileName.replace(/\.\/\\/g, "");
          return letters(a).localeCompare(letters(b));
        };
        if (a[2].fileName) {
          return sortFiles(a[2].fileName, b[2].fileName);
        }
        return a[1].kind === b[1].kind
          ? 0
          : a[1].id.localeCompare(b[1].id, undefined, { numeric: true });
      }
      ...
    }

but now in version 7 the api was changed and I'm lost again...

The version 6 was installed on Angular and this version 7 is installed on React. I don't think it matters but I'm pointing it anyway.

Any idea how to achieve the same result on version 7?


Solution

  • It shows how to sort alphabetically in the documentation, and works for me with storybook 7:

    https://storybook.js.org/docs/react/writing-stories/naming-components-and-hierarchy#sorting-stories

    // .storybook/preview.ts
    
    // Replace your-framework with the framework you are using (e.g., react, vue3)
    import { Preview } from '@storybook/your-framework';
    
    const preview: Preview = {
      parameters: {
        options: {
          storySort: (a, b) =>
            a.id === b.id ? 0 : a.id.localeCompare(b.id, undefined, { numeric: true }),
        },
      },
    };
    
    export default preview;