-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathWithDragAndDropUpload.tsx
More file actions
173 lines (153 loc) Β· 5.43 KB
/
WithDragAndDropUpload.tsx
File metadata and controls
173 lines (153 loc) Β· 5.43 KB
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
import type { CSSProperties, ElementType, PropsWithChildren } from 'react';
import React, { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
import { useDropzone } from 'react-dropzone';
import clsx from 'clsx';
import type { MessageComposerConfig } from 'stream-chat';
import { useMessageInputContext, useTranslationContext } from '../../context';
import { useAttachmentManagerState, useMessageComposer } from './hooks';
import { useStateStore } from '../../store';
import { useIsCooldownActive } from './hooks/useIsCooldownActive';
import { IconFileArrowLeftIn } from '../Icons';
const DragAndDropUploadContext = React.createContext<{
subscribeToDrop: ((fn: (files: File[]) => void) => () => void) | null;
}>({
subscribeToDrop: null,
});
export const useDragAndDropUploadContext = () => useContext(DragAndDropUploadContext);
/**
* @private This hook should be used only once directly in the `MessageInputProvider` to
* register `uploadNewFiles` functions of the rendered `MessageInputs`. Each `MessageInput`
* will then be notified when the drop event occurs from within the `WithDragAndDropUpload`
* component.
*/
export const useRegisterDropHandlers = () => {
const { subscribeToDrop } = useDragAndDropUploadContext();
const messageComposer = useMessageComposer();
useEffect(() => {
const unsubscribe = subscribeToDrop?.(messageComposer.attachmentManager.uploadFiles);
return unsubscribe;
}, [subscribeToDrop, messageComposer]);
};
const attachmentManagerConfigStateSelector = (state: MessageComposerConfig) => ({
acceptedFiles: state.attachments.acceptedFiles,
multipleUploads: state.attachments.maxNumberOfFilesPerMessage > 1,
});
/**
* Wrapper to replace now deprecated `Channel.dragAndDropWindow` option.
*
* @example
* ```tsx
* <Channel>
* <WithDragAndDropUpload component="section" className="message-list-dnd-wrapper">
* <Window>
* <MessageList />
* <MessageInput />
* </Window>
* </WithDragAndDropUpload>
* <Thread />
* <Channel>
* ```
*/
export const WithDragAndDropUpload = ({
children,
className,
component: Component = 'div',
style,
}: PropsWithChildren<{
acceptedFiles?: string[];
/**
* @description An element to render as a wrapper onto which drag & drop functionality will be applied.
* @default 'div'
*/
component?: ElementType;
className?: string;
style?: CSSProperties;
}>) => {
const dropHandlersRef = useRef<Set<(f: File[]) => void>>(new Set());
const messageInputContext = useMessageInputContext();
const dragAndDropUploadContext = useDragAndDropUploadContext();
const messageComposer = useMessageComposer();
const { isUploadEnabled } = useAttachmentManagerState();
const { acceptedFiles, multipleUploads } = useStateStore(
messageComposer.configState,
attachmentManagerConfigStateSelector,
);
const isCooldownActive = useIsCooldownActive();
// if message input context is available, there's no need to use the queue
const isWithinMessageInputContext = Object.keys(messageInputContext).length > 0;
const accept = useMemo(
() =>
acceptedFiles.reduce<Record<string, Array<string>>>((mediaTypeMap, mediaType) => {
mediaTypeMap[mediaType] ??= [];
return mediaTypeMap;
}, {}),
[acceptedFiles],
);
const subscribeToDrop = useCallback((fn: (files: File[]) => void) => {
dropHandlersRef.current.add(fn);
return () => {
dropHandlersRef.current.delete(fn);
};
}, []);
const handleDrop = useCallback((files: File[]) => {
dropHandlersRef.current.forEach((fn) => fn(files));
}, []);
const {
getRootProps,
isDragActive,
isDragReject: isDragRejected,
} = useDropzone({
accept,
// apply `disabled` rules if available, otherwise allow anything and
// let the `uploadNewFiles` handle the limitations internally
disabled: isWithinMessageInputContext ? !isUploadEnabled || isCooldownActive : false,
multiple: multipleUploads,
noClick: true,
onDrop: isWithinMessageInputContext
? messageComposer.attachmentManager.uploadFiles
: handleDrop,
});
// nested WithDragAndDropUpload components render wrappers without functionality
// (MessageInputFlat has a default WithDragAndDropUpload)
if (dragAndDropUploadContext.subscribeToDrop !== null) {
return <Component className={className}>{children}</Component>;
}
const rootClassName = clsx('str-chat__dropzone-root', className);
return (
<DragAndDropUploadContext.Provider value={{ subscribeToDrop }}>
<Component {...getRootProps({ className: rootClassName, style })}>
{isDragActive && (
<div
className={clsx('str-chat__dropzone-container', {
'str-chat__dropzone-container--not-accepted': isDragRejected,
})}
role='presentation'
>
<FileDragAndDropContent isDragRejected={isDragRejected} />
</div>
)}
{children}
</Component>
</DragAndDropUploadContext.Provider>
);
};
export type FileDragAndDropContentProps = {
isDragRejected: boolean;
};
export const FileDragAndDropContent = ({
isDragRejected,
}: FileDragAndDropContentProps) => {
const { t } = useTranslationContext();
return (
<div className='str-chat__dropzone-container__content'>
{isDragRejected ? (
<p>{t('Some of the files will not be accepted')}</p>
) : (
<>
<IconFileArrowLeftIn />
<p>{t('Drag your files here')}</p>
</>
)}
</div>
);
};