Skip to content

feat: introduce WithDragAndDropUpload component #2688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/components/Channel/Channel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,10 @@ export type ChannelProps<
updatedMessage: UpdatedMessage<StreamChatGenerics>,
options?: UpdateMessageOptions,
) => ReturnType<StreamChat<StreamChatGenerics>['updateMessage']>;
/** If true, chat users will be able to drag and drop file uploads to the entire channel window */
/**
* @deprecated Use `WithDragAndDropUpload` instead (wrap draggable-to elements with this component).
* @description If true, chat users will be able to drag and drop file uploads to the entire channel window
*/
dragAndDropWindow?: boolean;
/** Custom UI component to be shown if no active channel is set, defaults to null and skips rendering the Channel component */
EmptyPlaceholder?: React.ReactElement;
Expand Down Expand Up @@ -246,7 +249,10 @@ export type ChannelProps<
onMentionsClick?: OnMentionAction<StreamChatGenerics>;
/** Custom action handler function to run on hover of an @mention in a message */
onMentionsHover?: OnMentionAction<StreamChatGenerics>;
/** If `dragAndDropWindow` prop is true, the props to pass to the MessageInput component (overrides props placed directly on MessageInput) */
/**
* @deprecated Use `WithDragAndDropUpload` instead (wrap draggable-to elements with this component).
* @description If `dragAndDropWindow` prop is `true`, the props to pass to the `MessageInput` component (overrides props placed directly on `MessageInput`)
*/
optionalMessageInputProps?: MessageInputProps<StreamChatGenerics, V>;
/** You can turn on/off thumbnail generation for video attachments */
shouldGenerateVideoThumbnail?: boolean;
Expand Down
4 changes: 4 additions & 0 deletions src/components/MessageInput/MessageInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type {
} from '../../types/types';
import type { URLEnrichmentConfig } from './hooks/useLinkPreviews';
import type { CustomAudioRecordingConfig } from '../MediaRecorder';
import { useHandleDragAndDropQueuedFiles } from './WithDragAndDropUpload';

export type EmojiSearchIndexResult = {
id: string;
Expand Down Expand Up @@ -151,6 +152,9 @@ const MessageInputProvider = <
emojiSearchIndex: props.emojiSearchIndex ?? emojiSearchIndex,
});

// @ts-expect-error generics to be removed
useHandleDragAndDropQueuedFiles(messageInputContextValue);

return (
<MessageInputContextProvider<StreamChatGenerics, V> value={messageInputContextValue}>
{props.children}
Expand Down
167 changes: 64 additions & 103 deletions src/components/MessageInput/MessageInputFlat.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import type { Event } from 'stream-chat';
import clsx from 'clsx';
import { useDropzone } from 'react-dropzone';
import {
AttachmentSelector as DefaultAttachmentSelector,
SimpleAttachmentSelector,
Expand All @@ -28,17 +26,16 @@ import { RecordingAttachmentType } from '../MediaRecorder/classes';
import { useChatContext } from '../../context/ChatContext';
import { useChannelActionContext } from '../../context/ChannelActionContext';
import { useChannelStateContext } from '../../context/ChannelStateContext';
import { useTranslationContext } from '../../context/TranslationContext';
import { useMessageInputContext } from '../../context/MessageInputContext';
import { useComponentContext } from '../../context/ComponentContext';

import type { DefaultStreamChatGenerics } from '../../types/types';
import { AIStates, useAIState } from '../AIStateIndicator';
import { WithDragAndDropUpload } from './WithDragAndDropUpload';

export const MessageInputFlat = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>() => {
const { t } = useTranslationContext('MessageInputFlat');
const {
asyncMessagesMultiSendEnabled,
attachments,
Expand All @@ -48,14 +45,12 @@ export const MessageInputFlat = <
hideSendButton,
isUploadEnabled,
linkPreviews,
maxFilesLeft,
message,
numberOfUploads,
parent,
recordingController,
setCooldownRemaining,
text,
uploadNewFiles,
} = useMessageInputContext<StreamChatGenerics>('MessageInputFlat');

const {
Expand All @@ -71,11 +66,8 @@ export const MessageInputFlat = <
StartRecordingAudioButton = DefaultStartRecordingAudioButton,
StopAIGenerationButton: StopAIGenerationButtonOverride,
} = useComponentContext<StreamChatGenerics>('MessageInputFlat');
const {
acceptedFiles = [],
multipleUploads,
quotedMessage,
} = useChannelStateContext<StreamChatGenerics>('MessageInputFlat');
const { quotedMessage } =
useChannelStateContext<StreamChatGenerics>('MessageInputFlat');
const { setQuotedMessage } = useChannelActionContext('MessageInputFlat');
const { channel } = useChatContext<StreamChatGenerics>('MessageInputFlat');

Expand All @@ -96,23 +88,6 @@ export const MessageInputFlat = <
[attachments],
);

const accept = useMemo(
() =>
acceptedFiles.reduce<Record<string, Array<string>>>((mediaTypeMap, mediaType) => {
mediaTypeMap[mediaType] ??= [];
return mediaTypeMap;
}, {}),
[acceptedFiles],
);

const { getRootProps, isDragActive, isDragReject } = useDropzone({
accept,
disabled: !isUploadEnabled || maxFilesLeft === 0,
multiple: multipleUploads,
noClick: true,
onDrop: uploadNewFiles,
});

useEffect(() => {
const handleQuotedMessageUpdate = (e: Event<StreamChatGenerics>) => {
if (e.message?.id !== quotedMessage?.id) return;
Expand Down Expand Up @@ -156,90 +131,76 @@ export const MessageInputFlat = <
!!StopAIGenerationButton;

return (
<>
<div {...getRootProps({ className: 'str-chat__message-input' })}>
{recordingEnabled &&
recordingController.permissionState === 'denied' &&
showRecordingPermissionDeniedNotification && (
<RecordingPermissionDeniedNotification
onClose={closePermissionDeniedNotification}
permissionName={RecordingPermission.MIC}
/>
)}
{findAndEnqueueURLsToEnrich && (
<LinkPreviewList linkPreviews={Array.from(linkPreviews.values())} />
)}
{isDragActive && (
<div
className={clsx('str-chat__dropzone-container', {
'str-chat__dropzone-container--not-accepted': isDragReject,
})}
>
{!isDragReject && <p>{t<string>('Drag your files here')}</p>}
{isDragReject && <p>{t<string>('Some of the files will not be accepted')}</p>}
</div>
<WithDragAndDropUpload className='str-chat__message-input' component='div'>
{recordingEnabled &&
recordingController.permissionState === 'denied' &&
showRecordingPermissionDeniedNotification && (
<RecordingPermissionDeniedNotification
onClose={closePermissionDeniedNotification}
permissionName={RecordingPermission.MIC}
/>
)}
{displayQuotedMessage && <QuotedMessagePreviewHeader />}

<div className='str-chat__message-input-inner'>
<AttachmentSelector />
<div className='str-chat__message-textarea-container'>
{displayQuotedMessage && (
<QuotedMessagePreview quotedMessage={quotedMessage} />
{findAndEnqueueURLsToEnrich && (
<LinkPreviewList linkPreviews={Array.from(linkPreviews.values())} />
)}
{displayQuotedMessage && <QuotedMessagePreviewHeader />}

<div className='str-chat__message-input-inner'>
<AttachmentSelector />
<div className='str-chat__message-textarea-container'>
{displayQuotedMessage && <QuotedMessagePreview quotedMessage={quotedMessage} />}
{isUploadEnabled &&
!!(numberOfUploads + failedUploadsCount || attachments.length > 0) && (
<AttachmentPreviewList />
)}
{isUploadEnabled &&
!!(numberOfUploads + failedUploadsCount || attachments.length > 0) && (
<AttachmentPreviewList />
)}

<div className='str-chat__message-textarea-with-emoji-picker'>
<ChatAutoComplete />
<div className='str-chat__message-textarea-with-emoji-picker'>
<ChatAutoComplete />

{EmojiPicker && <EmojiPicker />}
</div>
{EmojiPicker && <EmojiPicker />}
</div>
{shouldDisplayStopAIGeneration ? (
<StopAIGenerationButton onClick={stopGenerating} />
) : (
!hideSendButton && (
<>
{cooldownRemaining ? (
<CooldownTimer
cooldownInterval={cooldownRemaining}
setCooldownRemaining={setCooldownRemaining}
</div>
{shouldDisplayStopAIGeneration ? (
<StopAIGenerationButton onClick={stopGenerating} />
) : (
!hideSendButton && (
<>
{cooldownRemaining ? (
<CooldownTimer
cooldownInterval={cooldownRemaining}
setCooldownRemaining={setCooldownRemaining}
/>
) : (
<>
<SendButton
disabled={
!numberOfUploads &&
!text.length &&
attachments.length - failedUploadsCount === 0
}
sendMessage={handleSubmit}
/>
) : (
<>
<SendButton
{recordingEnabled && (
<StartRecordingAudioButton
disabled={
!numberOfUploads &&
!text.length &&
attachments.length - failedUploadsCount === 0
isRecording ||
(!asyncMessagesMultiSendEnabled &&
attachments.some(
(a) => a.type === RecordingAttachmentType.VOICE_RECORDING,
))
}
sendMessage={handleSubmit}
onClick={() => {
recordingController.recorder?.start();
setShowRecordingPermissionDeniedNotification(true);
}}
/>
{recordingEnabled && (
<StartRecordingAudioButton
disabled={
isRecording ||
(!asyncMessagesMultiSendEnabled &&
attachments.some(
(a) => a.type === RecordingAttachmentType.VOICE_RECORDING,
))
}
onClick={() => {
recordingController.recorder?.start();
setShowRecordingPermissionDeniedNotification(true);
}}
/>
)}
</>
)}
</>
)
)}
</div>
)}
</>
)}
</>
)
)}
</div>
</>
</WithDragAndDropUpload>
);
};
Loading