Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI: Add support for expand/collapse keyboard shortcuts #12980

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -46,6 +47,8 @@ const initializeExpanded = ({
);
};

const noop = () => {};

export const useExpanded = ({
containerRef,
isBrowsing,
Expand All @@ -57,6 +60,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 @@ -106,6 +111,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