Storybook排序:能否为嵌套故事强制指定自定义展示顺序?
可以实现,通过扩展Storybook的storySort配置即可满足需求,有两种常用实现方案:
方案1:嵌套排序规则(推荐,无需自定义逻辑)
Storybook的order配置支持嵌套数组指定子层级的排序顺序,你可以直接修改原有配置如下:
options: { storySort: { method: 'alphabetical', order: [ 'Introduction', 'Styleguide', // 配置Atoms分组下的排序规则 ['Atoms', // * 匹配分组下所有组件,保持原有字母序 ['*', // 每个组件下优先排README,再排Examples ['README', 'Examples'] ] ], // Molecules分组排序规则同Atoms ['Molecules', ['*', ['README', 'Examples'] ] ], // Organisms分组排序规则同Atoms ['Organisms', ['*', ['README', 'Examples'] ] ], ], locales: 'en-US', } },
以上配置的生效逻辑:
- 顶层目录保持原有排序优先级:Introduction > Styleguide > Atoms > Molecules > Organisms
- 三个组件分组下的所有组件保持原有字母序不变
- 每个组件目录下强制将README排在最前,Examples紧随其后,其余未指定的项仍按字母序排列
方案2:自定义排序函数(适合更复杂的排序场景)
如果后续还有其他自定义排序需求,可以直接将storySort设置为排序函数,完全自主控制排序逻辑,示例如下:
options: { storySort: (a, b) => { // 先处理顶层分组的排序 const topLevelOrder = ['Introduction', 'Styleguide', 'Atoms', 'Molecules', 'Organisms']; const aTopLevel = a.title.split('/')[0]; const bTopLevel = b.title.split('/')[0]; const aTopIndex = topLevelOrder.indexOf(aTopLevel); const bTopIndex = topLevelOrder.indexOf(bTopLevel); if (aTopIndex !== bTopIndex) return aTopIndex - bTopIndex; // 同一组件下的内容优先展示README const aPath = a.title.split('/'); const bPath = b.title.split('/'); if (aPath.length === bPath.length && aPath.slice(0, -1).join('/') === bPath.slice(0, -1).join('/')) { const aLast = aPath.at(-1); const bLast = bPath.at(-1); if (aLast === 'README') return -1; if (bLast === 'README') return 1; if (aLast === 'Examples') return -1; if (bLast === 'Examples') return 1; } // 其余场景默认按字母序排序 return a.title.localeCompare(b.title, 'en-US'); } },
内容的提问来源于stack exchange,提问作者Brandon Durham
相关产品推荐
相关产品推荐

