forked from mrzachnugent/react-native-reusables
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.tsx
444 lines (401 loc) · 11 KB
/
command.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
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
import { type ListRenderItemInfo } from '@shopify/flash-list';
import { Search, X } from 'lucide-react-native';
import React, { useImperativeHandle } from 'react';
import {
GestureResponderEvent,
Modal,
Pressable,
Text,
View,
} from 'react-native';
import Animated, { FadeInUp, SlideInUp } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useKeyboard } from '~/lib/keyboard';
import * as Slot from '~/lib/rn-primitives/slot/slot-native';
import { cn, isTextChildren } from '~/lib/utils';
import { Button } from './button';
import { Input } from './input';
import { SectionList } from './section-list';
type Data = Record<string, unknown> | string;
interface CommandProps<T extends Data> {
data: T[];
onItemSelected: (item: Exclude<T, string>) => void;
filterFn: (search: string, item: Exclude<T, string>) => boolean;
defaultOpen?: boolean;
onOpenChange?: (isOpen: boolean) => void;
onSearch?: (search: string) => void;
}
interface CommandContext<T extends Data> {
data: T[];
onItemSelected: (item: Exclude<T, string>) => void;
isOpen: boolean;
toggleIsOpen: () => void;
search: string;
handleOnSearch: (search: string) => void;
}
const CommandContext = React.createContext<CommandContext<any>>(
{} as CommandContext<any>
);
type CommandWrapperProps<T extends Data> = React.ComponentPropsWithoutRef<
typeof View
> &
CommandProps<T>;
function CommandWrapper<T extends Data>(
{
data: dataFromProps,
defaultOpen = false,
onOpenChange,
onSearch,
onItemSelected,
filterFn,
...props
}: CommandWrapperProps<T>,
ref?: React.ForwardedRef<View>
) {
const [isOpen, setIsOpen] = React.useState(defaultOpen);
const [search, setSearch] = React.useState('');
const data = React.useMemo(() => {
const items = dataFromProps.filter((item) => {
if (typeof item === 'string') return true;
return filterFn(search, item as Exclude<T, string>);
});
return items.filter((item, index) => {
if (typeof item === 'string') {
const nextItem = items[index + 1];
return nextItem && typeof nextItem !== 'string';
}
return true;
});
}, [search, dataFromProps, filterFn]);
function toggleIsOpen() {
setIsOpen((prev) => {
const newVal = !prev;
onOpenChange?.(newVal);
return newVal;
});
if (search) {
setSearch('');
}
}
function handleOnSearch(search: string) {
setSearch(search);
onSearch?.(search);
}
return (
<CommandContext.Provider
value={{
data: data,
onItemSelected,
isOpen,
toggleIsOpen,
search,
handleOnSearch,
}}
>
<View ref={ref} {...props} />
</CommandContext.Provider>
);
}
interface WithForwardRefCommand extends React.FC<CommandWrapperProps<Data>> {
<T extends Data>(props: CommandWrapperProps<T>): ReturnType<
React.FC<CommandWrapperProps<T>>
>;
}
const Command: WithForwardRefCommand = React.forwardRef(CommandWrapper);
Command.displayName = 'Command';
function useCommandContext<T extends Data>() {
const context = React.useContext<CommandContext<T>>(CommandContext);
if (!context) {
throw new Error(
'Command compound components cannot be rendered outside the Command component'
);
}
return context;
}
function CommandPressable<T extends Data>(
{
onPress,
asChild = false,
...props
}: React.ComponentPropsWithoutRef<typeof Pressable> & {
asChild?: boolean;
},
ref: React.ForwardedRef<React.ElementRef<typeof Pressable>>
) {
const { toggleIsOpen } = useCommandContext<T>();
function handleOnPress(event: GestureResponderEvent) {
toggleIsOpen();
onPress?.(event);
}
const Trigger = asChild ? Slot.Pressable : Pressable;
return <Trigger onPress={handleOnPress} ref={ref} {...props} />;
}
const CommandTrigger = React.forwardRef(CommandPressable);
CommandTrigger.displayName = 'CommandTrigger';
function CommandModal<T extends Data>(
{
className,
children,
animationType = 'fade',
overlayClass,
style,
...props
}: React.ComponentPropsWithoutRef<typeof Modal> & {
overlayClass?: string;
},
ref: React.ForwardedRef<React.ElementRef<typeof Modal>>
) {
const insets = useSafeAreaInsets();
const { keyboardHeight } = useKeyboard();
const { toggleIsOpen, isOpen } = useCommandContext<T>();
return (
<Modal
ref={ref}
animationType={animationType}
transparent={true}
visible={isOpen}
aria-modal
onRequestClose={toggleIsOpen}
statusBarTranslucent
{...props}
>
<View aria-hidden={isOpen} className={cn('flex-1 ', overlayClass)}>
<Pressable
onPressOut={toggleIsOpen}
className={cn('flex-1', className)}
style={{
paddingTop: insets.top + 8,
}}
>
<Animated.View
entering={FadeInUp.delay(200)}
className='flex-1 bg-zinc-900/30'
>
{children}
<Pressable
onPressOut={toggleIsOpen}
style={{ height: keyboardHeight }}
/>
</Animated.View>
</Pressable>
</View>
</Modal>
);
}
const CommandContent = React.forwardRef(CommandModal);
CommandContent.displayName = 'CommandContent';
function CommandTextInput<T extends Data>(
{
className,
placeholderClassName,
...props
}: React.ComponentPropsWithoutRef<typeof Input>,
ref: React.ForwardedRef<React.ElementRef<typeof Input>>
) {
const inputRef = React.useRef<React.ComponentRef<typeof Input>>(null);
const { search, handleOnSearch, data, onItemSelected, toggleIsOpen } =
useCommandContext<T>();
useImperativeHandle(
ref,
() => {
if (!inputRef.current) {
return {} as React.ComponentRef<typeof Input>;
}
return inputRef.current;
},
[inputRef.current]
);
function onSubmitEditing() {
const firstItem = data.find((item) => typeof item !== 'string');
if (firstItem && typeof firstItem !== 'string') {
onItemSelected(firstItem as Exclude<T, string>);
}
toggleIsOpen();
}
function onSearchIconPress() {
inputRef.current?.focus();
}
return (
<Animated.View
entering={SlideInUp}
className='relative px-4 flex-row items-center pb-4 bg-background z-50'
>
<Input
role='searchbox'
ref={inputRef}
className='pl-12 flex-1'
value={search}
onChangeText={handleOnSearch}
onSubmitEditing={onSubmitEditing}
returnKeyType='go'
returnKeyLabel='Select'
clearButtonMode='while-editing'
placeholder='Type a command or search...'
autoFocus
{...props}
/>
<Button
variant={'ghost'}
size='sm'
className='absolute left-5 top-1.5'
onPress={onSearchIconPress}
>
<Search size={18} className='text-foreground opacity-50' />
</Button>
<Button
variant={'ghost'}
className='pr-0 pl-3'
size='sm'
onPress={toggleIsOpen}
>
<X size={24} className='text-muted-foreground' />
</Button>
</Animated.View>
);
}
const CommandInput = React.forwardRef(CommandTextInput);
CommandInput.displayName = 'CommandInput';
type CommandSectionListProps<T extends Data> = Omit<
React.ComponentPropsWithoutRef<typeof SectionList<T>>,
'data'
> & {
headerHeight?: number;
itemHeight?: number;
};
function CommandSectionList<T extends Data>(
{
headerHeight = 43,
itemHeight = 57,
className,
extraData,
...props
}: CommandSectionListProps<T>,
ref: React.ForwardedRef<React.ElementRef<typeof SectionList<T>>>
) {
const { data, search } = useCommandContext<T>();
function overrideItemLayout(layout: any, item: any) {
if (typeof item === 'string') {
layout.size = headerHeight;
}
layout.size = itemHeight;
}
return (
<View
style={{ minHeight: 2 }}
className={cn('flex-1 rounded-b-2xl overflow-hidden relative', className)}
>
<View className='absolute top-0 right-0 left-0 h-14 bg-background' />
<SectionList<T>
ref={ref}
data={data}
extraData={[search, extraData]}
estimatedItemSize={itemHeight}
overrideItemLayout={overrideItemLayout}
keyboardShouldPersistTaps='handled'
role='menu'
{...props}
/>
</View>
);
}
interface WithForwardRefCommandList
extends React.FC<CommandSectionListProps<Data>> {
<T extends Data>(props: CommandSectionListProps<T>): ReturnType<
React.FC<
Omit<React.ComponentPropsWithoutRef<typeof SectionList<T>>, 'data'> & {
headerHeight?: number;
itemHeight?: number;
}
>
>;
}
const CommandList: WithForwardRefCommandList =
React.forwardRef(CommandSectionList);
CommandList.displayName = 'CommandList';
const CommandListHeader = React.forwardRef<
React.ElementRef<typeof View>,
React.ComponentPropsWithoutRef<typeof View> & { textClass?: string }
>(({ className, textClass, children, ...props }, ref) => {
return (
<Pressable
ref={ref}
className={cn(
'px-5 pt-6 bg-background border-t border-border',
className
)}
{...props}
>
{isTextChildren(children) ? (
<Text
className={cn(
'text-muted-foreground text-base font-semibold px-0.5',
textClass
)}
>
{children}
</Text>
) : (
children
)}
</Pressable>
);
});
type CommandListHeaderProps = ListRenderItemInfo<string>;
CommandListHeader.displayName = 'CommandListHeader';
function CommandSectionListItem<T extends Data>(
{
className,
index,
containnerClass,
onPress,
children,
...props
}: React.ComponentPropsWithoutRef<typeof Button> & {
index: number;
containnerClass?: string;
},
ref: React.ForwardedRef<React.ElementRef<typeof Button>>
) {
const { data, onItemSelected, toggleIsOpen } = useCommandContext<T>();
function handleOnPress(event: GestureResponderEvent) {
const item = data[index];
if (typeof item === 'string' || !item) return;
onItemSelected(item as Exclude<T, string>);
onPress?.(event);
toggleIsOpen();
}
return (
<Pressable
className={cn(
'px-3 py-1 bg-background ',
index === data.length - 1 && 'rounded-b-2xl pb-3',
containnerClass
)}
>
<Button
ref={ref}
variant={index === 1 ? 'secondary' : 'ghost'}
className={cn('flex-row items-center justify-start px-2 gap-3')}
onPress={handleOnPress}
role='menuitem'
{...props}
>
{children}
</Button>
</Pressable>
);
}
type CommandListItemProps<T extends Data> = ListRenderItemInfo<T>;
const CommandListItem = React.forwardRef(CommandSectionListItem);
CommandListItem.displayName = 'CommandListItem';
export {
Command,
CommandContent,
CommandInput,
CommandList,
CommandListHeader,
CommandListItem,
CommandTrigger,
type CommandListHeaderProps,
type CommandListItemProps,
};