Monday, January 25, 2021

custom sorting sections in storybook

Aargh, one of those silly "didn't read far enough in the documentation" -- Storybook DOES easily cover 2 levels of hierarchy, so you can have your main Documentation before your per-Component documentation, and then sorted Documentation sections (but if you need finer grained control than that, you're going to have to work harder.)

Assuming you already have a `export const parameters` object, just add this:

  options: {
    storySort: {
      order: ['Documentation', 
               ['Overview','Design System Workflow'], 
             'Components'],    
    },
  },

But before I read low enough on the page to see the previous example, I had the "roll your own sort function" on my mind., even for the simpler sort one level of sections version. This was the code I came up with... I kind of like sorting one array by the contents of another:

const knownSectionsForSorting = ['Documentation', 'Components'];

const positionOfContainingSection = (titlePath: string) => {
  const section = titlePath.substring(0, titlePath.indexOf('/'));
  return knownSectionsForSorting.indexOf(section);
};

export const parameters = {
  options: {
    storySort: (a, b) => {
      // story titles are the "kind" parameter of the second item of the info array
      const diffInSection =
        positionOfContainingSection(a[1].kind) -
        positionOfContainingSection(b[1].kind);
      return diffInSection || a[1].kind.localeCompare(b[1].kind);
    },
  },
};

You'd have to build something like that but more advanced if you need to sort individual files with a subsection of your Documentation section, for example.

And the documentation for doing that is a little light... odd that you have to look at "a[1].kind" to find the Title to sort on...

No comments:

Post a Comment