-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathSpeedDial.js
585 lines (535 loc) · 16 KB
/
SpeedDial.js
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
'use client';
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import composeClasses from '@mui/utils/composeClasses';
import useTimeout from '@mui/utils/useTimeout';
import clamp from '@mui/utils/clamp';
import { styled, useTheme } from '../zero-styled';
import memoTheme from '../utils/memoTheme';
import { useDefaultProps } from '../DefaultPropsProvider';
import Zoom from '../Zoom';
import Fab from '../Fab';
import capitalize from '../utils/capitalize';
import isMuiElement from '../utils/isMuiElement';
import useForkRef from '../utils/useForkRef';
import useControlled from '../utils/useControlled';
import speedDialClasses, { getSpeedDialUtilityClass } from './speedDialClasses';
import useSlot from '../utils/useSlot';
const useUtilityClasses = (ownerState) => {
const { classes, open, direction } = ownerState;
const slots = {
root: ['root', `direction${capitalize(direction)}`],
fab: ['fab'],
actions: ['actions', !open && 'actionsClosed'],
};
return composeClasses(slots, getSpeedDialUtilityClass, classes);
};
function getOrientation(direction) {
if (direction === 'up' || direction === 'down') {
return 'vertical';
}
if (direction === 'right' || direction === 'left') {
return 'horizontal';
}
return undefined;
}
const dialRadius = 32;
const spacingActions = 16;
const SpeedDialRoot = styled('div', {
name: 'MuiSpeedDial',
slot: 'Root',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [styles.root, styles[`direction${capitalize(ownerState.direction)}`]];
},
})(
memoTheme(({ theme }) => ({
zIndex: (theme.vars || theme).zIndex.speedDial,
display: 'flex',
alignItems: 'center',
pointerEvents: 'none',
variants: [
{
props: {
direction: 'up',
},
style: {
flexDirection: 'column-reverse',
[`& .${speedDialClasses.actions}`]: {
flexDirection: 'column-reverse',
marginBottom: -dialRadius,
paddingBottom: spacingActions + dialRadius,
},
},
},
{
props: {
direction: 'down',
},
style: {
flexDirection: 'column',
[`& .${speedDialClasses.actions}`]: {
flexDirection: 'column',
marginTop: -dialRadius,
paddingTop: spacingActions + dialRadius,
},
},
},
{
props: {
direction: 'left',
},
style: {
flexDirection: 'row-reverse',
[`& .${speedDialClasses.actions}`]: {
flexDirection: 'row-reverse',
marginRight: -dialRadius,
paddingRight: spacingActions + dialRadius,
},
},
},
{
props: {
direction: 'right',
},
style: {
flexDirection: 'row',
[`& .${speedDialClasses.actions}`]: {
flexDirection: 'row',
marginLeft: -dialRadius,
paddingLeft: spacingActions + dialRadius,
},
},
},
],
})),
);
const SpeedDialFab = styled(Fab, {
name: 'MuiSpeedDial',
slot: 'Fab',
overridesResolver: (props, styles) => styles.fab,
})({
pointerEvents: 'auto',
});
const SpeedDialActions = styled('div', {
name: 'MuiSpeedDial',
slot: 'Actions',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [styles.actions, !ownerState.open && styles.actionsClosed];
},
})({
display: 'flex',
pointerEvents: 'auto',
variants: [
{
props: ({ ownerState }) => !ownerState.open,
style: {
transition: 'top 0s linear 0.2s',
pointerEvents: 'none',
},
},
],
});
const SpeedDial = React.forwardRef(function SpeedDial(inProps, ref) {
const props = useDefaultProps({ props: inProps, name: 'MuiSpeedDial' });
const theme = useTheme();
const defaultTransitionDuration = {
enter: theme.transitions.duration.enteringScreen,
exit: theme.transitions.duration.leavingScreen,
};
const {
ariaLabel,
FabProps: { ref: origDialButtonRef, ...FabProps } = {},
children: childrenProp,
className,
direction = 'up',
hidden = false,
icon,
onBlur,
onClose,
onFocus,
onKeyDown,
onMouseEnter,
onMouseLeave,
onOpen,
open: openProp,
openIcon,
slots = {},
slotProps = {},
TransitionComponent: TransitionComponentProp,
TransitionProps: TransitionPropsProp,
transitionDuration = defaultTransitionDuration,
...other
} = props;
const [open, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: 'SpeedDial',
state: 'open',
});
const ownerState = { ...props, open, direction };
const classes = useUtilityClasses(ownerState);
const eventTimer = useTimeout();
/**
* an index in actions.current
*/
const focusedAction = React.useRef(0);
/**
* pressing this key while the focus is on a child SpeedDialAction focuses
* the next SpeedDialAction.
* It is equal to the first arrow key pressed while focus is on the SpeedDial
* that is not orthogonal to the direction.
* @type {utils.ArrowKey?}
*/
const nextItemArrowKey = React.useRef();
/**
* refs to the Button that have an action associated to them in this SpeedDial
* [Fab, ...(SpeedDialActions > Button)]
* @type {HTMLButtonElement[]}
*/
const actions = React.useRef([]);
actions.current = [actions.current[0]];
const handleOwnFabRef = React.useCallback((fabFef) => {
actions.current[0] = fabFef;
}, []);
const handleFabRef = useForkRef(origDialButtonRef, handleOwnFabRef);
/**
* creates a ref callback for the Button in a SpeedDialAction
* Is called before the original ref callback for Button that was set in buttonProps
*
* @param dialActionIndex {number}
* @param origButtonRef {React.RefObject?}
*/
const createHandleSpeedDialActionButtonRef = (dialActionIndex, origButtonRef) => {
return (buttonRef) => {
actions.current[dialActionIndex + 1] = buttonRef;
if (origButtonRef) {
origButtonRef(buttonRef);
}
};
};
const handleKeyDown = (event) => {
if (onKeyDown) {
onKeyDown(event);
}
const key = event.key.replace('Arrow', '').toLowerCase();
const { current: nextItemArrowKeyCurrent = key } = nextItemArrowKey;
if (event.key === 'Escape') {
setOpenState(false);
actions.current[0].focus();
if (onClose) {
onClose(event, 'escapeKeyDown');
}
return;
}
if (
getOrientation(key) === getOrientation(nextItemArrowKeyCurrent) &&
getOrientation(key) !== undefined
) {
event.preventDefault();
const actionStep = key === nextItemArrowKeyCurrent ? 1 : -1;
// stay within array indices
const nextAction = clamp(focusedAction.current + actionStep, 0, actions.current.length - 1);
actions.current[nextAction].focus();
focusedAction.current = nextAction;
nextItemArrowKey.current = nextItemArrowKeyCurrent;
}
};
React.useEffect(() => {
// actions were closed while navigation state was not reset
if (!open) {
focusedAction.current = 0;
nextItemArrowKey.current = undefined;
}
}, [open]);
const handleClose = (event) => {
if (event.type === 'mouseleave' && onMouseLeave) {
onMouseLeave(event);
}
if (event.type === 'blur' && onBlur) {
onBlur(event);
}
eventTimer.clear();
if (event.type === 'blur') {
eventTimer.start(0, () => {
setOpenState(false);
if (onClose) {
onClose(event, 'blur');
}
});
} else {
setOpenState(false);
if (onClose) {
onClose(event, 'mouseLeave');
}
}
};
const handleClick = (event) => {
if (FabProps.onClick) {
FabProps.onClick(event);
}
eventTimer.clear();
if (open) {
setOpenState(false);
if (onClose) {
onClose(event, 'toggle');
}
} else {
setOpenState(true);
if (onOpen) {
onOpen(event, 'toggle');
}
}
};
const handleOpen = (event) => {
if (event.type === 'mouseenter' && onMouseEnter) {
onMouseEnter(event);
}
if (event.type === 'focus' && onFocus) {
onFocus(event);
}
// When moving the focus between two items,
// a chain if blur and focus event is triggered.
// We only handle the last event.
eventTimer.clear();
if (!open) {
// Wait for a future focus or click event
eventTimer.start(0, () => {
setOpenState(true);
if (onOpen) {
const eventMap = {
focus: 'focus',
mouseenter: 'mouseEnter',
};
onOpen(event, eventMap[event.type]);
}
});
}
};
// Filter the label for valid id characters.
const id = ariaLabel.replace(/^[^a-z]+|[^\w:.-]+/gi, '');
const allItems = React.Children.toArray(childrenProp).filter((child) => {
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(
[
"MUI: The SpeedDial component doesn't accept a Fragment as a child.",
'Consider providing an array instead.',
].join('\n'),
);
}
}
return React.isValidElement(child);
});
const children = allItems.map((child, index) => {
const {
FabProps: { ref: origButtonRef, ...ChildFabProps } = {},
tooltipPlacement: tooltipPlacementProp,
} = child.props;
const tooltipPlacement =
tooltipPlacementProp || (getOrientation(direction) === 'vertical' ? 'left' : 'top');
return React.cloneElement(child, {
FabProps: {
...ChildFabProps,
ref: createHandleSpeedDialActionButtonRef(index, origButtonRef),
},
delay: 30 * (open ? index : allItems.length - index),
open,
tooltipPlacement,
id: `${id}-action-${index}`,
});
});
const backwardCompatibleSlots = { transition: TransitionComponentProp, ...slots };
const backwardCompatibleSlotProps = { transition: TransitionPropsProp, ...slotProps };
const externalForwardedProps = {
slots: backwardCompatibleSlots,
slotProps: backwardCompatibleSlotProps,
};
const [TransitionSlot, transitionProps] = useSlot('transition', {
elementType: Zoom,
externalForwardedProps,
ownerState,
});
return (
<SpeedDialRoot
className={clsx(classes.root, className)}
ref={ref}
role="presentation"
onKeyDown={handleKeyDown}
onBlur={handleClose}
onFocus={handleOpen}
onMouseEnter={handleOpen}
onMouseLeave={handleClose}
ownerState={ownerState}
{...other}
>
<TransitionSlot in={!hidden} timeout={transitionDuration} unmountOnExit {...transitionProps}>
<SpeedDialFab
color="primary"
aria-label={ariaLabel}
aria-haspopup="true"
aria-expanded={open}
aria-controls={`${id}-actions`}
{...FabProps}
onClick={handleClick}
className={clsx(classes.fab, FabProps.className)}
ref={handleFabRef}
ownerState={ownerState}
>
{React.isValidElement(icon) && isMuiElement(icon, ['SpeedDialIcon'])
? React.cloneElement(icon, { open })
: icon}
</SpeedDialFab>
</TransitionSlot>
<SpeedDialActions
id={`${id}-actions`}
role="menu"
aria-orientation={getOrientation(direction)}
className={clsx(classes.actions, { [classes.actionsClosed]: !open })}
ownerState={ownerState}
>
{children}
</SpeedDialActions>
</SpeedDialRoot>
);
});
SpeedDial.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the d.ts file and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* The aria-label of the button element.
* Also used to provide the `id` for the `SpeedDial` element and its children.
*/
ariaLabel: PropTypes.string.isRequired,
/**
* SpeedDialActions to display when the SpeedDial is `open`.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The direction the actions open relative to the floating action button.
* @default 'up'
*/
direction: PropTypes.oneOf(['down', 'left', 'right', 'up']),
/**
* Props applied to the [`Fab`](https://mui.com/material-ui/api/fab/) element.
* @default {}
*/
FabProps: PropTypes.object,
/**
* If `true`, the SpeedDial is hidden.
* @default false
*/
hidden: PropTypes.bool,
/**
* The icon to display in the SpeedDial Fab. The `SpeedDialIcon` component
* provides a default Icon with animation.
*/
icon: PropTypes.node,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"toggle"`, `"blur"`, `"mouseLeave"`, `"escapeKeyDown"`.
*/
onClose: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* @ignore
*/
onMouseEnter: PropTypes.func,
/**
* @ignore
*/
onMouseLeave: PropTypes.func,
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"toggle"`, `"focus"`, `"mouseEnter"`.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* The icon to display in the SpeedDial Fab when the SpeedDial is open.
*/
openIcon: PropTypes.node,
/**
* The props used for each slot inside.
* @default {}
*/
slotProps: PropTypes.shape({
transition: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside.
* @default {}
*/
slots: PropTypes.shape({
transition: PropTypes.elementType,
}),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* The component used for the transition.
* [Follow this guide](https://mui.com/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Zoom
* * @deprecated Use `slots.transition` instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/)
*/
TransitionComponent: PropTypes.elementType,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default {
* enter: theme.transitions.duration.enteringScreen,
* exit: theme.transitions.duration.leavingScreen,
* }
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
appear: PropTypes.number,
enter: PropTypes.number,
exit: PropTypes.number,
}),
]),
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](https://reactcommunity.org/react-transition-group/transition/) component.
* @deprecated Use `slotProps.transition` instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/)
*/
TransitionProps: PropTypes.object,
};
export default SpeedDial;