-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
useExpanded.ts
220 lines (189 loc) · 7.09 KB
/
useExpanded.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import type { StoriesHash } from '@storybook/api';
import { 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';
import { matchesKeyCode, matchesModifiers } from '../../keybinding';
import { Highlight } from './types';
import { isAncestor, getAncestorIds, getDescendantIds, scrollIntoView } from './utils';
export type ExpandedState = Record<string, boolean>;
export interface ExpandAction {
ids: string[];
value: boolean;
}
export interface ExpandedProps {
containerRef: MutableRefObject<HTMLElement>;
isBrowsing: boolean;
refId: string;
data: StoriesHash;
initialExpanded?: ExpandedState;
rootIds: string[];
highlightedRef: MutableRefObject<Highlight>;
setHighlightedItemId: (storyId: string) => void;
selectedStoryId: string | null;
onSelectStoryId: (storyId: string) => void;
}
const initializeExpanded = ({
refId,
data,
initialExpanded,
highlightedRef,
rootIds,
}: {
refId: string;
data: StoriesHash;
initialExpanded?: ExpandedState;
highlightedRef: MutableRefObject<Highlight>;
rootIds: string[];
}) => {
const highlightedAncestors =
highlightedRef.current?.refId === refId
? getAncestorIds(data, highlightedRef.current?.itemId)
: [];
return [...rootIds, ...highlightedAncestors].reduce<ExpandedState>(
(acc, id) => Object.assign(acc, { [id]: id in initialExpanded ? initialExpanded[id] : true }),
{}
);
};
const noop = () => {};
export const useExpanded = ({
containerRef,
isBrowsing,
refId,
data,
initialExpanded,
rootIds,
highlightedRef,
setHighlightedItemId,
selectedStoryId,
onSelectStoryId,
}: ExpandedProps): [ExpandedState, Dispatch<ExpandAction>] => {
const api = useStorybookApi();
// Track the set of currently expanded nodes within this tree.
// Root nodes are expanded by default.
const [expanded, setExpanded] = useReducer<
React.Reducer<ExpandedState, ExpandAction>,
{
refId: string;
data: StoriesHash;
highlightedRef: MutableRefObject<Highlight>;
rootIds: string[];
initialExpanded: ExpandedState;
}
>(
(state, { ids, value }) =>
ids.reduce((acc, id) => Object.assign(acc, { [id]: value }), { ...state }),
{ refId, data, highlightedRef, rootIds, initialExpanded },
initializeExpanded
);
const getElementByDataItemId = useCallback(
(id: string) => containerRef.current?.querySelector(`[data-item-id="${id}"]`),
[containerRef]
);
const highlightElement = useCallback(
(element: Element) => {
setHighlightedItemId(element.getAttribute('data-item-id'));
scrollIntoView(element);
},
[setHighlightedItemId]
);
const updateExpanded = useCallback(
({ ids, value }) => {
setExpanded({ ids, value });
if (ids.length === 1) {
const element = containerRef.current?.querySelector(
`[data-item-id="${ids[0]}"][data-ref-id="${refId}"]`
);
if (element) highlightElement(element);
}
},
[containerRef, highlightElement, refId]
);
// Expand the whole ancestry of the currently selected story whenever it changes.
useEffect(() => {
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');
// Even though we ignore repeated events, use throttle because IE doesn't support event.repeat.
const navigateTree = throttle((event: KeyboardEvent) => {
const highlightedItemId =
highlightedRef.current?.refId === refId && highlightedRef.current?.itemId;
if (!isBrowsing || !containerRef.current || !highlightedItemId || event.repeat) return;
if (!matchesModifiers(false, event)) return;
const isEnter = matchesKeyCode('Enter', event);
const isSpace = matchesKeyCode('Space', event);
const isArrowLeft = matchesKeyCode('ArrowLeft', event);
const isArrowRight = matchesKeyCode('ArrowRight', event);
if (!(isEnter || isSpace || isArrowLeft || isArrowRight)) return;
const highlightedElement = getElementByDataItemId(highlightedItemId);
if (!highlightedElement || highlightedElement.getAttribute('data-ref-id') !== refId) return;
const target = event.target as Element;
if (!isAncestor(menuElement, target) && !isAncestor(target, menuElement)) return;
if (target.hasAttribute('data-action')) {
if (isEnter || isSpace) return;
(target as HTMLButtonElement).blur();
}
event.preventDefault();
const type = highlightedElement.getAttribute('data-nodetype');
if ((isEnter || isSpace) && ['component', 'story', 'document'].includes(type)) {
onSelectStoryId(highlightedItemId);
}
const isExpanded = highlightedElement.getAttribute('aria-expanded');
if (isArrowLeft) {
if (isExpanded === 'true') {
// The highlighted node is expanded, so we collapse it.
setExpanded({ ids: [highlightedItemId], value: false });
return;
}
const parentId = highlightedElement.getAttribute('data-parent-id');
const parentElement = parentId && getElementByDataItemId(parentId);
if (parentElement && parentElement.getAttribute('data-highlightable') === 'true') {
// The highlighted node isn't expanded, so we move the highlight to its parent instead.
highlightElement(parentElement);
return;
}
// The parent can't be highlighted, which means it must be a root.
// The highlighted node is already collapsed, so we collapse its descendants.
setExpanded({ ids: getDescendantIds(data, highlightedItemId, true), value: false });
return;
}
if (isArrowRight) {
if (isExpanded === 'false') {
updateExpanded({ ids: [highlightedItemId], value: true });
} else if (isExpanded === 'true') {
updateExpanded({ ids: getDescendantIds(data, highlightedItemId, true), value: true });
}
}
}, 60);
document.addEventListener('keydown', navigateTree);
return () => document.removeEventListener('keydown', navigateTree);
}, [
containerRef,
isBrowsing,
refId,
data,
highlightedRef,
setHighlightedItemId,
onSelectStoryId,
]);
return [expanded, updateExpanded];
};