/
Spotlight.tsx
296 lines (256 loc) · 8.5 KB
/
Spotlight.tsx
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
import React, { useState } from 'react';
import {
OptionalPortal,
GroupedTransition,
MantineTransition,
Overlay,
Paper,
DefaultProps,
Selectors,
MantineShadow,
TextInput,
getDefaultZIndex,
MantineNumberSize,
MantineColor,
TextInputProps,
} from '@mantine/core';
import { getGroupedOptions } from '@mantine/utils';
import { useScrollLock, useFocusTrap, useDidUpdate, useFocusReturn } from '@mantine/hooks';
import { DefaultAction, DefaultActionProps } from '../DefaultAction/DefaultAction';
import { ActionsList, ActionsListStylesNames } from '../ActionsList/ActionsList';
import type { SpotlightAction } from '../types';
import { filterActions } from './filter-actions/filter-actions';
import useStyles from './Spotlight.styles';
export type SpotlightStylesNames = Selectors<typeof useStyles> | ActionsListStylesNames;
export interface InnerSpotlightProps
extends DefaultProps<SpotlightStylesNames>,
React.ComponentPropsWithoutRef<'div'> {
/** Should spotlight be rendered within Portal */
withinPortal?: boolean;
/** Premade transition or transition object */
transition?: MantineTransition;
/** Transition duration in ms, set to 0 to disable all transitions */
transitionDuration?: number;
/** Backdrop overlay color, e.g. #000 */
overlayColor?: string;
/** Backdrop overlay opacity (0-1), e.g. 0.65 */
overlayOpacity?: number;
/** Backdrop overlay blur in px */
overlayBlur?: number;
/** Value from theme.shadows or any valid css box-shadow value */
shadow?: MantineShadow;
/** Radius from theme.radius, or number to set border-radius in px, defaults to theme.defaultRadius */
radius?: MantineNumberSize;
/** Should spotlight be rendered in the center of the screen */
centered?: boolean;
/** Max spotlight width */
maxWidth?: number;
/** Top offset when spotlight is not centered */
topOffset?: number;
/** Search input placeholder */
searchPlaceholder?: string;
/** Search input icon */
searchIcon?: React.ReactNode;
/** Function used to determine how actions will be filtered based on user input */
filter?(query: string, actions: SpotlightAction[]): SpotlightAction[];
/** Message displayed when actions were not found */
nothingFoundMessage?: React.ReactNode;
/** Number of actions displayed at a time */
limit?: number;
/** Should spotlight be closed when action is triggered */
closeOnActionTrigger?: boolean;
/** Component that is used to render actions */
actionComponent?: React.FC<DefaultActionProps>;
/** Component that is used to wrap actions list */
actionsWrapperComponent?: React.FC<{ children: React.ReactNode }> | string;
/** Spotlight z-index */
zIndex?: React.CSSProperties['zIndex'];
/** Should user query be highlighted in actions title */
highlightQuery?: boolean;
/** The highlight color */
highlightColor?: MantineColor;
/** Props spread to search input */
searchInputProps?: TextInputProps;
}
interface SpotlightProps extends InnerSpotlightProps {
actions: SpotlightAction[];
onClose(): void;
opened: boolean;
query: string;
onQueryChange(query: string): void;
}
export function Spotlight({
query,
onQueryChange,
actions,
onClose,
opened,
withinPortal,
transition = 'pop',
transitionDuration,
classNames,
styles,
overlayColor = '#000',
overlayOpacity = 0.25,
overlayBlur = 3,
shadow = 'md',
radius = 'sm',
centered = false,
closeOnActionTrigger = true,
highlightQuery = false,
highlightColor,
maxWidth = 600,
topOffset = 120,
className,
searchPlaceholder,
searchIcon,
filter = filterActions,
nothingFoundMessage,
limit = 10,
actionComponent = DefaultAction,
actionsWrapperComponent: ActionsWrapper = 'div',
zIndex = getDefaultZIndex('max'),
searchInputProps,
...others
}: SpotlightProps) {
const [hovered, setHovered] = useState(-1);
const [IMEOpen, setIMEOpen] = useState(false);
const { classes, cx } = useStyles(
{ centered, maxWidth, topOffset, radius, zIndex },
{ classNames, styles, name: 'Spotlight' }
);
const [, lockScroll] = useScrollLock();
const focusTrapRef = useFocusTrap(opened);
const resetHovered = () => setHovered(-1);
const handleClose = () => {
resetHovered();
onClose();
};
useFocusReturn({ opened });
const filteredActions = filter(query, actions).slice(0, limit);
const groupedWithLabels = getGroupedOptions(filteredActions).items;
const groupedActions = groupedWithLabels
.map((item) => (item.type === 'item' ? item.item : undefined))
.filter((item) => item);
useDidUpdate(() => {
if (groupedActions.length - 1 < hovered) {
setHovered(groupedActions.length - 1);
}
}, [groupedActions.length]);
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (IMEOpen) {
return;
}
switch (event.key) {
case 'ArrowDown': {
event.preventDefault();
setHovered((current) => (current < groupedActions.length - 1 ? current + 1 : 0));
break;
}
case 'ArrowUp': {
event.preventDefault();
setHovered((current) => (current > 0 ? current - 1 : groupedActions.length - 1));
break;
}
case 'Enter': {
event.preventDefault();
const action = groupedActions[hovered];
action?.onTrigger?.(action);
if (closeOnActionTrigger && action?.onTrigger) {
handleClose();
}
break;
}
case 'Escape': {
event.preventDefault();
handleClose();
}
}
};
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onQueryChange(event.currentTarget.value);
if (hovered === -1) {
setHovered(0);
}
};
return (
<OptionalPortal withinPortal={withinPortal}>
<GroupedTransition
onExited={() => lockScroll(false)}
onEntered={() => lockScroll(true)}
mounted={opened}
transitions={{
spotlight: {
duration: transitionDuration,
transition,
timingFunction: 'ease',
},
overlay: {
duration: transitionDuration / 2,
transition: 'fade',
timingFunction: 'ease',
},
}}
>
{(transitionStyles) => (
<div className={cx(classes.root, className)} {...others}>
<div className={classes.inner} ref={focusTrapRef}>
<Paper
style={transitionStyles.spotlight}
className={classes.spotlight}
shadow={shadow}
radius={radius}
onMouseLeave={resetHovered}
>
<TextInput
{...searchInputProps}
value={query}
onChange={handleInputChange}
onKeyDown={handleInputKeyDown}
onCompositionStart={() => setIMEOpen(true)}
onCompositionEnd={() => setIMEOpen(false)}
classNames={{ input: classes.searchInput }}
size="lg"
placeholder={searchPlaceholder}
icon={searchIcon}
onMouseEnter={resetHovered}
autoComplete="chrome-please-just-do-not-show-it-thanks"
/>
<ActionsWrapper>
<ActionsList
highlightQuery={highlightQuery}
highlightColor={highlightColor}
actions={groupedWithLabels}
actionComponent={actionComponent}
hovered={hovered}
query={query}
nothingFoundMessage={nothingFoundMessage}
onActionHover={setHovered}
onActionTrigger={(action) => {
action.onTrigger(action);
(action.closeOnTrigger ?? closeOnActionTrigger) && handleClose();
}}
styles={styles}
classNames={classNames}
radius={radius}
/>
</ActionsWrapper>
</Paper>
<div style={transitionStyles.overlay}>
<Overlay
className={classes.overlay}
zIndex={1}
onMouseDown={handleClose}
color={overlayColor}
opacity={overlayOpacity}
blur={overlayBlur}
/>
</div>
</div>
</div>
)}
</GroupedTransition>
</OptionalPortal>
);
}
Spotlight.displayName = '@mantine/spotlight/Spotlight';