Skip to content

Commit

Permalink
Merge pull request #12980 from teimurjan/teimurjan/add-stories-expand…
Browse files Browse the repository at this point in the history
…-collapse

UI: Add support for expand/collapse keyboard shortcuts
  • Loading branch information
shilman committed Dec 1, 2020
2 parents a5e0031 + 4fca569 commit 94052ae
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/ui/src/components/sidebar/useExpanded.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -47,6 +48,8 @@ const initializeExpanded = ({
);
};

const noop = () => {};

export const useExpanded = ({
containerRef,
isBrowsing,
Expand All @@ -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<
Expand Down Expand Up @@ -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');
Expand Down

0 comments on commit 94052ae

Please sign in to comment.