Skip to content

Instantly share code, notes, and snippets.

@JohnAlbin
Last active May 6, 2022 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnAlbin/83ef5282d07c6aa447ff39719429843e to your computer and use it in GitHub Desktop.
Save JohnAlbin/83ef5282d07c6aa447ff39719429843e to your computer and use it in GitHub Desktop.
Storybook navigation sorting
// .storybook/config.js
import { addParameters, configure } from '@storybook/react';
import { storySort } from 'storybook-sort';
addParameters({
options: {
showRoots: true,
storySort: storySort({ order: ['Home', 'Pages', ['Projects', 'Community', 'Help'], 'Components']}),
},
});
// ... rest of config.js
export const storySort = options => (a, b) => {
// Debug.
// console.log({a, b});
// If the two stories have the same story kind, then use the default
// ordering, which is the order they are defined in the story file.
if (a[1].kind === b[1].kind) {
return 0;
}
const storyKindA = a[1].kind.split('/');
const storyKindB = b[1].kind.split('/');
let depth = 0;
let nameA, nameB, indexA, indexB, index;
let ordering = options.order || [];
while (true) {
nameA = storyKindA[depth] ? storyKindA[depth] : '';
nameB = storyKindB[depth] ? storyKindB[depth] : '';
if (nameA === nameB) {
// If a nested array is provided for a name, use it for ordering.
index = ordering.indexOf(nameA);
if (index !== -1 && Array.isArray(ordering[index + 1])) {
ordering = ordering[index + 1];
}
// We'll need to look at the next part of the name.
depth++;
continue;
}
else {
// Look for the names in the given `ordering` array.
indexA = ordering.indexOf(nameA);
indexB = ordering.indexOf(nameB);
// If at least one of the names is found, sort by the `ordering` array.
if (indexA !== -1 || indexB !== -1) {
// If one of the names is not found in `ordering`, list it last.
if (indexA === -1) {
indexA = ordering.length;
}
if (indexB === -1) {
indexB = ordering.length;
}
return indexA - indexB;
}
}
// Otherwise, use alphabetical order.
return nameA.localeCompare(nameB);
}
};
@vitorbertulucci
Copy link

That's a very nice solution, but I found in the docs that they already have something implemented to do that on the preview properties:
https://storybook.js.org/docs/react/writing-stories/naming-components-and-hierarchy#sorting-stories

@JohnAlbin
Copy link
Author

@vitorbertulucci Yep. I added that functionality (and its docs) to Storybook with this PR: storybookjs/storybook#9188

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment