mirror of
https://github.com/storybookjs/storybook.git
synced 2025-03-16 05:03:11 +08:00
Merge pull request #12980 from teimurjan/teimurjan/add-stories-expand-collapse
UI: Add support for expand/collapse keyboard shortcuts
This commit is contained in:
commit
94052ae175
@ -1,4 +1,5 @@
|
||||
import { StoriesHash } from '@storybook/api';
|
||||
import { StoriesHash, useStorybookApi } from '@storybook/api';
|
||||
import { STORIES_COLLAPSE_ALL, STORIES_EXPAND_ALL } from '@storybook/core-events';
|
||||
import { document } from 'global';
|
||||
import throttle from 'lodash/throttle';
|
||||
import React, { Dispatch, MutableRefObject, useCallback, useEffect, useReducer } from 'react';
|
||||
@ -47,6 +48,8 @@ const initializeExpanded = ({
|
||||
);
|
||||
};
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
export const useExpanded = ({
|
||||
containerRef,
|
||||
isBrowsing,
|
||||
@ -58,6 +61,8 @@ export const useExpanded = ({
|
||||
selectedStoryId,
|
||||
onSelectStoryId,
|
||||
}: ExpandedProps): [Record<string, boolean>, Dispatch<ExpandAction>] => {
|
||||
const api = useStorybookApi();
|
||||
|
||||
// Track the set of currently expanded nodes within this tree.
|
||||
// Root nodes are expanded by default (and cannot be collapsed).
|
||||
const [expanded, setExpanded] = useReducer<
|
||||
@ -107,6 +112,27 @@ export const useExpanded = ({
|
||||
setExpanded({ ids: getAncestorIds(data, selectedStoryId), value: true });
|
||||
}, [data, selectedStoryId]);
|
||||
|
||||
const collapseAll = useCallback(() => {
|
||||
const ids = Object.keys(data).filter(id => !rootIds.includes(id));
|
||||
setExpanded({ ids, value: false });
|
||||
}, [data, rootIds]);
|
||||
|
||||
const expandAll = useCallback(() => {
|
||||
setExpanded({ ids: Object.keys(data), value: true });
|
||||
}, [data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return noop;
|
||||
|
||||
api.on(STORIES_COLLAPSE_ALL, collapseAll);
|
||||
api.on(STORIES_EXPAND_ALL, expandAll);
|
||||
|
||||
return () => {
|
||||
api.off(STORIES_COLLAPSE_ALL, collapseAll);
|
||||
api.off(STORIES_EXPAND_ALL, expandAll);
|
||||
};
|
||||
}, [api, collapseAll, expandAll]);
|
||||
|
||||
// Expand, collapse or select nodes in the tree using keyboard shortcuts.
|
||||
useEffect(() => {
|
||||
const menuElement = document.getElementById('storybook-explorer-menu');
|
||||
|
Loading…
x
Reference in New Issue
Block a user