/
hook.ts
317 lines (282 loc) · 8.35 KB
/
hook.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/**
* WordPress dependencies
*/
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from '@wordpress/element';
/**
* Internal dependencies
*/
import * as styles from '../styles';
import { useContextSystem, WordPressComponentProps } from '../../ui/context';
import { useCx } from '../../utils/hooks/use-cx';
import type {
ToolsPanelItem,
ToolsPanelMenuItemKey,
ToolsPanelMenuItems,
ToolsPanelMenuItemsConfig,
ToolsPanelProps,
} from '../types';
const DEFAULT_COLUMNS = 2;
const generateMenuItems = ( {
panelItems,
shouldReset,
currentMenuItems,
}: ToolsPanelMenuItemsConfig ) => {
const menuItems: ToolsPanelMenuItems = { default: {}, optional: {} };
panelItems.forEach( ( { hasValue, isShownByDefault, label } ) => {
const group = isShownByDefault ? 'default' : 'optional';
// If a menu item for this label already exists, do not overwrite its value.
// This can cause default controls that have been flagged as customized to
// lose their value.
const existingItemValue = currentMenuItems?.[ group ]?.[ label ];
const value =
existingItemValue !== undefined ? existingItemValue : hasValue();
menuItems[ group ][ label ] = shouldReset ? false : value;
} );
return menuItems;
};
const isMenuItemTypeEmpty = (
obj?: ToolsPanelMenuItems[ ToolsPanelMenuItemKey ]
) => obj && Object.keys( obj ).length === 0;
export function useToolsPanel(
props: WordPressComponentProps< ToolsPanelProps, 'div' >
) {
const {
className,
headingLevel = 2,
resetAll,
panelId,
hasInnerWrapper,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass,
...otherProps
} = useContextSystem( props, 'ToolsPanel' );
const isResetting = useRef( false );
const wasResetting = isResetting.current;
// `isResetting` is cleared via this hook to effectively batch together
// the resetAll task. Without this, the flag is cleared after the first
// control updates and forces a rerender with subsequent controls then
// believing they need to reset, unfortunately using stale data.
useEffect( () => {
if ( wasResetting ) {
isResetting.current = false;
}
}, [ wasResetting ] );
// Allow panel items to register themselves.
const [ panelItems, setPanelItems ] = useState< ToolsPanelItem[] >( [] );
const registerPanelItem = useCallback(
( item: ToolsPanelItem ) => {
setPanelItems( ( items ) => {
const newItems = [ ...items ];
// If an item with this label has already been registered, remove it
// first. This can happen when an item is moved between the default
// and optional groups.
const existingIndex = newItems.findIndex(
( oldItem ) => oldItem.label === item.label
);
if ( existingIndex !== -1 ) {
newItems.splice( existingIndex, 1 );
}
return [ ...newItems, item ];
} );
},
[ setPanelItems ]
);
// Panels need to deregister on unmount to avoid orphans in menu state.
// This is an issue when panel items are being injected via SlotFills.
const deregisterPanelItem = useCallback(
( label: string ) => {
// When switching selections between components injecting matching
// controls, e.g. both panels have a "padding" control, the
// deregistration of the first panel doesn't occur until after the
// registration of the next.
setPanelItems( ( items ) => {
const newItems = [ ...items ];
const index = newItems.findIndex(
( item ) => item.label === label
);
if ( index !== -1 ) {
newItems.splice( index, 1 );
}
return newItems;
} );
},
[ setPanelItems ]
);
// Manage and share display state of menu items representing child controls.
const [ menuItems, setMenuItems ] = useState< ToolsPanelMenuItems >( {
default: {},
optional: {},
} );
// Setup menuItems state as panel items register themselves.
useEffect( () => {
setMenuItems( ( prevState ) => {
const items = generateMenuItems( {
panelItems,
shouldReset: false,
currentMenuItems: prevState,
} );
return items;
} );
}, [ panelItems, setMenuItems ] );
// Force a menu item to be checked.
// This is intended for use with default panel items. They are displayed
// separately to optional items and have different display states,
// we need to update that when their value is customized.
const flagItemCustomization = useCallback(
( label: string, group: ToolsPanelMenuItemKey = 'default' ) => {
setMenuItems( ( items ) => {
const newState = {
...items,
[ group ]: {
...items[ group ],
[ label ]: true,
},
};
return newState;
} );
},
[ setMenuItems ]
);
// Whether all optional menu items are hidden or not must be tracked
// in order to later determine if the panel display is empty and handle
// conditional display of a plus icon to indicate the presence of further
// menu items.
const [ areAllOptionalControlsHidden, setAreAllOptionalControlsHidden ] =
useState( false );
useEffect( () => {
if (
isMenuItemTypeEmpty( menuItems?.default ) &&
! isMenuItemTypeEmpty( menuItems?.optional )
) {
const allControlsHidden = ! Object.entries(
menuItems.optional
).some( ( [ , isSelected ] ) => isSelected );
setAreAllOptionalControlsHidden( allControlsHidden );
}
}, [ menuItems, setAreAllOptionalControlsHidden ] );
const cx = useCx();
const classes = useMemo( () => {
const wrapperStyle =
hasInnerWrapper &&
styles.ToolsPanelWithInnerWrapper( DEFAULT_COLUMNS );
const emptyStyle =
isMenuItemTypeEmpty( menuItems?.default ) &&
areAllOptionalControlsHidden &&
styles.ToolsPanelHiddenInnerWrapper;
return cx(
styles.ToolsPanel( DEFAULT_COLUMNS ),
wrapperStyle,
emptyStyle,
className
);
}, [
areAllOptionalControlsHidden,
className,
cx,
hasInnerWrapper,
menuItems,
] );
// Toggle the checked state of a menu item which is then used to determine
// display of the item within the panel.
const toggleItem = useCallback(
( label: string ) => {
const currentItem = panelItems.find(
( item ) => item.label === label
);
if ( ! currentItem ) {
return;
}
const menuGroup = currentItem.isShownByDefault
? 'default'
: 'optional';
const newMenuItems = {
...menuItems,
[ menuGroup ]: {
...menuItems[ menuGroup ],
[ label ]: ! menuItems[ menuGroup ][ label ],
},
};
setMenuItems( newMenuItems );
},
[ menuItems, panelItems, setMenuItems ]
);
// Resets display of children and executes resetAll callback if available.
const resetAllItems = useCallback( () => {
if ( typeof resetAll === 'function' ) {
isResetting.current = true;
// Collect available reset filters from panel items.
const filters: Array< () => void > = [];
panelItems.forEach( ( item ) => {
if ( item.resetAllFilter ) {
filters.push( item.resetAllFilter );
}
} );
resetAll( filters );
}
// Turn off display of all non-default items.
const resetMenuItems = generateMenuItems( {
panelItems,
shouldReset: true,
} );
setMenuItems( resetMenuItems );
}, [ panelItems, resetAll, setMenuItems ] );
// Assist ItemGroup styling when there are potentially hidden placeholder
// items by identifying first & last items that are toggled on for display.
const getFirstVisibleItemLabel = ( items: ToolsPanelItem[] ) => {
const optionalItems = menuItems.optional || {};
const firstItem = items.find(
( item ) => item.isShownByDefault || !! optionalItems[ item.label ]
);
return firstItem?.label;
};
const firstDisplayedItem = getFirstVisibleItemLabel( panelItems );
const lastDisplayedItem = getFirstVisibleItemLabel(
[ ...panelItems ].reverse()
);
const panelContext = useMemo(
() => ( {
areAllOptionalControlsHidden,
deregisterPanelItem,
firstDisplayedItem,
flagItemCustomization,
hasMenuItems: !! panelItems.length,
isResetting: isResetting.current,
lastDisplayedItem,
menuItems,
panelId,
registerPanelItem,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass,
} ),
[
areAllOptionalControlsHidden,
deregisterPanelItem,
firstDisplayedItem,
flagItemCustomization,
lastDisplayedItem,
menuItems,
panelId,
panelItems,
registerPanelItem,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass,
]
);
return {
...otherProps,
headingLevel,
panelContext,
resetAllItems,
toggleItem,
className: classes,
};
}