diff --git a/examples/ExpoMessaging/package.json b/examples/ExpoMessaging/package.json index 277bd91ffd..4e684ae738 100644 --- a/examples/ExpoMessaging/package.json +++ b/examples/ExpoMessaging/package.json @@ -40,7 +40,7 @@ "expo-video": "~58.0.10", "react": "19.3.0", "react-dom": "19.3.0", - "react-native": "0.88.0", + "react-native": "0.88.1", "react-native-gesture-handler": "~3.4.0", "react-native-keyboard-controller": "1.22.7", "react-native-maps": "1.29.11", diff --git a/examples/SampleApp/App.tsx b/examples/SampleApp/App.tsx index 554f274069..0b92e8778e 100644 --- a/examples/SampleApp/App.tsx +++ b/examples/SampleApp/App.tsx @@ -54,6 +54,7 @@ import { MapScreen } from './src/screens/MapScreen'; import { NewDirectMessagingScreen } from './src/screens/NewDirectMessagingScreen'; import { NewGroupChannelAddMemberScreen } from './src/screens/NewGroupChannelAddMemberScreen'; import { NewGroupChannelAssignNameScreen } from './src/screens/NewGroupChannelAssignNameScreen'; +import { ScheduledMessagesScreen } from './src/screens/ScheduledMessagesScreen'; import { ThreadScreen } from './src/screens/ThreadScreen'; import { UserSelectorScreen } from './src/screens/UserSelectorScreen'; @@ -462,6 +463,11 @@ const HomeScreen = () => { name='ChannelPinnedMessagesScreen' options={{ headerShown: false }} /> + { iconActive: , title: 'Reminders', }; + case 'ScheduledScreen': + return { + icon: , + iconActive: , + title: 'Scheduled', + }; // Add more cases for other tabs as needed default: return null; @@ -127,28 +141,39 @@ const Tab = (props: TabProps) => { }; export const BottomTabs: React.FC = (props) => { - const { navigation, state } = props; + const { descriptors, navigation, state } = props; const { theme: { semantics }, } = useTheme(); const { bottom, left, right } = useSafeAreaInsets(); + const { tabBarStyle } = descriptors[state.routes[state.index].key].options; + + // A screen hides the tab bar with `tabBarStyle: { display: 'none' }`, e.g. while editing. It + // slides down out of view, and back up when shown again, but not when the app opens. + const hidden = StyleSheet.flatten(tabBarStyle)?.display === 'none'; return ( - - {state.routes.map((route, index) => ( - - ))} - + + {hidden ? null : ( + + {state.routes.map((route, index) => ( + + ))} + + )} + ); }; diff --git a/examples/SampleApp/src/components/ScheduledMessages/useAllScheduledMessagesView.ts b/examples/SampleApp/src/components/ScheduledMessages/useAllScheduledMessagesView.ts new file mode 100644 index 0000000000..365565b5c2 --- /dev/null +++ b/examples/SampleApp/src/components/ScheduledMessages/useAllScheduledMessagesView.ts @@ -0,0 +1,26 @@ +import { useEffect, useMemo } from 'react'; + +import { ScheduledMessagePaginator, ScheduledMessagesView } from 'stream-chat'; +import { useChatContext } from 'stream-chat-react-native'; + +/** + * Every scheduled message of the user, across channels. Its paginator is registered with the + * client while mounted, so the list follows the scheduled message events. + */ +export const useAllScheduledMessagesView = () => { + const { client } = useChatContext(); + const view = useMemo( + () => new ScheduledMessagesView({ paginator: new ScheduledMessagePaginator({ client }) }), + [client], + ); + + useEffect(() => { + const manager = client.scheduledMessagePaginators; + manager.insertPaginator({ paginator: view.paginator }); + return () => { + manager.removePaginator(view.paginator); + }; + }, [client, view]); + + return view; +}; diff --git a/examples/SampleApp/src/icons/ScheduledTab.tsx b/examples/SampleApp/src/icons/ScheduledTab.tsx new file mode 100644 index 0000000000..7b78b5c0a4 --- /dev/null +++ b/examples/SampleApp/src/icons/ScheduledTab.tsx @@ -0,0 +1,35 @@ +import React from 'react'; +import Svg, { Path } from 'react-native-svg'; + +import { useLegacyColors } from '../theme/useLegacyColors'; +import { IconProps } from '../utils/base'; + +/** A filled clock while the tab is active, and the SDK's outlined clock otherwise, as in Figma. */ +export const ScheduledTab: React.FC = ({ active, height = 24, width = 24 }) => { + const { black, grey } = useLegacyColors(); + + if (!active) { + return ( + + + + ); + } + + return ( + + + + ); +}; diff --git a/examples/SampleApp/src/screens/ChannelDetailsScreen.tsx b/examples/SampleApp/src/screens/ChannelDetailsScreen.tsx index e2c02ef626..f6b840add0 100644 --- a/examples/SampleApp/src/screens/ChannelDetailsScreen.tsx +++ b/examples/SampleApp/src/screens/ChannelDetailsScreen.tsx @@ -42,9 +42,11 @@ const navigationItems: { [key in ChannelDetailsNavigationSectionType]: | 'ChannelPinnedMessagesScreen' | 'ChannelImagesScreen' - | 'ChannelFilesScreen'; + | 'ChannelFilesScreen' + | 'ScheduledMessagesScreen'; } = { 'pinned-messages': 'ChannelPinnedMessagesScreen', + 'scheduled-messages': 'ScheduledMessagesScreen', 'photos-and-videos': 'ChannelImagesScreen', files: 'ChannelFilesScreen', }; diff --git a/examples/SampleApp/src/screens/ChannelScreen.tsx b/examples/SampleApp/src/screens/ChannelScreen.tsx index 7039de0cf8..28418eb01b 100644 --- a/examples/SampleApp/src/screens/ChannelScreen.tsx +++ b/examples/SampleApp/src/screens/ChannelScreen.tsx @@ -309,6 +309,12 @@ export const ChannelScreen: React.FC = ({ navigation, route [channel, messageId, navigation, setThread], ); + const onScheduledMessagesBannerPress = useCallback( + ({ channel: bannerChannel }: { channel: StreamChatChannel }) => + navigation.navigate('ScheduledMessagesScreen', { channel: bannerChannel }), + [navigation], + ); + const handleMessageInfo = useCallback((message: LocalMessage) => { setSelectedMessage(message); setModalVisible(true); @@ -387,6 +393,7 @@ export const ChannelScreen: React.FC = ({ navigation, route keyboardVerticalOffset={0} messageActions={messageActions} onAlsoSentToChannelHeaderPress={onAlsoSentToChannelHeaderPress} + onScheduledMessagesBannerPress={onScheduledMessagesBannerPress} > diff --git a/examples/SampleApp/src/screens/ChatScreen.tsx b/examples/SampleApp/src/screens/ChatScreen.tsx index 9670513d43..f161bc4951 100644 --- a/examples/SampleApp/src/screens/ChatScreen.tsx +++ b/examples/SampleApp/src/screens/ChatScreen.tsx @@ -10,6 +10,7 @@ import { ChannelListScreen } from './ChannelListScreen'; import { DraftsScreen } from './DraftScreen'; import { MentionsScreen } from './MentionsScreen'; import { RemindersScreen } from './RemindersScreen'; +import { ScheduledScreen } from './ScheduledScreen'; import { ThreadListScreen } from './ThreadListScreen'; import { BottomTabs } from '../components/BottomTabs'; @@ -39,6 +40,11 @@ export const ChatScreen: React.FC = () => ( name='ThreadsScreen' options={{ headerShown: false }} /> + ; +}; + +/** + * A channel's or a thread's scheduled messages. The `Channel` is set up like the channel screen's, + * so editing uses the same composer, but it neither loads messages nor marks the channel read. + */ +export const ScheduledMessagesScreen: React.FC = ({ + route: { + params: { channel, thread }, + }, +}) => { + const { messageInputFloating } = useAppContext(); + + return ( + + + + + + + ); +}; + +const styles = StyleSheet.create({ + flex: { + flex: 1, + }, +}); diff --git a/examples/SampleApp/src/screens/ScheduledScreen.tsx b/examples/SampleApp/src/screens/ScheduledScreen.tsx new file mode 100644 index 0000000000..980c5ded16 --- /dev/null +++ b/examples/SampleApp/src/screens/ScheduledScreen.tsx @@ -0,0 +1,112 @@ +import React, { useEffect, useState } from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { SafeAreaView } from 'react-native-safe-area-context'; + +import type { BottomTabNavigationProp } from '@react-navigation/bottom-tabs'; +import { useNavigation } from '@react-navigation/native'; + +import type { ScheduledMessageResponse, Channel as StreamChatChannel } from 'stream-chat'; +import { + Channel, + getChannelNotificationHostId, + getScheduledMessageChannel, + NotificationList, + ScheduledMessageEditComposer, + ScheduledMessageList, + useChatContext, + useStableCallback, +} from 'stream-chat-react-native'; + +import { ChatScreenHeader } from '../components/ChatScreenHeader'; +import { useAllScheduledMessagesView } from '../components/ScheduledMessages/useAllScheduledMessagesView'; +import { useAppContext } from '../context/AppContext'; +import type { BottomTabNavigatorParamList } from '../types'; + +type EditTarget = { + channel: StreamChatChannel; + scheduledMessage: ScheduledMessageResponse; +}; + +/** + * Edits a message from the tab. The list mixes channels, so only the composer is wrapped in a + * `Channel`, for the edited message's channel, laid over the whole screen. The tab bar is hidden + * meanwhile, so the `Channel` reaches the bottom of the window, as on a channel screen. + */ +const ScheduledTabEditComposer = ({ + channel, + onClose, + scheduledMessage, +}: EditTarget & { onClose: () => void }) => { + const { messageInputFloating } = useAppContext(); + + return ( + + + + + + + + + ); +}; + +/** The Scheduled tab: every scheduled message of the user, across channels. */ +export const ScheduledScreen: React.FC = () => { + const { client } = useChatContext(); + const navigation = useNavigation>(); + const view = useAllScheduledMessagesView(); + const [editTarget, setEditTarget] = useState(); + const isEditing = !!editTarget; + + useEffect(() => { + navigation.setOptions({ tabBarStyle: isEditing ? { display: 'none' } : undefined }); + }, [isEditing, navigation]); + + const editScheduledMessage = useStableCallback( + async (scheduledMessage: ScheduledMessageResponse) => { + const channel = getScheduledMessageChannel(client, scheduledMessage); + // The composer needs the channel's config and the user's capabilities, which a query loads. + if (!channel.initialized) { + try { + await channel.query(); + } catch { + return; + } + } + setEditTarget({ channel, scheduledMessage }); + }, + ); + + const closeEdit = useStableCallback(() => setEditTarget(undefined)); + + return ( + + + + {editTarget ? ( + + ) : null} + + ); +}; + +const styles = StyleSheet.create({ + flex: { + flex: 1, + }, +}); diff --git a/examples/SampleApp/src/screens/ThreadScreen.tsx b/examples/SampleApp/src/screens/ThreadScreen.tsx index b4fbfa1303..a1ea258501 100644 --- a/examples/SampleApp/src/screens/ThreadScreen.tsx +++ b/examples/SampleApp/src/screens/ThreadScreen.tsx @@ -165,6 +165,11 @@ export const ThreadScreen: React.FC = ({ navigation, route }) [channel, navigation], ); + const onScheduledMessagesBannerPress = useCallback( + () => navigation.navigate('ScheduledMessagesScreen', { channel, thread }), + [channel, navigation, thread], + ); + return ( = ({ navigation, route }) onPressMessage={onPressMessage} thread={thread} onAlsoSentToChannelHeaderPress={onAlsoSentToChannelHeaderPress} + onScheduledMessagesBannerPress={onScheduledMessagesBannerPress} onThreadDismount={onThreadDismount} > diff --git a/examples/SampleApp/src/types.ts b/examples/SampleApp/src/types.ts index 3114756bf8..285a240aca 100644 --- a/examples/SampleApp/src/types.ts +++ b/examples/SampleApp/src/types.ts @@ -30,6 +30,10 @@ export type StackNavigatorParamList = { NewDirectMessagingScreen: { initialUser?: UserResponse } | undefined; NewGroupChannelAddMemberScreen: undefined; NewGroupChannelAssignNameScreen: undefined; + ScheduledMessagesScreen: { + channel: Channel; + thread?: Thread; + }; ThreadScreen: { channel: Channel; thread: Thread; @@ -47,6 +51,7 @@ export type BottomTabNavigatorParamList = { DraftsScreen: undefined; RemindersScreen: undefined; MentionsScreen: undefined; + ScheduledScreen: undefined; ThreadsScreen: undefined; }; diff --git a/package/expo-package/Package.swift b/package/expo-package/Package.swift index 2201137289..75df8598f6 100644 --- a/package/expo-package/Package.swift +++ b/package/expo-package/Package.swift @@ -24,6 +24,7 @@ let interfacesTargetName = "StreamChatNativeInterfaces" let swiftSources = [ "AIAgentModule.swift", "AIDictationModule.swift", + "StreamDateTimePickerPresenter.swift", "StreamMultipartUploadBodyStream.swift", "StreamMultipartUploadManager.swift", "StreamMultipartUploadModels.swift", diff --git a/package/expo-package/android/build.gradle b/package/expo-package/android/build.gradle index a63828b6cd..44afd1b820 100644 --- a/package/expo-package/android/build.gradle +++ b/package/expo-package/android/build.gradle @@ -164,6 +164,9 @@ dependencies { // The agent components' tool-call sign-ins: an Auth Tab where the app's build allows 1.9.0, // else a Custom Tab (see `agentSignInWithAuthTab`). implementation "androidx.browser:browser:${agentSignInWithAuthTab ? '1.9.0' : '1.8.0'}" + // Provides the date and time picker dialogs. Apps using react-native-screens already resolve + // 1.13.0, so this declaration does not raise their version. + implementation "com.google.android.material:material:1.12.0" } if (isNewArchitectureEnabled()) { diff --git a/package/expo-package/android/src/main/java/com/streamchatexpo/StreamChatExpoPackage.java b/package/expo-package/android/src/main/java/com/streamchatexpo/StreamChatExpoPackage.java index 9336dd4546..6b2cc3197d 100644 --- a/package/expo-package/android/src/main/java/com/streamchatexpo/StreamChatExpoPackage.java +++ b/package/expo-package/android/src/main/java/com/streamchatexpo/StreamChatExpoPackage.java @@ -17,6 +17,7 @@ public class StreamChatExpoPackage extends TurboReactPackage { private static final String STREAM_MULTIPART_UPLOADER_MODULE = "StreamMultipartUploader"; private static final String STREAM_VIDEO_THUMBNAIL_MODULE = "StreamVideoThumbnail"; + private static final String STREAM_DATE_TIME_PICKER_MODULE = "StreamDateTimePicker"; private static final String AI_DICTATION_MODULE = "AIDictation"; private static final String AI_AGENT_MODULE = "AIAgent"; @@ -31,6 +32,10 @@ public NativeModule getModule(String name, ReactApplicationContext reactContext) return createNewArchModule("com.streamchatexpo.StreamVideoThumbnailModule", reactContext); } + if (name.equals(STREAM_DATE_TIME_PICKER_MODULE)) { + return createNewArchModule("com.streamchatexpo.StreamDateTimePickerModule", reactContext); + } + if (name.equals(AI_DICTATION_MODULE)) { return createNewArchModule("com.streamchatexpo.AIDictationModule", reactContext); } @@ -68,6 +73,17 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { false, // isCxxModule true // isTurboModule )); + moduleInfos.put( + STREAM_DATE_TIME_PICKER_MODULE, + new ReactModuleInfo( + STREAM_DATE_TIME_PICKER_MODULE, + STREAM_DATE_TIME_PICKER_MODULE, + false, // canOverrideExistingModule + false, // needsEagerInit + false, // hasConstants + false, // isCxxModule + true // isTurboModule + )); moduleInfos.put( AI_DICTATION_MODULE, diff --git a/package/expo-package/android/src/main/res/values-night/stream_date_time_picker.xml b/package/expo-package/android/src/main/res/values-night/stream_date_time_picker.xml new file mode 100644 index 0000000000..fb2ec7f522 --- /dev/null +++ b/package/expo-package/android/src/main/res/values-night/stream_date_time_picker.xml @@ -0,0 +1,17 @@ + + + + #FFFFFF + #1A1C1C + #D4D4D4 + #000000 + #474747 + #E2E2E2 + #131313 + #2A2A2A + #353535 + #E2E2E2 + #C6C6C6 + #565656 + #474747 + diff --git a/package/expo-package/android/src/main/res/values/stream_date_time_picker.xml b/package/expo-package/android/src/main/res/values/stream_date_time_picker.xml new file mode 100644 index 0000000000..fb4af5ab8c --- /dev/null +++ b/package/expo-package/android/src/main/res/values/stream_date_time_picker.xml @@ -0,0 +1,89 @@ + + + + #1A1B25 + #FFFFFF + #1A1B25 + #FFFFFF + #D5DBE1 + #1A1B25 + #EBEEF1 + #EBEEF1 + #D5DBE1 + #1A1B25 + #414552 + #C0C8D2 + #C0C8D2 + + + + + + + + + + + + diff --git a/package/expo-package/android/src/newarch/com/streamchatexpo/StreamDateTimePickerModule.kt b/package/expo-package/android/src/newarch/com/streamchatexpo/StreamDateTimePickerModule.kt new file mode 100644 index 0000000000..a7913488d5 --- /dev/null +++ b/package/expo-package/android/src/newarch/com/streamchatexpo/StreamDateTimePickerModule.kt @@ -0,0 +1,59 @@ +package com.streamchatexpo + +import com.facebook.react.bridge.LifecycleEventListener +import com.facebook.react.bridge.Promise +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReadableMap +import com.streamchatreactnative.shared.StreamDateTimePicker + +class StreamDateTimePickerModule( + reactContext: ReactApplicationContext, +) : NativeStreamDateTimePickerSpec(reactContext), + LifecycleEventListener { + init { + reactContext.addLifecycleEventListener(this) + } + + override fun getName(): String = NAME + + override fun pick(options: ReadableMap, promise: Promise) { + StreamDateTimePicker.pick( + activity = reactApplicationContext.currentActivity, + themes = + StreamDateTimePicker.Themes( + date = R.style.StreamChat_DateTimePicker_Date, + time = R.style.StreamChat_DateTimePicker_Time, + ), + mode = options.getString("mode") ?: "date", + value = options.getDouble("value").toLong(), + minimumDate = options.optionalMillis("minimumDate"), + maximumDate = options.optionalMillis("maximumDate"), + ) { result -> promise.resolve(result?.toDouble()) } + } + + override fun dismiss() { + StreamDateTimePicker.dismissActive() + } + + override fun onHostResume() { + StreamDateTimePicker.dismissOrphans(reactApplicationContext.currentActivity) + } + + override fun onHostPause() = Unit + + override fun onHostDestroy() = Unit + + // Dismisses a picker that is still shown when the module is invalidated, for example on reload. + override fun invalidate() { + reactApplicationContext.removeLifecycleEventListener(this) + StreamDateTimePicker.dismissActive() + super.invalidate() + } + + private fun ReadableMap.optionalMillis(key: String): Long? = + if (hasKey(key) && !isNull(key)) getDouble(key).toLong() else null + + companion object { + const val NAME = "StreamDateTimePicker" + } +} diff --git a/package/expo-package/package.json b/package/expo-package/package.json index ae4d21ccec..0659c9a0c1 100644 --- a/package/expo-package/package.json +++ b/package/expo-package/package.json @@ -118,6 +118,7 @@ "ios": { "modulesProvider": { "AIAgent": "AIAgent", + "StreamDateTimePicker": "StreamDateTimePicker", "StreamMultipartUploader": "StreamMultipartUploader", "StreamVideoThumbnail": "StreamVideoThumbnail" }, diff --git a/package/expo-package/src/handlers/__tests__/pickDateTime.test.ts b/package/expo-package/src/handlers/__tests__/pickDateTime.test.ts new file mode 100644 index 0000000000..81a6dce94c --- /dev/null +++ b/package/expo-package/src/handlers/__tests__/pickDateTime.test.ts @@ -0,0 +1,66 @@ +describe('pickDateTime', () => { + const pick = jest.fn(); + const dismiss = jest.fn(); + + const loadHandler = () => { + // `__esModule: true` keeps the handler's default import from double-wrapping the mock. + jest.doMock('../../native/NativeStreamDateTimePicker', () => ({ + __esModule: true, + default: { dismiss, pick }, + })); + return require('../pickDateTime').pickDateTime as typeof import('../pickDateTime').pickDateTime; + }; + + const options = (signal?: AbortSignal) => ({ + cancelLabel: 'Cancel', + confirmLabel: 'Confirm', + mode: 'date' as const, + signal, + value: new Date(1_700_000_000_000), + }); + + afterEach(() => { + jest.resetModules(); + jest.clearAllMocks(); + }); + + it('resolves with the picked moment', async () => { + pick.mockResolvedValue(1_700_000_060_000); + + await expect(loadHandler()(options())).resolves.toEqual(new Date(1_700_000_060_000)); + expect(pick).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'date', value: 1_700_000_000_000 }), + ); + }); + + it('closes the picker when the signal aborts, and resolves with null', async () => { + let resolvePick: (value: number | null) => void = () => undefined; + pick.mockImplementation(() => new Promise((resolve) => (resolvePick = resolve))); + dismiss.mockImplementation(() => resolvePick(null)); + const controller = new AbortController(); + + const result = loadHandler()(options(controller.signal)); + controller.abort(); + + await expect(result).resolves.toBeNull(); + expect(dismiss).toHaveBeenCalledTimes(1); + }); + + it('opens nothing when the signal is already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + + await expect(loadHandler()(options(controller.signal))).resolves.toBeNull(); + expect(pick).not.toHaveBeenCalled(); + }); + + it('leaves the next picker alone when aborted after settling', async () => { + pick.mockResolvedValue(null); + const controller = new AbortController(); + + await loadHandler()(options(controller.signal)); + controller.abort(); + + expect(dismiss).not.toHaveBeenCalled(); + }); +}); diff --git a/package/expo-package/src/handlers/index.ts b/package/expo-package/src/handlers/index.ts index 83b0ed3ce3..966e4d795e 100644 --- a/package/expo-package/src/handlers/index.ts +++ b/package/expo-package/src/handlers/index.ts @@ -1,2 +1,3 @@ export * from './compressImage'; export * from './multipartUpload'; +export * from './pickDateTime'; diff --git a/package/expo-package/src/handlers/pickDateTime.ts b/package/expo-package/src/handlers/pickDateTime.ts new file mode 100644 index 0000000000..8bbb20a4ed --- /dev/null +++ b/package/expo-package/src/handlers/pickDateTime.ts @@ -0,0 +1,37 @@ +import type { PickDateTime } from 'stream-chat-react-native-core'; + +import NativeStreamDateTimePicker from '../native/NativeStreamDateTimePicker'; + +/** + * Opens the system date or time picker. Resolves with the selected moment, or with `null` when the + * picker is cancelled, aborted through `signal`, or unavailable because the native module is absent. + */ +export const pickDateTime: PickDateTime = async ({ + cancelLabel, + confirmLabel, + maximumDate, + minimumDate, + mode, + signal, + value, +}) => { + const nativePicker = NativeStreamDateTimePicker; + if (!nativePicker || signal?.aborted) return null; + + // Only one picker is shown at a time, so dismissing the current picker closes this one. + const dismiss = () => nativePicker.dismiss(); + signal?.addEventListener('abort', dismiss); + try { + const picked = await nativePicker.pick({ + cancelLabel, + confirmLabel, + maximumDate: maximumDate?.getTime(), + minimumDate: minimumDate?.getTime(), + mode, + value: value.getTime(), + }); + return picked === null || signal?.aborted ? null : new Date(picked); + } finally { + signal?.removeEventListener('abort', dismiss); + } +}; diff --git a/package/expo-package/src/index.js b/package/expo-package/src/index.js index 3a624dd845..a8c1bea7ab 100644 --- a/package/expo-package/src/index.js +++ b/package/expo-package/src/index.js @@ -2,7 +2,7 @@ import { FlatList } from 'react-native'; import { registerNativeHandlers } from 'stream-chat-react-native-core'; -import { compressImage, multipartUpload } from './handlers'; +import { compressImage, multipartUpload, pickDateTime } from './handlers'; import { Audio, @@ -39,6 +39,7 @@ export const defaultNativeHandlers = { NativeShimmerView, oniOS14GalleryLibrarySelectionChange, overrideAudioRecordingConfiguration, + pickDateTime, pickDocument, pickImage, saveFile, diff --git a/package/expo-package/src/native/NativeStreamDateTimePicker.ts b/package/expo-package/src/native/NativeStreamDateTimePicker.ts new file mode 100644 index 0000000000..8c0fd520c0 --- /dev/null +++ b/package/expo-package/src/native/NativeStreamDateTimePicker.ts @@ -0,0 +1,31 @@ +import type { TurboModule } from 'react-native'; +import { TurboModuleRegistry } from 'react-native'; + +/** + * Codegen spec for the native date and time picker, backed by Material dialogs on Android and a + * `UIDatePicker` dialog on iOS. + * + * The spec exists in both `package/native-package/src/native` and `package/expo-package/src/native`, + * since codegen reads each package separately. Keep the two copies identical. + */ + +export type DateTimePickerOptions = { + /** Either `date` or `time`. */ + mode: string; + /** The moment the picker opens on, in milliseconds since the epoch. */ + value: number; + minimumDate?: number; + maximumDate?: number; + /** Translated labels for the iOS dialog buttons. The Android dialogs provide their own. */ + confirmLabel: string; + cancelLabel: string; +}; + +export interface Spec extends TurboModule { + /** Resolves with the selected moment in milliseconds, or null when the picker is cancelled. */ + pick(options: DateTimePickerOptions): Promise; + /** Dismisses the picker currently shown, which resolves its `pick` call with null. */ + dismiss(): void; +} + +export default TurboModuleRegistry.get('StreamDateTimePicker'); diff --git a/package/native-package/Package.swift b/package/native-package/Package.swift index 21e6b598ea..70f04fa218 100644 --- a/package/native-package/Package.swift +++ b/package/native-package/Package.swift @@ -24,6 +24,7 @@ let interfacesTargetName = "StreamChatNativeInterfaces" let swiftSources = [ "AIAgentModule.swift", "AIDictationModule.swift", + "StreamDateTimePickerPresenter.swift", "StreamMultipartUploadBodyStream.swift", "StreamMultipartUploadManager.swift", "StreamMultipartUploadModels.swift", diff --git a/package/native-package/android/build.gradle b/package/native-package/android/build.gradle index 187eef47e3..05be40465d 100644 --- a/package/native-package/android/build.gradle +++ b/package/native-package/android/build.gradle @@ -182,6 +182,9 @@ dependencies { // The agent components' tool-call sign-ins: an Auth Tab where the app's build allows 1.9.0, // else a Custom Tab (see `agentSignInWithAuthTab`). implementation "androidx.browser:browser:${agentSignInWithAuthTab ? '1.9.0' : '1.8.0'}" + // Provides the date and time picker dialogs. Apps using react-native-screens already resolve + // 1.13.0, so this declaration does not raise their version. + implementation "com.google.android.material:material:1.12.0" } if (isNewArchitectureEnabled()) { diff --git a/package/native-package/android/src/main/java/com/streamchatreactnative/StreamChatReactNativePackage.java b/package/native-package/android/src/main/java/com/streamchatreactnative/StreamChatReactNativePackage.java index aa8e7be391..340b5f0dc2 100644 --- a/package/native-package/android/src/main/java/com/streamchatreactnative/StreamChatReactNativePackage.java +++ b/package/native-package/android/src/main/java/com/streamchatreactnative/StreamChatReactNativePackage.java @@ -16,6 +16,7 @@ public class StreamChatReactNativePackage extends TurboReactPackage { private static final String STREAM_MULTIPART_UPLOADER_MODULE = "StreamMultipartUploader"; private static final String STREAM_VIDEO_THUMBNAIL_MODULE = "StreamVideoThumbnail"; + private static final String STREAM_DATE_TIME_PICKER_MODULE = "StreamDateTimePicker"; private static final String AI_DICTATION_MODULE = "AIDictation"; private static final String AI_AGENT_MODULE = "AIAgent"; @@ -34,6 +35,11 @@ public NativeModule getModule(String name, ReactApplicationContext reactContext) "com.streamchatreactnative.StreamVideoThumbnailModule", reactContext ); + } else if (name.equals(STREAM_DATE_TIME_PICKER_MODULE)) { + return createNewArchModule( + "com.streamchatreactnative.StreamDateTimePickerModule", + reactContext + ); } else if (name.equals(AI_DICTATION_MODULE)) { return createNewArchModule( "com.streamchatreactnative.AIDictationModule", @@ -86,6 +92,17 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { false, // isCxxModule true // isTurboModule )); + moduleInfos.put( + STREAM_DATE_TIME_PICKER_MODULE, + new ReactModuleInfo( + STREAM_DATE_TIME_PICKER_MODULE, + STREAM_DATE_TIME_PICKER_MODULE, + false, // canOverrideExistingModule + false, // needsEagerInit + false, // hasConstants + false, // isCxxModule + true // isTurboModule + )); moduleInfos.put( AI_DICTATION_MODULE, diff --git a/package/native-package/android/src/main/res/values-night/stream_date_time_picker.xml b/package/native-package/android/src/main/res/values-night/stream_date_time_picker.xml new file mode 100644 index 0000000000..fb2ec7f522 --- /dev/null +++ b/package/native-package/android/src/main/res/values-night/stream_date_time_picker.xml @@ -0,0 +1,17 @@ + + + + #FFFFFF + #1A1C1C + #D4D4D4 + #000000 + #474747 + #E2E2E2 + #131313 + #2A2A2A + #353535 + #E2E2E2 + #C6C6C6 + #565656 + #474747 + diff --git a/package/native-package/android/src/main/res/values/stream_date_time_picker.xml b/package/native-package/android/src/main/res/values/stream_date_time_picker.xml new file mode 100644 index 0000000000..fb4af5ab8c --- /dev/null +++ b/package/native-package/android/src/main/res/values/stream_date_time_picker.xml @@ -0,0 +1,89 @@ + + + + #1A1B25 + #FFFFFF + #1A1B25 + #FFFFFF + #D5DBE1 + #1A1B25 + #EBEEF1 + #EBEEF1 + #D5DBE1 + #1A1B25 + #414552 + #C0C8D2 + #C0C8D2 + + + + + + + + + + + + diff --git a/package/native-package/android/src/newarch/com/streamchatreactnative/StreamDateTimePickerModule.kt b/package/native-package/android/src/newarch/com/streamchatreactnative/StreamDateTimePickerModule.kt new file mode 100644 index 0000000000..64968cdd70 --- /dev/null +++ b/package/native-package/android/src/newarch/com/streamchatreactnative/StreamDateTimePickerModule.kt @@ -0,0 +1,59 @@ +package com.streamchatreactnative + +import com.facebook.react.bridge.LifecycleEventListener +import com.facebook.react.bridge.Promise +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReadableMap +import com.streamchatreactnative.shared.StreamDateTimePicker + +class StreamDateTimePickerModule( + reactContext: ReactApplicationContext, +) : NativeStreamDateTimePickerSpec(reactContext), + LifecycleEventListener { + init { + reactContext.addLifecycleEventListener(this) + } + + override fun getName(): String = NAME + + override fun pick(options: ReadableMap, promise: Promise) { + StreamDateTimePicker.pick( + activity = reactApplicationContext.currentActivity, + themes = + StreamDateTimePicker.Themes( + date = R.style.StreamChat_DateTimePicker_Date, + time = R.style.StreamChat_DateTimePicker_Time, + ), + mode = options.getString("mode") ?: "date", + value = options.getDouble("value").toLong(), + minimumDate = options.optionalMillis("minimumDate"), + maximumDate = options.optionalMillis("maximumDate"), + ) { result -> promise.resolve(result?.toDouble()) } + } + + override fun dismiss() { + StreamDateTimePicker.dismissActive() + } + + override fun onHostResume() { + StreamDateTimePicker.dismissOrphans(reactApplicationContext.currentActivity) + } + + override fun onHostPause() = Unit + + override fun onHostDestroy() = Unit + + // Dismisses a picker that is still shown when the module is invalidated, for example on reload. + override fun invalidate() { + reactApplicationContext.removeLifecycleEventListener(this) + StreamDateTimePicker.dismissActive() + super.invalidate() + } + + private fun ReadableMap.optionalMillis(key: String): Long? = + if (hasKey(key) && !isNull(key)) getDouble(key).toLong() else null + + companion object { + const val NAME = "StreamDateTimePicker" + } +} diff --git a/package/native-package/package.json b/package/native-package/package.json index 77e99e236c..fc9f35cbbf 100644 --- a/package/native-package/package.json +++ b/package/native-package/package.json @@ -113,6 +113,7 @@ "modulesProvider": { "AIAgent": "AIAgent", "StreamChatReactNative": "StreamChatReactNative", + "StreamDateTimePicker": "StreamDateTimePicker", "StreamMultipartUploader": "StreamMultipartUploader", "StreamVideoThumbnail": "StreamVideoThumbnail" }, diff --git a/package/native-package/src/handlers/__tests__/pickDateTime.test.ts b/package/native-package/src/handlers/__tests__/pickDateTime.test.ts new file mode 100644 index 0000000000..81a6dce94c --- /dev/null +++ b/package/native-package/src/handlers/__tests__/pickDateTime.test.ts @@ -0,0 +1,66 @@ +describe('pickDateTime', () => { + const pick = jest.fn(); + const dismiss = jest.fn(); + + const loadHandler = () => { + // `__esModule: true` keeps the handler's default import from double-wrapping the mock. + jest.doMock('../../native/NativeStreamDateTimePicker', () => ({ + __esModule: true, + default: { dismiss, pick }, + })); + return require('../pickDateTime').pickDateTime as typeof import('../pickDateTime').pickDateTime; + }; + + const options = (signal?: AbortSignal) => ({ + cancelLabel: 'Cancel', + confirmLabel: 'Confirm', + mode: 'date' as const, + signal, + value: new Date(1_700_000_000_000), + }); + + afterEach(() => { + jest.resetModules(); + jest.clearAllMocks(); + }); + + it('resolves with the picked moment', async () => { + pick.mockResolvedValue(1_700_000_060_000); + + await expect(loadHandler()(options())).resolves.toEqual(new Date(1_700_000_060_000)); + expect(pick).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'date', value: 1_700_000_000_000 }), + ); + }); + + it('closes the picker when the signal aborts, and resolves with null', async () => { + let resolvePick: (value: number | null) => void = () => undefined; + pick.mockImplementation(() => new Promise((resolve) => (resolvePick = resolve))); + dismiss.mockImplementation(() => resolvePick(null)); + const controller = new AbortController(); + + const result = loadHandler()(options(controller.signal)); + controller.abort(); + + await expect(result).resolves.toBeNull(); + expect(dismiss).toHaveBeenCalledTimes(1); + }); + + it('opens nothing when the signal is already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + + await expect(loadHandler()(options(controller.signal))).resolves.toBeNull(); + expect(pick).not.toHaveBeenCalled(); + }); + + it('leaves the next picker alone when aborted after settling', async () => { + pick.mockResolvedValue(null); + const controller = new AbortController(); + + await loadHandler()(options(controller.signal)); + controller.abort(); + + expect(dismiss).not.toHaveBeenCalled(); + }); +}); diff --git a/package/native-package/src/handlers/index.ts b/package/native-package/src/handlers/index.ts index 83b0ed3ce3..966e4d795e 100644 --- a/package/native-package/src/handlers/index.ts +++ b/package/native-package/src/handlers/index.ts @@ -1,2 +1,3 @@ export * from './compressImage'; export * from './multipartUpload'; +export * from './pickDateTime'; diff --git a/package/native-package/src/handlers/pickDateTime.ts b/package/native-package/src/handlers/pickDateTime.ts new file mode 100644 index 0000000000..8bbb20a4ed --- /dev/null +++ b/package/native-package/src/handlers/pickDateTime.ts @@ -0,0 +1,37 @@ +import type { PickDateTime } from 'stream-chat-react-native-core'; + +import NativeStreamDateTimePicker from '../native/NativeStreamDateTimePicker'; + +/** + * Opens the system date or time picker. Resolves with the selected moment, or with `null` when the + * picker is cancelled, aborted through `signal`, or unavailable because the native module is absent. + */ +export const pickDateTime: PickDateTime = async ({ + cancelLabel, + confirmLabel, + maximumDate, + minimumDate, + mode, + signal, + value, +}) => { + const nativePicker = NativeStreamDateTimePicker; + if (!nativePicker || signal?.aborted) return null; + + // Only one picker is shown at a time, so dismissing the current picker closes this one. + const dismiss = () => nativePicker.dismiss(); + signal?.addEventListener('abort', dismiss); + try { + const picked = await nativePicker.pick({ + cancelLabel, + confirmLabel, + maximumDate: maximumDate?.getTime(), + minimumDate: minimumDate?.getTime(), + mode, + value: value.getTime(), + }); + return picked === null || signal?.aborted ? null : new Date(picked); + } finally { + signal?.removeEventListener('abort', dismiss); + } +}; diff --git a/package/native-package/src/index.js b/package/native-package/src/index.js index 5f99773b12..9114a6a39d 100644 --- a/package/native-package/src/index.js +++ b/package/native-package/src/index.js @@ -2,7 +2,7 @@ import { Platform } from 'react-native'; import { registerNativeHandlers } from 'stream-chat-react-native-core'; -import { compressImage, multipartUpload } from './handlers'; +import { compressImage, multipartUpload, pickDateTime } from './handlers'; import { Audio, @@ -40,6 +40,7 @@ export const defaultNativeHandlers = { NativeShimmerView, oniOS14GalleryLibrarySelectionChange, overrideAudioRecordingConfiguration, + pickDateTime, pickDocument, pickImage, saveFile, diff --git a/package/native-package/src/native/NativeStreamDateTimePicker.ts b/package/native-package/src/native/NativeStreamDateTimePicker.ts new file mode 100644 index 0000000000..8c0fd520c0 --- /dev/null +++ b/package/native-package/src/native/NativeStreamDateTimePicker.ts @@ -0,0 +1,31 @@ +import type { TurboModule } from 'react-native'; +import { TurboModuleRegistry } from 'react-native'; + +/** + * Codegen spec for the native date and time picker, backed by Material dialogs on Android and a + * `UIDatePicker` dialog on iOS. + * + * The spec exists in both `package/native-package/src/native` and `package/expo-package/src/native`, + * since codegen reads each package separately. Keep the two copies identical. + */ + +export type DateTimePickerOptions = { + /** Either `date` or `time`. */ + mode: string; + /** The moment the picker opens on, in milliseconds since the epoch. */ + value: number; + minimumDate?: number; + maximumDate?: number; + /** Translated labels for the iOS dialog buttons. The Android dialogs provide their own. */ + confirmLabel: string; + cancelLabel: string; +}; + +export interface Spec extends TurboModule { + /** Resolves with the selected moment in milliseconds, or null when the picker is cancelled. */ + pick(options: DateTimePickerOptions): Promise; + /** Dismisses the picker currently shown, which resolves its `pick` call with null. */ + dismiss(): void; +} + +export default TurboModuleRegistry.get('StreamDateTimePicker'); diff --git a/package/shared-native/android/StreamDateTimePicker.kt b/package/shared-native/android/StreamDateTimePicker.kt new file mode 100644 index 0000000000..cb813eddb2 --- /dev/null +++ b/package/shared-native/android/StreamDateTimePicker.kt @@ -0,0 +1,164 @@ +package com.streamchatreactnative.shared + +import android.app.Activity +import android.text.format.DateFormat +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import com.google.android.material.datepicker.CalendarConstraints +import com.google.android.material.datepicker.CompositeDateValidator +import com.google.android.material.datepicker.DateValidatorPointBackward +import com.google.android.material.datepicker.DateValidatorPointForward +import com.google.android.material.datepicker.MaterialDatePicker +import com.google.android.material.timepicker.MaterialTimePicker +import com.google.android.material.timepicker.TimeFormat +import java.lang.ref.WeakReference +import java.util.Calendar +import java.util.TimeZone + +/** + * Presents the Material date or time picker and reports the selected moment in milliseconds, or + * null when the picker is cancelled or cannot be shown. Each package passes its own theme ids. + */ +object StreamDateTimePicker { + private const val TAG = "StreamDateTimePicker" + private val utc: TimeZone = TimeZone.getTimeZone("UTC") + + // The picker whose result is still pending. It is cleared when the picker settles, so a picker + // requested right afterwards, such as the time after the date, can open during the exit animation. + private var active: WeakReference? = null + + data class Themes(val date: Int, val time: Int) + + fun pick( + activity: Activity?, + themes: Themes, + mode: String, + value: Long, + minimumDate: Long?, + maximumDate: Long?, + onResult: (Long?) -> Unit, + ) { + val host = activity as? FragmentActivity + if (host == null || host.isFinishing || host.isDestroyed) { + onResult(null) + return + } + + host.runOnUiThread { + val fragments = host.supportFragmentManager + // Only one picker is shown at a time, and none while the fragment manager has saved its state. + if (fragments.isStateSaved || active?.get() != null) { + onResult(null) + return@runOnUiThread + } + + var settled = false + var lifecycleObserver: LifecycleEventObserver? = null + val settle = { result: Long? -> + if (!settled) { + settled = true + active = null + lifecycleObserver?.let { host.lifecycle.removeObserver(it) } + onResult(result) + } + } + // The dialog is destroyed together with its activity, in which case the call resolves as cancelled. + lifecycleObserver = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_DESTROY) settle(null) + } + host.lifecycle.addObserver(lifecycleObserver) + + if (mode == "time") { + val current = localCalendar(value) + val picker = + MaterialTimePicker.Builder() + .setTheme(themes.time) + .setTimeFormat( + if (DateFormat.is24HourFormat(host)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H, + ) + .setInputMode(MaterialTimePicker.INPUT_MODE_KEYBOARD) + .setHour(current.get(Calendar.HOUR_OF_DAY)) + .setMinute(current.get(Calendar.MINUTE)) + .build() + picker.addOnPositiveButtonClickListener { + current.set(Calendar.HOUR_OF_DAY, picker.hour) + current.set(Calendar.MINUTE, picker.minute) + current.set(Calendar.SECOND, 0) + current.set(Calendar.MILLISECOND, 0) + settle(current.timeInMillis) + } + picker.addOnDismissListener { settle(null) } + active = WeakReference(picker) + picker.show(fragments, TAG) + return@runOnUiThread + } + + // MaterialDatePicker selections are UTC midnights, so only the calendar day is read from the + // selection and the time of day is preserved from `value`. + val validators = mutableListOf() + minimumDate?.let { validators.add(DateValidatorPointForward.from(utcMidnight(it))) } + maximumDate?.let { validators.add(DateValidatorPointBackward.before(utcMidnight(it))) } + val constraints = CalendarConstraints.Builder().setOpenAt(utcMidnight(value)) + if (validators.isNotEmpty()) { + constraints.setValidator(CompositeDateValidator.allOf(validators)) + } + + val picker = + MaterialDatePicker.Builder.datePicker() + .setTheme(themes.date) + .setSelection(utcMidnight(value)) + .setCalendarConstraints(constraints.build()) + .build() + picker.addOnPositiveButtonClickListener { selection -> + val picked = Calendar.getInstance(utc).apply { timeInMillis = selection } + val result = localCalendar(value) + result.set( + picked.get(Calendar.YEAR), + picked.get(Calendar.MONTH), + picked.get(Calendar.DAY_OF_MONTH), + ) + settle(result.timeInMillis) + } + picker.addOnDismissListener { settle(null) } + active = WeakReference(picker) + picker.show(fragments, TAG) + } + } + + /** Dismisses the picker currently shown, which resolves its call as cancelled. */ + fun dismissActive() { + val picker = active?.get() ?: return + picker.activity?.runOnUiThread { picker.dismissAllowingStateLoss() } + } + + /** + * Dismisses pickers the fragment manager restored after the activity was recreated, for example + * on rotation. Their calls have already resolved as cancelled and nothing observes them. + */ + fun dismissOrphans(activity: Activity?) { + val host = activity as? FragmentActivity ?: return + host.runOnUiThread { + val fragments = host.supportFragmentManager + if (fragments.isStateSaved) return@runOnUiThread + fragments.fragments + .filter { it.tag == TAG && it !== active?.get() } + .forEach { (it as? DialogFragment)?.dismissAllowingStateLoss() } + } + } + + private fun localCalendar(millis: Long): Calendar = + Calendar.getInstance().apply { timeInMillis = millis } + + /** Returns the UTC midnight of the local calendar day containing `millis`. */ + private fun utcMidnight(millis: Long): Long { + val local = localCalendar(millis) + return Calendar.getInstance(utc) + .apply { + clear() + set(local.get(Calendar.YEAR), local.get(Calendar.MONTH), local.get(Calendar.DAY_OF_MONTH)) + } + .timeInMillis + } +} diff --git a/package/shared-native/ios/StreamDateTimePicker.h b/package/shared-native/ios/StreamDateTimePicker.h new file mode 100644 index 0000000000..0a2f52c52f --- /dev/null +++ b/package/shared-native/ios/StreamDateTimePicker.h @@ -0,0 +1,20 @@ +#ifdef RCT_NEW_ARCH_ENABLED + +#if __has_include("StreamChatReactNativeSpec.h") +#import "StreamChatReactNativeSpec.h" +#elif __has_include("StreamChatExpoSpec.h") +#import "StreamChatExpoSpec.h" +#elif __has_include() +#import +#elif __has_include() +#import +#else +#error "Unable to find generated codegen spec header for StreamDateTimePicker." +#endif + +#import + +@interface StreamDateTimePicker : NSObject +@end + +#endif diff --git a/package/shared-native/ios/StreamDateTimePicker.mm b/package/shared-native/ios/StreamDateTimePicker.mm new file mode 100644 index 0000000000..d2095a2488 --- /dev/null +++ b/package/shared-native/ios/StreamDateTimePicker.mm @@ -0,0 +1,59 @@ +#import "StreamDateTimePicker.h" + +#ifdef RCT_NEW_ARCH_ENABLED + +#import + +#import "StreamDateTimePickerAPI.h" + +// Implemented in StreamDateTimePickerPresenter.swift. +@interface StreamDateTimePickerPresenter : NSObject +@end + +@implementation StreamDateTimePicker + +RCT_EXPORT_MODULE(StreamDateTimePicker) + +- (void)pick:(JS::NativeStreamDateTimePicker::DateTimePickerOptions &)options + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + NSNumber *minimumDate = options.minimumDate().has_value() ? @(options.minimumDate().value()) : nil; + NSNumber *maximumDate = options.maximumDate().has_value() ? @(options.maximumDate().value()) : nil; + + [StreamDateTimePickerPresenter presentWithMode:options.mode() + value:options.value() + minimumDate:minimumDate + maximumDate:maximumDate + confirmLabel:options.confirmLabel() + cancelLabel:options.cancelLabel() + presenter:^UIViewController * { + // The topmost controller that is not being dismissed, so the + // dialog also appears above a React Native . + return RCTPresentedViewController(); + } + completion:^(NSNumber *result) { + resolve(result ?: [NSNull null]); + }]; +} + +- (void)dismiss +{ + [StreamDateTimePickerPresenter dismissPresented]; +} + +// Dismisses a picker that is still shown when the module is invalidated, for example on reload. +- (void)invalidate +{ + [StreamDateTimePickerPresenter dismissPresented]; +} + +- (std::shared_ptr)getTurboModule: +(const facebook::react::ObjCTurboModule::InitParams &)params +{ + return std::make_shared(params); +} + +@end + +#endif diff --git a/package/shared-native/ios/StreamDateTimePickerPresenter.swift b/package/shared-native/ios/StreamDateTimePickerPresenter.swift new file mode 100644 index 0000000000..27a3e95fcf --- /dev/null +++ b/package/shared-native/ios/StreamDateTimePickerPresenter.swift @@ -0,0 +1,293 @@ +import UIKit +#if canImport(StreamChatNativeInterfaces) +import StreamChatNativeInterfaces +#endif + +/// Presents `UIDatePicker` in a centred card with confirm and cancel buttons, using the inline +/// calendar for dates and wheels for times. The card appears above any React Native content, +/// including a ``. Only one picker is shown at a time, and every call completes exactly once. +@objc(StreamDateTimePickerPresenter) +@objcMembers +public final class StreamDateTimePickerPresenter: NSObject { + private static weak var current: StreamDateTimePickerController? + /// The number of presentation attempts while the presenting controller is in a transition. + private static let maxPresentAttempts = 40 + + @objc(presentWithMode:value:minimumDate:maximumDate:confirmLabel:cancelLabel:presenter:completion:) + public static func present( + mode: String, + value: Double, + minimumDate: NSNumber?, + maximumDate: NSNumber?, + confirmLabel: String, + cancelLabel: String, + presenter: @escaping () -> UIViewController?, + completion: @escaping (NSNumber?) -> Void + ) { + DispatchQueue.main.async { + guard current == nil else { + completion(nil) + return + } + let controller = StreamDateTimePickerController( + mode: mode == "time" ? .time : .date, + value: Date(milliseconds: value), + minimumDate: minimumDate.map { Date(milliseconds: $0.doubleValue) }, + maximumDate: maximumDate.map { Date(milliseconds: $0.doubleValue) }, + confirmLabel: confirmLabel, + cancelLabel: cancelLabel, + completion: { result in + // Cleared before resolving, so a picker requested immediately afterwards can be presented. + current = nil + completion(result) + } + ) + current = controller + presentWhenReady(controller, presenter: presenter, attempt: 0) + } + } + + @objc(dismissPresented) + public static func dismissPresented() { + DispatchQueue.main.async { + current?.finish(with: nil) + } + } + + /// Presents the controller once `host` has no transition in progress, since UIKit refuses to + /// present over a controller that is being presented or dismissed. + private static func presentWhenReady( + _ controller: StreamDateTimePickerController, + presenter: @escaping () -> UIViewController?, + attempt: Int + ) { + guard current === controller else { return } + guard let host = presenter(), host.viewIfLoaded?.window != nil else { + controller.finish(with: nil) + return + } + let busy = host.isBeingPresented || host.isBeingDismissed || host.presentedViewController != nil + guard busy else { + host.present(controller, animated: false) + return + } + guard attempt < maxPresentAttempts else { + controller.finish(with: nil) + return + } + if let coordinator = host.transitionCoordinator { + coordinator.animate(alongsideTransition: nil) { _ in + presentWhenReady(controller, presenter: presenter, attempt: attempt + 1) + } + } else { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { + presentWhenReady(controller, presenter: presenter, attempt: attempt + 1) + } + } + } +} + +extension StreamDateTimePickerPresenter: StreamDateTimePickerPresenterAPI {} + +private extension Date { + init(milliseconds: Double) { + self.init(timeIntervalSince1970: milliseconds / 1000) + } + + var milliseconds: Double { timeIntervalSince1970 * 1000 } +} + +/// A dimmed backdrop with a card holding the picker and its buttons, animated in and out like a +/// system alert. It is presented `.overFullScreen`, so the presenting content stays in the window. +final class StreamDateTimePickerController: UIViewController { + private let mode: UIDatePicker.Mode + private let picker = UIDatePicker() + private let backdrop = UIView() + private let card = UIView() + private let confirmLabel: String + private let cancelLabel: String + private var completion: ((NSNumber?) -> Void)? + private let maxCardWidth: CGFloat = 400 + + init( + mode: UIDatePicker.Mode, + value: Date, + minimumDate: Date?, + maximumDate: Date?, + confirmLabel: String, + cancelLabel: String, + completion: @escaping (NSNumber?) -> Void + ) { + self.mode = mode + self.confirmLabel = confirmLabel + self.cancelLabel = cancelLabel + self.completion = completion + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = .overFullScreen + picker.datePickerMode = mode + picker.minimumDate = minimumDate + picker.maximumDate = maximumDate + picker.date = value + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) is not supported") + } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .clear + + backdrop.backgroundColor = UIColor.black.withAlphaComponent(0.4) + backdrop.translatesAutoresizingMaskIntoConstraints = false + backdrop.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cancel))) + view.addSubview(backdrop) + + // White in light mode and the elevated grey of system alerts in dark mode. + card.backgroundColor = UIColor { traits in + traits.userInterfaceStyle == .dark ? .secondarySystemBackground : .systemBackground + } + card.layer.cornerRadius = 32 + card.layer.cornerCurve = .continuous + card.layer.shadowColor = UIColor.black.cgColor + card.layer.shadowOpacity = 0.16 + card.layer.shadowOffset = CGSize(width: 0, height: 12) + card.layer.shadowRadius = 16 + card.translatesAutoresizingMaskIntoConstraints = false + card.accessibilityViewIsModal = true + view.addSubview(card) + + // The selection uses the label colour, as in the design, instead of the app tint. + picker.tintColor = .label + picker.preferredDatePickerStyle = mode == .time ? .wheels : .inline + picker.translatesAutoresizingMaskIntoConstraints = false + + let titleFont = UIConfigurationTextAttributesTransformer { attributes in + var attributes = attributes + attributes.font = UIFont.preferredFont(forTextStyle: .headline) + return attributes + } + + var confirmConfiguration = UIButton.Configuration.filled() + confirmConfiguration.title = confirmLabel + confirmConfiguration.cornerStyle = .capsule + confirmConfiguration.titleTextAttributesTransformer = titleFont + let confirmButton = UIButton(configuration: confirmConfiguration) + confirmButton.addTarget(self, action: #selector(confirmPicked), for: .primaryActionTriggered) + + var cancelConfiguration = UIButton.Configuration.bordered() + cancelConfiguration.title = cancelLabel + cancelConfiguration.cornerStyle = .capsule + cancelConfiguration.titleTextAttributesTransformer = titleFont + cancelConfiguration.baseForegroundColor = .label + cancelConfiguration.baseBackgroundColor = .clear + cancelConfiguration.background.strokeColor = .systemGray4 + cancelConfiguration.background.strokeWidth = 1 + let cancelButton = UIButton(configuration: cancelConfiguration) + cancelButton.addTarget(self, action: #selector(cancel), for: .primaryActionTriggered) + + let buttons = UIStackView(arrangedSubviews: [confirmButton, cancelButton]) + buttons.axis = .vertical + buttons.spacing = 8 + + let content = UIStackView(arrangedSubviews: [picker, buttons]) + content.axis = .vertical + content.spacing = 32 + content.translatesAutoresizingMaskIntoConstraints = false + card.addSubview(content) + + NSLayoutConstraint.activate([ + backdrop.topAnchor.constraint(equalTo: view.topAnchor), + backdrop.bottomAnchor.constraint(equalTo: view.bottomAnchor), + backdrop.leadingAnchor.constraint(equalTo: view.leadingAnchor), + backdrop.trailingAnchor.constraint(equalTo: view.trailingAnchor), + + card.centerXAnchor.constraint(equalTo: view.centerXAnchor), + card.centerYAnchor.constraint(equalTo: view.centerYAnchor), + card.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 24), + card.widthAnchor.constraint(lessThanOrEqualToConstant: maxCardWidth), + card.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor), + + content.topAnchor.constraint(equalTo: card.topAnchor, constant: 32), + content.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -24), + content.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 24), + content.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -24), + + confirmButton.heightAnchor.constraint(equalToConstant: 48), + cancelButton.heightAnchor.constraint(equalToConstant: 48), + ]) + // Fills the available width, up to a phone-sized maximum on larger screens. + let preferredWidth = card.widthAnchor.constraint(equalToConstant: maxCardWidth) + preferredWidth.priority = .defaultHigh + preferredWidth.isActive = true + + backdrop.alpha = 0 + card.alpha = 0 + card.transform = CGAffineTransform(scaleX: 1.08, y: 1.08) + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + // An explicit shadow path avoids an offscreen rendering pass. + card.layer.shadowPath = UIBezierPath( + roundedRect: card.bounds, + cornerRadius: card.layer.cornerRadius + ).cgPath + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseOut, .allowUserInteraction]) { + self.backdrop.alpha = 1 + self.card.alpha = 1 + self.card.transform = .identity + } + UIAccessibility.post(notification: .screenChanged, argument: card) + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + // When a controller underneath is dismissed, for example a modal closed from JS, UIKit removes + // this dialog without calling `finish`, so the call is resolved as cancelled here. A controller + // presented on top only covers the dialog and is ignored. + DispatchQueue.main.async { + guard self.completion != nil, self.presentedViewController == nil else { return } + guard self.presentingViewController == nil || self.view.window == nil else { return } + self.finish(with: nil) + } + } + + override func accessibilityPerformEscape() -> Bool { + cancel() + return true + } + + @objc private func confirmPicked() { + finish(with: NSNumber(value: picker.date.milliseconds)) + } + + @objc private func cancel() { + finish(with: nil) + } + + /// Animates the dialog out, dismisses it and calls the completion. Subsequent calls do nothing. + func finish(with result: NSNumber?) { + guard let completion else { return } + self.completion = nil + view.isUserInteractionEnabled = false + + let complete = { completion(result) } + guard presentingViewController != nil else { + complete() + return + } + UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseIn]) { + self.backdrop.alpha = 0 + self.card.alpha = 0 + self.card.transform = CGAffineTransform(scaleX: 0.95, y: 0.95) + } completion: { _ in + self.dismiss(animated: false, completion: complete) + } + } +} diff --git a/package/shared-native/ios/interfaces/include/StreamDateTimePickerAPI.h b/package/shared-native/ios/interfaces/include/StreamDateTimePickerAPI.h new file mode 100644 index 0000000000..f00014da24 --- /dev/null +++ b/package/shared-native/ios/interfaces/include/StreamDateTimePickerAPI.h @@ -0,0 +1,26 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +/// The interface through which `StreamDateTimePicker.mm` reaches the Swift +/// `StreamDateTimePickerPresenter`. +@protocol StreamDateTimePickerPresenterAPI + +/// Presents the picker above the controller returned by `presenter` and calls `completion` once, +/// with the selected moment in milliseconds or nil when the picker is cancelled or cannot be shown. ++ (void)presentWithMode:(NSString *)mode + value:(double)value + minimumDate:(nullable NSNumber *)minimumDate + maximumDate:(nullable NSNumber *)maximumDate + confirmLabel:(NSString *)confirmLabel + cancelLabel:(NSString *)cancelLabel + presenter:(UIViewController *_Nullable (^)(void))presenter + completion:(void (^)(NSNumber *_Nullable result))completion + NS_SWIFT_NAME(present(mode:value:minimumDate:maximumDate:confirmLabel:cancelLabel:presenter:completion:)); + +/// Dismisses a picker that is still shown, which resolves it as cancelled. ++ (void)dismissPresented NS_SWIFT_NAME(dismissPresented()); + +@end + +NS_ASSUME_NONNULL_END diff --git a/package/src/components/Channel/ChannelShell.tsx b/package/src/components/Channel/ChannelShell.tsx index 81962b36e6..8c4b0f32cb 100644 --- a/package/src/components/Channel/ChannelShell.tsx +++ b/package/src/components/Channel/ChannelShell.tsx @@ -189,6 +189,7 @@ export type ChannelConfigProps = Partial< | 'messageSwipeToReplyHitSlop' | 'myMessageTheme' | 'onAlsoSentToChannelHeaderPress' + | 'onScheduledMessagesBannerPress' | 'onLongPressMessage' | 'onPressInMessage' | 'onPressMessage' @@ -339,6 +340,7 @@ export const ChannelShell = (props: PropsWithChildren) => { onPressInMessage, onPressMessage, onAlsoSentToChannelHeaderPress, + onScheduledMessagesBannerPress, openPollCreationDialog, overrideOwnCapabilities, reactionListPosition = 'top', @@ -499,6 +501,7 @@ export const ChannelShell = (props: PropsWithChildren) => { myMessageTheme, onAlsoSentToChannelHeaderPress, onLongPressMessage, + onScheduledMessagesBannerPress, onPressInMessage, onPressMessage, reactionListPosition, @@ -532,7 +535,9 @@ export const ChannelShell = (props: PropsWithChildren) => { {initializeOnMount ? : null} - {children} + + {children} + {shouldRenderAttachmentPicker ? : null} diff --git a/package/src/components/Channel/hooks/useCreateMessagesContext.ts b/package/src/components/Channel/hooks/useCreateMessagesContext.ts index 0698f87a9d..8121ee961a 100644 --- a/package/src/components/Channel/hooks/useCreateMessagesContext.ts +++ b/package/src/components/Channel/hooks/useCreateMessagesContext.ts @@ -39,6 +39,7 @@ export const useCreateMessagesContext = ({ myMessageTheme, onAlsoSentToChannelHeaderPress, onLongPressMessage, + onScheduledMessagesBannerPress, onPressInMessage, onPressMessage, reactionListPosition, @@ -93,6 +94,7 @@ export const useCreateMessagesContext = ({ myMessageTheme, onAlsoSentToChannelHeaderPress, onLongPressMessage, + onScheduledMessagesBannerPress, onPressInMessage, onPressMessage, reactionListPosition, diff --git a/package/src/components/ChannelDetails/__tests__/ChannelDetailsNavigationSection.test.tsx b/package/src/components/ChannelDetails/__tests__/ChannelDetailsNavigationSection.test.tsx index 8963236ca2..7788e8148a 100644 --- a/package/src/components/ChannelDetails/__tests__/ChannelDetailsNavigationSection.test.tsx +++ b/package/src/components/ChannelDetails/__tests__/ChannelDetailsNavigationSection.test.tsx @@ -71,7 +71,13 @@ jest.mock('../../ImageGallery/ImageGallery', () => { }); const renderSection = ( - { getNavigationItems }: { getNavigationItems?: GetChannelDetailsNavigationItems } = {}, + { + channel, + getNavigationItems, + }: { + channel?: ChannelDetailsContextValue['channel']; + getNavigationItems?: GetChannelDetailsNavigationItems; + } = {}, overlay: Overlay = 'none', ) => { const overlayContextValue: OverlayContextValue = { @@ -94,9 +100,7 @@ const renderSection = ( }} > - + @@ -111,6 +115,45 @@ describe('ChannelDetailsNavigationSection', () => { pinnedListProbe.length = 0; }); + describe('scheduled messages row', () => { + const channel = { + scheduledMessagesEnabled: true, + } as unknown as ChannelDetailsContextValue['channel']; + + it('is left out until the app routes it, since it has no built-in modal', () => { + const { queryByTestId } = renderSection({ channel }); + + expect(queryByTestId('channel-details-scheduled-messages')).toBeNull(); + }); + + it('is shown and opens the route once the app sets its onPress', () => { + const onPress = jest.fn(); + const { getByTestId } = renderSection({ + channel, + getNavigationItems: ({ defaultItems }) => + defaultItems.map((item) => + item.section === 'scheduled-messages' ? { ...item, onPress } : item, + ), + }); + + fireEvent.press(getByTestId('channel-details-scheduled-messages')); + + expect(onPress).toHaveBeenCalledTimes(1); + }); + + it('is left out where the user cannot schedule messages, even when routed', () => { + const { queryByTestId } = renderSection({ + channel: { + scheduledMessagesEnabled: false, + } as unknown as ChannelDetailsContextValue['channel'], + getNavigationItems: ({ defaultItems }) => + defaultItems.map((item) => ({ ...item, onPress: jest.fn() })), + }); + + expect(queryByTestId('channel-details-scheduled-messages')).toBeNull(); + }); + }); + it('renders the three navigation rows with their labels and testIDs', () => { const { getByTestId } = renderSection(); diff --git a/package/src/components/ChannelDetails/hooks/useChannelDetailsNavigationItems.ts b/package/src/components/ChannelDetails/hooks/useChannelDetailsNavigationItems.ts index 1b2b20c6e7..58861347f2 100644 --- a/package/src/components/ChannelDetails/hooks/useChannelDetailsNavigationItems.ts +++ b/package/src/components/ChannelDetails/hooks/useChannelDetailsNavigationItems.ts @@ -1,8 +1,10 @@ import React, { useMemo } from 'react'; +import { useChannelDetailsContext } from '../../../contexts/channelDetailsContext/channelDetailsContext'; import { useComponentsContext } from '../../../contexts/componentsContext/ComponentsContext'; import type { TranslationContextValue } from '../../../contexts/translationContext/TranslationContext'; import { useTranslationContext } from '../../../contexts/translationContext/TranslationContext'; +import { useCanScheduleMessages } from '../../../hooks/useCanScheduleMessages'; import { asDynamicKey } from '../../../i18n/utils'; import type { IconProps } from '../../../icons/utils/base'; @@ -12,6 +14,7 @@ import type { IconProps } from '../../../icons/utils/base'; */ export type ChannelDetailsNavigationSectionType = | 'pinned-messages' + | 'scheduled-messages' | 'photos-and-videos' | 'files' | string; @@ -24,7 +27,10 @@ export type ChannelDetailsNavigationItem = { label: string; /** The section this row represents. */ section: ChannelDetailsNavigationSectionType; - /** Fired when the row is tapped. When unset, the row opens the built-in modal for its section. */ + /** + * Fired when the row is tapped. When unset, the row opens the built-in modal for its section, + * except `scheduled-messages`, which has none and is left out until this is set. + */ onPress?: () => void; }; @@ -33,10 +39,14 @@ export type ChannelDetailsNavigationItem = { * The declaration order is the order of the rows. */ const SECTION_CONFIG: Record< - 'pinned-messages' | 'photos-and-videos' | 'files', - { icon: 'Pin' | 'Picture' | 'Folder'; label: string } + 'pinned-messages' | 'scheduled-messages' | 'photos-and-videos' | 'files', + { icon: 'Pin' | 'Time' | 'Picture' | 'Folder'; label: string } > = { 'pinned-messages': { icon: 'Pin', label: 'channelDetails.navigation.pinnedMessages.label' }, + 'scheduled-messages': { + icon: 'Time', + label: 'channelDetails.navigation.scheduledMessages.label', + }, 'photos-and-videos': { icon: 'Picture', label: 'channelDetails.navigation.photosAndVideos.label', @@ -53,7 +63,9 @@ export type ChannelDetailsNavigationItemsContext = { /** * Customizes the rows rendered by `ChannelDetailsNavigationSection`. Receives the built-in * `defaultItems` (and a `context`) and returns the rows to render. Set a row's `onPress` to route - * it elsewhere, or add and remove rows. A row without `onPress` opens the built-in modal. + * it elsewhere, or add and remove rows. A row without `onPress` opens the built-in modal, except + * `scheduled-messages`, which is shown only with an `onPress` that opens a screen rendering + * `ChannelScheduledMessages` inside a `Channel`. */ export type GetChannelDetailsNavigationItems = (params: { context: ChannelDetailsNavigationItemsContext; @@ -78,21 +90,30 @@ export const useChannelDetailsNavigationItems = ({ } = {}): ChannelDetailsNavigationItem[] => { const { icons } = useComponentsContext(); const { t } = useTranslationContext(); + const { channel } = useChannelDetailsContext(); + const showScheduledMessages = useCanScheduleMessages(channel); const context = useMemo(() => ({ t }), [t]); const defaultItems = useMemo( () => - SECTIONS.map((section) => { - const { icon, label } = SECTION_CONFIG[section]; - // The label key comes from `SECTION_CONFIG`, so it is only known at runtime. - return { Icon: icons[icon], label: t(asDynamicKey(label)), section }; - }), - [icons, t], + SECTIONS.filter((section) => section !== 'scheduled-messages' || showScheduledMessages).map( + (section) => { + const { icon, label } = SECTION_CONFIG[section]; + // The label key comes from `SECTION_CONFIG`, so it is only known at runtime. + return { Icon: icons[icon], label: t(asDynamicKey(label)), section }; + }, + ), + [icons, showScheduledMessages, t], ); + // Editing a scheduled message needs the app's own `Channel`, so there is no built-in modal for + // it and the row is shown only once the app routes it. return useMemo( - () => getNavigationItems({ context, defaultItems }), + () => + getNavigationItems({ context, defaultItems }).filter( + (item) => item.section !== 'scheduled-messages' || item.onPress, + ), [context, defaultItems, getNavigationItems], ); }; diff --git a/package/src/components/Chat/Chat.tsx b/package/src/components/Chat/Chat.tsx index 547ea99cbc..b5fa582bf4 100644 --- a/package/src/components/Chat/Chat.tsx +++ b/package/src/components/Chat/Chat.tsx @@ -209,12 +209,14 @@ const ChatWithContext = (props: PropsWithChildren) => { client.polls.registerSubscriptions(); client.reminders.registerSubscriptions(); client.reminders.initTimers(); + client.scheduledMessagePaginators.registerSubscriptions(); return () => { client.threads.unregisterSubscriptions(); client.polls.unregisterSubscriptions(); client.reminders.unregisterSubscriptions(); client.reminders.clearTimers(); + client.scheduledMessagePaginators.unregisterSubscriptions(); }; }, [client]); diff --git a/package/src/components/MessageInput/MessageComposer.tsx b/package/src/components/MessageInput/MessageComposer.tsx index 2bb0ad7eac..848fef9d63 100644 --- a/package/src/components/MessageInput/MessageComposer.tsx +++ b/package/src/components/MessageInput/MessageComposer.tsx @@ -218,6 +218,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { MessageComposerTrailingView, MessageInputHeaderView, MessageInputTrailingView, + ScheduleMessageSheet, } = useComponentsContext(); const styles = useStyles(); @@ -343,7 +344,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { style={{ paddingBottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + ? attachmentPickerBottomSheetHeight + bottomInset : 0, }} /> @@ -356,7 +357,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { { bottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + BOTTOM_OFFSET + ? attachmentPickerBottomSheetHeight + bottomInset + BOTTOM_OFFSET : BOTTOM_OFFSET, }, floatingWrapper, @@ -372,10 +373,12 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { layout: { height: newHeight }, }, }) => { + // Only the docked wrapper pads itself for the open picker. The floating composer is + // lifted by a spacer outside this view, so its measured height is already its own. messageInputHeightStore.setHeight( newHeight - - (selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + (!messageInputFloating && selectedPicker && !isKeyboardVisible + ? attachmentPickerBottomSheetHeight + bottomInset : 0), ); }} @@ -390,12 +393,13 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { borderTopColor: semantics.borderCoreSubtle, paddingBottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + BOTTOM_OFFSET + ? attachmentPickerBottomSheetHeight + bottomInset + BOTTOM_OFFSET : BOTTOM_OFFSET, }, wrapper, ] } + testID='message-composer-measured-view' > {Input ? ( @@ -469,6 +473,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { /> ) : null} + ); }; diff --git a/package/src/components/MessageInput/MessageInputHeaderView.tsx b/package/src/components/MessageInput/MessageInputHeaderView.tsx index c24d1c6fad..522eade2f5 100644 --- a/package/src/components/MessageInput/MessageInputHeaderView.tsx +++ b/package/src/components/MessageInput/MessageInputHeaderView.tsx @@ -1,8 +1,10 @@ -import React, { useCallback } from 'react'; +import React, { useCallback, useMemo } from 'react'; import { StyleSheet } from 'react-native'; import Animated from 'react-native-reanimated'; +import { toScheduledMessagePreview } from 'stream-chat'; + import { LinkPreviewList } from './components/LinkPreviewList'; import { useHasLinkPreviews } from './hooks/useLinkPreviews'; @@ -18,6 +20,9 @@ import { useTheme } from '../../contexts/themeContext/ThemeContext'; import { useStateStore } from '../../hooks/useStateStore'; import { primitives } from '../../theme'; import { transitions } from '../../utils/animations/transitions'; +import { useEditedScheduledMessage } from '../ScheduledMessages/hooks/useEditedScheduledMessage'; +import { QuoteDeletedNotice } from '../ScheduledMessages/QuoteDeletedNotice'; +import { isDeletedQuotedMessage } from '../ScheduledMessages/utils/quote'; export const MessageInputHeaderView = () => { const { @@ -26,8 +31,17 @@ export const MessageInputHeaderView = () => { }, } = useTheme(); const messageComposer = useMessageComposer(); - const editing = !!messageComposer.editedMessage; + const { editedScheduledMessage } = useEditedScheduledMessage(); + const editingScheduled = !!editedScheduledMessage; + const editing = !!messageComposer.editedMessage || editingScheduled; const { clearEditingState } = useMessageComposerAPIContext(); + const scheduledMessagePreview = useMemo( + () => (editedScheduledMessage ? toScheduledMessagePreview(editedScheduledMessage) : undefined), + [editedScheduledMessage], + ); + const onDismissScheduledEdit = useCallback(() => { + messageComposer.cancelScheduledMessageEdit(); + }, [messageComposer]); const { quotedMessage } = useStateStore(messageComposer.state, messageComposerStateStoreSelector); const hasLinkPreviews = useHasLinkPreviews(); const { audioRecorderManager } = useMessageInputContext(); @@ -55,7 +69,15 @@ export const MessageInputHeaderView = () => { contentContainer, ]} > - {editing ? ( + {editingScheduled ? ( + + + + ) : editing ? ( { /> ) : null} + {editingScheduled && isDeletedQuotedMessage(quotedMessage) ? ( + + + + ) : null} {quotedMessage && !editing ? ( diff --git a/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx b/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx index f74062e077..cb91110e10 100644 --- a/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx +++ b/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx @@ -1,12 +1,13 @@ import React from 'react'; -import { Alert } from 'react-native'; +import { Alert, StyleSheet } from 'react-native'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react-native'; import type { Channel as ChannelType, StreamChat, UserResponse } from 'stream-chat'; import * as AttachmentPickerUtils from '../../../contexts/attachmentPickerContext/AttachmentPickerContext'; import { WithComponents } from '../../../contexts/componentsContext/ComponentsContext'; +import { useMessageInputContext } from '../../../contexts/messageInputContext/MessageInputContext'; import { OverlayProvider } from '../../../contexts/overlayContext/OverlayProvider'; import { initiateClientWithChannels } from '../../../mock-builders/api/initiateClientWithChannels'; @@ -14,6 +15,7 @@ import { generateMember } from '../../../mock-builders/generator/member'; import { generateUser } from '../../../mock-builders/generator/user'; import { AttachmentPickerStore } from '../../../state-store/attachment-picker-store'; +import type { MessageInputHeightStore } from '../../../state-store/message-input-height-store'; import { AttachmentPickerContent } from '../../AttachmentPicker/components/AttachmentPickerContent'; import { AttachmentPickerSelectionBar } from '../../AttachmentPicker/components/AttachmentPickerSelectionBar'; import type { ChannelProps } from '../../Channel/Channel'; @@ -22,6 +24,7 @@ import { Chat } from '../../Chat/Chat'; import { MessageComposer } from '../MessageComposer'; jest.spyOn(Alert, 'alert'); +let attachmentPickerContextOverrides: Record = {}; jest.spyOn(AttachmentPickerUtils, 'useAttachmentPickerContext').mockImplementation(() => { const attachmentPickerStore = new AttachmentPickerStore(); attachmentPickerStore.setSelectedPicker('images'); @@ -33,6 +36,7 @@ jest.spyOn(AttachmentPickerUtils, 'useAttachmentPickerContext').mockImplementati setBottomInset: jest.fn(), setTopInset: jest.fn(), attachmentPickerStore, + ...attachmentPickerContextOverrides, } as unknown as ReturnType; }); @@ -69,11 +73,65 @@ describe('MessageComposer', () => { }); afterEach(() => { + attachmentPickerContextOverrides = {}; act(() => { channel.messageComposer.clear(); }); }); + // The picker is lifted by the bottom inset, so the composer rises above both. + it('rises above the picker and the bottom inset', () => { + attachmentPickerContextOverrides = { attachmentPickerBottomSheetHeight: 300, bottomInset: 80 }; + renderComponent({ channelProps: { channel }, client, props: {} }); + + const paddings = screen.UNSAFE_root.findAll( + (node) => typeof node.type === 'string' && node.props.style !== undefined, + ).map((node) => StyleSheet.flatten(node.props.style)?.paddingBottom); + + expect(paddings).toContain(300 + 80 + 16); + expect(paddings).not.toContain(300 - 80 + 16); + }); + + describe('measured height while the picker is open', () => { + // Lays out the composer's measured view at `height` and returns the height it stored. + const measure = (messageInputFloating: boolean, height: number) => { + attachmentPickerContextOverrides = { + attachmentPickerBottomSheetHeight: 300, + bottomInset: 80, + }; + let heightStore: MessageInputHeightStore | undefined; + const HeightProbe = () => { + heightStore = useMessageInputContext().messageInputHeightStore; + return null; + }; + render( + + + + + + + + , + ); + const layout = { + nativeEvent: { layout: { height, width: 400, x: 0, y: 0 } }, + }; + const measuredView = screen.getByTestId('message-composer-measured-view'); + act(() => measuredView.props.onLayout(layout)); + return heightStore?.store.getLatestValue().height; + }; + + it('leaves out the picker space the docked composer pads itself with', () => { + expect(measure(false, 456)).toBe(456 - 300 - 80); + }); + + // The floating composer is lifted by a spacer outside the measured view. + it('keeps the floating composer at its measured height', () => { + expect(measure(true, 76)).toBe(76); + }); + }); + // Mention candidates are read from the channel when `Input` asks for them. A member added after mount // (or a presence / user update, which republishes members) must not leave them stale. it('gives Input the current members as mention candidates', async () => { diff --git a/package/src/components/MessageInput/__tests__/__snapshots__/AttachButton.test.tsx.snap b/package/src/components/MessageInput/__tests__/__snapshots__/AttachButton.test.tsx.snap index a7f0495e78..1471937239 100644 --- a/package/src/components/MessageInput/__tests__/__snapshots__/AttachButton.test.tsx.snap +++ b/package/src/components/MessageInput/__tests__/__snapshots__/AttachButton.test.tsx.snap @@ -12,6 +12,7 @@ exports[`AttachButton should call handleAttachButtonPress when the button is cli } > ; export type InputButtonsWithContextProps = Pick< MessageInputContextValue, - 'hasCameraPicker' | 'hasCommands' | 'hasFilePicker' | 'hasImagePicker' + 'hasCameraPicker' | 'hasCommands' | 'hasFilePicker' | 'hasImagePicker' | 'messageInputFloating' > & Pick; @@ -34,6 +35,7 @@ export const InputButtonsWithContext = (props: InputButtonsWithContextProps) => hasCommands, hasFilePicker, hasImagePicker, + messageInputFloating, uploadFile: ownCapabilitiesUploadFile, } = props; const { AttachButton } = useComponentsContext(); @@ -44,8 +46,10 @@ export const InputButtonsWithContext = (props: InputButtonsWithContextProps) => const { theme: { messageComposer: { attachButtonContainer }, + semantics, }, } = useTheme(); + const scheme = useColorScheme(); useEffect(() => { rotation.value = withTiming(selectedPicker !== undefined ? 45 : 0, { duration: 200 }); @@ -63,7 +67,19 @@ export const InputButtonsWithContext = (props: InputButtonsWithContextProps) => } return hasAttachmentUploadCapabilities && !command ? ( - + @@ -91,7 +107,11 @@ const areEqual = ( uploadFile: nextUploadFile, } = nextProps; - if (prevHasCommands !== nextHasCommands || prevUploadFile !== nextUploadFile) { + if ( + prevHasCommands !== nextHasCommands || + prevUploadFile !== nextUploadFile || + prevProps.messageInputFloating !== nextProps.messageInputFloating + ) { return false; } @@ -116,7 +136,8 @@ const MemoizedInputButtonsWithContext = React.memo( ) as typeof InputButtonsWithContext; export const InputButtons = (props: InputButtonsProps) => { - const { hasCameraPicker, hasCommands, hasFilePicker, hasImagePicker } = useMessageInputContext(); + const { hasCameraPicker, hasCommands, hasFilePicker, hasImagePicker, messageInputFloating } = + useMessageInputContext(); const { uploadFile } = useOwnCapabilitiesContext(); return ( @@ -126,6 +147,7 @@ export const InputButtons = (props: InputButtonsProps) => { hasCommands, hasFilePicker, hasImagePicker, + messageInputFloating, uploadFile, }} {...props} @@ -135,4 +157,7 @@ export const InputButtons = (props: InputButtonsProps) => { const styles = StyleSheet.create({ attachButtonContainer: {}, + floatingContainer: { + borderRadius: primitives.radiusMax, + }, }); diff --git a/package/src/components/MessageInput/components/OutputButtons/SendButton.tsx b/package/src/components/MessageInput/components/OutputButtons/SendButton.tsx index 2babe3c34f..3709cd39fa 100644 --- a/package/src/components/MessageInput/components/OutputButtons/SendButton.tsx +++ b/package/src/components/MessageInput/components/OutputButtons/SendButton.tsx @@ -1,5 +1,6 @@ import React, { useCallback } from 'react'; +import { useChannelContext } from '../../../../contexts/channelContext/ChannelContext'; import { useComponentsContext } from '../../../../contexts/componentsContext/ComponentsContext'; import { MessageInputContextValue, @@ -15,8 +16,10 @@ export type SendButtonProps = Partial { const { disabled = false, sendMessage: propsSendMessage } = props; const { icons } = useComponentsContext(); - const { sendMessage: sendMessageFromContext } = useMessageInputContext(); + const { openScheduleSheet, sendMessage: sendMessageFromContext } = useMessageInputContext(); const sendMessage = propsSendMessage || sendMessageFromContext; + const { channel } = useChannelContext(); + const canSchedule = !disabled && channel?.scheduledMessagesEnabled; const onPressHandler = useCallback(() => { if (disabled) { @@ -32,6 +35,7 @@ export const SendButton = (props: SendButtonProps) => { type='solid' disabled={disabled} LeadingIcon={icons.SendRight} + onLongPress={canSchedule ? openScheduleSheet : undefined} onPress={onPressHandler} size='sm' testID='send-button' diff --git a/package/src/components/MessageInput/components/OutputButtons/index.tsx b/package/src/components/MessageInput/components/OutputButtons/index.tsx index 18ca6b4bbe..495cb67eca 100644 --- a/package/src/components/MessageInput/components/OutputButtons/index.tsx +++ b/package/src/components/MessageInput/components/OutputButtons/index.tsx @@ -23,6 +23,8 @@ import { useStateStore } from '../../../../hooks/useStateStore'; import { transitions } from '../../../../utils/animations/transitions'; import { AIStates, useAIState } from '../../../AITypingIndicatorView'; import { useSettledWSConnectionHealth } from '../../../Chat/hooks/useWSConnectionState'; +import { useEditedScheduledMessage } from '../../../ScheduledMessages/hooks/useEditedScheduledMessage'; +import { ScheduledMessageSaveButton } from '../../../ScheduledMessages/ScheduledMessageSaveButton'; import { useIsCooldownActive } from '../../hooks/useIsCooldownActive'; export type OutputButtonsProps = Partial; @@ -64,7 +66,8 @@ export const OutputButtonsWithContext = (props: OutputButtonsWithContextProps) = } = useTheme(); const messageComposer = useMessageComposer(); - const editing = !!messageComposer.editedMessage; + const { editedScheduledMessage } = useEditedScheduledMessage(); + const editing = !!messageComposer.editedMessage || !!editedScheduledMessage; const { textComposer } = messageComposer; const { command, textIsEmpty } = useStateStore(textComposer.state, textComposerStateSelector); const hasSendableData = useMessageComposerHasSendableData(); @@ -85,7 +88,11 @@ export const OutputButtonsWithContext = (props: OutputButtonsWithContextProps) = key='edit-button' style={editButtonContainer} > - + {editedScheduledMessage ? ( + + ) : ( + + )} ); } else if (cooldownIsActive) { diff --git a/package/src/components/MessageList/MessageFlashList.tsx b/package/src/components/MessageList/MessageFlashList.tsx index d8587a0256..0dd5f8e2e5 100644 --- a/package/src/components/MessageList/MessageFlashList.tsx +++ b/package/src/components/MessageList/MessageFlashList.tsx @@ -87,10 +87,18 @@ const flatListViewabilityConfig: ViewabilityConfig = { viewAreaCoveragePercentThreshold: 1, }; -const messageInputHeightStoreSelector = (state: MessageInputHeightState) => ({ +const floatingComposerSelector = (state: MessageInputHeightState) => ({ + bannerHeight: state.bannerHeight, height: state.height, }); +// A fixed composer sits below the list, so the list doesn't follow its height and isn't rendered +// again when the keyboard changes it. +const fixedComposerSelector = (state: MessageInputHeightState) => ({ + bannerHeight: state.bannerHeight, + height: 0, +}); + type MessageFlashListPropsWithContext = Pick< AttachmentPickerContextValue, 'closePicker' | 'attachmentPickerStore' @@ -268,6 +276,7 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => MessageListLoadingIndicator: LoadingIndicator, NetworkDownIndicator, NotificationList, + ScheduledMessagesBanner, ScrollToBottomButton, StickyHeader, TypingIndicator, @@ -276,9 +285,9 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => } = useComponentsContext(); const flashListRef = useRef | null>(null); - const { height: messageInputHeight } = useStateStore( + const { bannerHeight, height: messageInputHeight } = useStateStore( messageInputHeightStore.store, - messageInputHeightStoreSelector, + messageInputFloating ? floatingComposerSelector : fixedComposerSelector, ); const paginator = thread ? thread.messagePaginator : channel.messagePaginator; @@ -554,7 +563,9 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => const visibleLength = nativeEvent.layoutMeasurement.height; const contentLength = nativeEvent.contentSize.height; - const isScrollAtBottom = contentLength - visibleLength - offset < messageInputHeight; + const isScrollAtBottom = + contentLength - visibleLength - offset < + messageInputHeightStore.store.getLatestValue().height; // The scroll-to-bottom button shows unless the list is at the bottom with no newer messages. setScrollToBottomButtonVisible( @@ -640,14 +651,15 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => const flatListContentContainerStyle = useMemo( () => [ styles.contentContainer, - { paddingBottom: messageInputFloating ? messageInputHeight : 0 }, + { paddingBottom: (messageInputFloating ? messageInputHeight : 0) + bannerHeight }, additionalFlashListProps?.contentContainerStyle, ], [ additionalFlashListProps?.contentContainerStyle, - styles.contentContainer, + bannerHeight, messageInputFloating, messageInputHeight, + styles.contentContainer, ], ); @@ -774,9 +786,10 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => style={[ styles.scrollToBottomButtonContainer, { - bottom: messageInputFloating - ? messageInputHeight + primitives.spacingMd - : primitives.spacingMd, + bottom: + (messageInputFloating + ? messageInputHeight + primitives.spacingMd + : primitives.spacingMd) + bannerHeight, }, ]} > @@ -794,6 +807,23 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => /> ) : null} + {ScheduledMessagesBanner ? ( + + + + + + ) : null} @@ -932,6 +964,10 @@ const useStyles = () => { return useMemo( () => StyleSheet.create({ + scheduledMessagesBannerContainer: { + position: 'absolute', + width: '100%', + }, suggestionsListContainer: { backgroundColor: 'transparent', position: 'absolute', diff --git a/package/src/components/MessageList/MessageList.tsx b/package/src/components/MessageList/MessageList.tsx index eb7df10831..06c3276c42 100644 --- a/package/src/components/MessageList/MessageList.tsx +++ b/package/src/components/MessageList/MessageList.tsx @@ -110,6 +110,10 @@ const useStyles = () => { return useMemo( () => StyleSheet.create({ + scheduledMessagesBannerContainer: { + position: 'absolute', + width: '100%', + }, suggestionsListContainer: { backgroundColor: 'transparent', position: 'absolute', @@ -230,10 +234,18 @@ type MessageListPropsWithContext = Pick< animateLayout?: boolean; }; -const messageInputHeightStoreSelector = (state: MessageInputHeightState) => ({ +const floatingComposerSelector = (state: MessageInputHeightState) => ({ + bannerHeight: state.bannerHeight, height: state.height, }); +// A fixed composer sits below the list, so the list doesn't follow its height and isn't rendered +// again when the keyboard changes it. +const fixedComposerSelector = (state: MessageInputHeightState) => ({ + bannerHeight: state.bannerHeight, + height: 0, +}); + /** Renders the list of messages in a FlatList. */ const MessageListWithContext = (props: MessageListPropsWithContext) => { const { @@ -272,6 +284,7 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { MessageListLoadingIndicator: LoadingIndicator, NetworkDownIndicator, NotificationList, + ScheduledMessagesBanner, ScrollToBottomButton, StickyHeader, TypingIndicator, @@ -281,9 +294,9 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { } = useComponentsContext(); const { theme } = useTheme(); const styles = useStyles(); - const { height: messageInputHeight } = useStateStore( + const { bannerHeight, height: messageInputHeight } = useStateStore( messageInputHeightStore.store, - messageInputHeightStoreSelector, + messageInputFloating ? floatingComposerSelector : fixedComposerSelector, ); const paginator = thread ? thread.messagePaginator : channel.messagePaginator; @@ -563,7 +576,7 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { const handleScroll: ScrollViewProps['onScroll'] = useStableCallback((event) => { const messageListHasMessages = processedMessageList.length > 0; const offset = event.nativeEvent.contentOffset.y; - const isScrollAtBottom = offset <= messageInputHeight; + const isScrollAtBottom = offset <= messageInputHeightStore.store.getLatestValue().height; // The scroll-to-bottom button shows unless the list is at the bottom with no newer messages. setScrollToBottomButtonVisible( @@ -695,15 +708,17 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { const flatListContentContainerStyle = useMemo( () => [ - { paddingTop: messageInputFloating ? messageInputHeight : 0 }, + // The banner floats over the list, so the newest message ends above it. + { paddingTop: (messageInputFloating ? messageInputHeight : 0) + bannerHeight }, styles.contentContainer, additionalFlatListProps?.contentContainerStyle, ], [ additionalFlatListProps?.contentContainerStyle, - styles.contentContainer, - messageInputHeight, + bannerHeight, messageInputFloating, + messageInputHeight, + styles.contentContainer, ], ); @@ -853,9 +868,10 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { layout={transitions.layout200} style={[ { - bottom: messageInputFloating - ? messageInputHeight + primitives.spacingMd + 16 - : primitives.spacingMd, + bottom: + (messageInputFloating + ? messageInputHeight + primitives.spacingMd + 16 + : primitives.spacingMd) + bannerHeight, }, styles.scrollToBottomButtonContainer, ]} @@ -876,6 +892,23 @@ const MessageListWithContext = (props: MessageListPropsWithContext) => { /> ) : null} + {ScheduledMessagesBanner ? ( + + + + + + ) : null} { diff --git a/package/src/components/Notifications/__tests__/notificationTranslations.test.ts b/package/src/components/Notifications/__tests__/notificationTranslations.test.ts index 56f3efe397..68be954782 100644 --- a/package/src/components/Notifications/__tests__/notificationTranslations.test.ts +++ b/package/src/components/Notifications/__tests__/notificationTranslations.test.ts @@ -1,4 +1,4 @@ -import { CORE_NOTIFICATION_TYPE } from 'stream-chat'; +import { CORE_NOTIFICATION_TYPE, StreamAPIError } from 'stream-chat'; import type { CommandSuggestionDisabledReason, Notification } from 'stream-chat'; import type { StreamTFunction } from '../../../i18n/types'; @@ -57,3 +57,43 @@ describe('getNotificationDisplayMessage', () => { expect(getNotificationDisplayMessage({ notification, t })).toBe('developer-facing fallback'); }); }); + +describe('scheduled message notifications', () => { + it.each([ + ['sent', 'This message was already sent'], + ['deleted', 'This scheduled message was deleted'], + ['failed', 'This scheduled message failed to send'], + ])('renders the copy for an edit that ended because the message was %s', (reason, expected) => { + const notification = buildNotification({ + metadata: { reason }, + type: CORE_NOTIFICATION_TYPE.scheduledMessageCompositionEnded, + }); + + expect(getNotificationDisplayMessage({ notification, t })).toBe(expected); + }); + + it('renders the command copy for a blocked command', () => { + const notification = buildNotification({ + metadata: { reason: 'command' }, + type: CORE_NOTIFICATION_TYPE.scheduledMessageBlocked, + }); + + expect(getNotificationDisplayMessage({ notification, t })).toBe("Commands can't be scheduled"); + }); + + it('maps the server error of a failed schedule to its copy', () => { + const originalError = new StreamAPIError('limit', { + code: 118, + response: undefined, + status: 400, + }); + const notification = buildNotification({ + originalError, + type: CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed, + }); + + expect(getNotificationDisplayMessage({ notification, t })).toBe( + "You've reached your limit of scheduled messages.", + ); + }); +}); diff --git a/package/src/components/Notifications/notificationTranslations.ts b/package/src/components/Notifications/notificationTranslations.ts index bbc0caa44b..4413f0d51b 100644 --- a/package/src/components/Notifications/notificationTranslations.ts +++ b/package/src/components/Notifications/notificationTranslations.ts @@ -1,14 +1,26 @@ -import { CORE_NOTIFICATION_TYPE } from 'stream-chat'; +import { + CORE_NOTIFICATION_TYPE, + MessageComposer, + ScheduledMessageBlockReason, + ScheduledMessageCompositionEndReason, +} from 'stream-chat'; import type { CoreNotificationType, Notification } from 'stream-chat'; import type { StreamTFunction } from '../../i18n/types'; import { asDynamicKey } from '../../i18n/utils'; +import { getScheduleErrorText } from '../ScheduledMessages/utils/scheduleErrors'; type NotificationTranslator = (options: { notification: Notification; t: StreamTFunction; }) => string; +/** The channel of the composer a notification came from, when a composer emitted it. */ +const getNotificationComposerChannel = (notification: Notification) => { + const composer = notification.origin.context?.composer; + return composer instanceof MessageComposer ? composer.channel : undefined; +}; + const normalizeReason = (notification?: Notification) => { const reason = notification?.metadata?.reason; if (typeof reason !== 'string' || !reason.length) return undefined; @@ -33,6 +45,43 @@ const withReasonFallback = ({ return t(asDynamicKey(reasonTranslationKey), { reason }); }; +const translateScheduledMessageBlocked: NotificationTranslator = ({ notification, t }) => { + switch (notification.metadata?.reason) { + case ScheduledMessageBlockReason.Command: + return t( + 'notifications.scheduledMessageBlocked.command.error', + "Commands can't be scheduled", + ); + default: + return t('notifications.scheduledMessageBlocked.error', 'This message cannot be scheduled'); + } +}; + +const translateScheduledMessageCompositionEnded: NotificationTranslator = ({ notification, t }) => { + switch (notification.metadata?.reason) { + case ScheduledMessageCompositionEndReason.Sent: + return t( + 'notifications.scheduledMessageCompositionEnded.sent.error', + 'This message was already sent', + ); + case ScheduledMessageCompositionEndReason.Deleted: + return t( + 'notifications.scheduledMessageCompositionEnded.deleted.error', + 'This scheduled message was deleted', + ); + case ScheduledMessageCompositionEndReason.Failed: + return t( + 'notifications.scheduledMessageCompositionEnded.failed.error', + 'This scheduled message failed to send', + ); + default: + return t( + 'notifications.scheduledMessageCompositionEnded.error', + 'The scheduled message can no longer be edited', + ); + } +}; + const translateAttachmentUploadBlocked = ({ notification, t, @@ -163,17 +212,23 @@ const coreNotificationTranslators: Record - t('notifications.scheduledMessageBlocked.error', 'This message cannot be scheduled'), - [CORE_NOTIFICATION_TYPE.scheduledMessageCompositionEnded]: ({ t }) => - t( - 'notifications.scheduledMessageCompositionEnded.error', - 'The scheduled message can no longer be edited', + [CORE_NOTIFICATION_TYPE.scheduledMessageBlocked]: translateScheduledMessageBlocked, + [CORE_NOTIFICATION_TYPE.scheduledMessageCompositionEnded]: + translateScheduledMessageCompositionEnded, + [CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed]: ({ notification, t }) => + getScheduleErrorText( + t, + notification.originalError, + 'schedule', + getNotificationComposerChannel(notification), + ), + [CORE_NOTIFICATION_TYPE.scheduledMessageUpdateFailed]: ({ notification, t }) => + getScheduleErrorText( + t, + notification.originalError, + 'update', + getNotificationComposerChannel(notification), ), - [CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed]: ({ t }) => - t('notifications.scheduledMessageCreateFailed.error', 'Failed to schedule the message'), - [CORE_NOTIFICATION_TYPE.scheduledMessageUpdateFailed]: ({ t }) => - t('notifications.scheduledMessageUpdateFailed.error', 'Failed to update the scheduled message'), }; /** diff --git a/package/src/components/Reply/Reply.tsx b/package/src/components/Reply/Reply.tsx index f56b12184b..0dc5aea2eb 100644 --- a/package/src/components/Reply/Reply.tsx +++ b/package/src/components/Reply/Reply.tsx @@ -1,4 +1,4 @@ -import React, { useMemo } from 'react'; +import React, { useContext, useMemo } from 'react'; import { I18nManager, Image, @@ -25,11 +25,14 @@ import { ReplyMessageView } from './ReplyMessageView'; import { useAnnounceOnShow } from '../../a11y/hooks/useAnnounceOnShow'; import { useChatContext } from '../../contexts/chatContext/ChatContext'; import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { + MessageComposerContext, + type MessageComposerContextValue, +} from '../../contexts/messageComposerContext/MessageComposerContext'; import { MessageContextValue, useMessageContext, } from '../../contexts/messageContext/MessageContext'; -import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer'; import { useTheme } from '../../contexts/themeContext/ThemeContext'; import { useTranslationContext } from '../../contexts/translationContext/TranslationContext'; import { useStateStore } from '../../hooks'; @@ -102,7 +105,10 @@ export type ReplyPropsWithContext = { ImageComponent: React.ComponentType void; - mode: 'reply' | 'edit'; + /** `editScheduled` is the composer's edit of a scheduled message. */ + mode: 'reply' | 'edit' | 'editScheduled'; + /** Replaces the title the mode gives, e.g. `Message to Maya Ross`. */ + title?: string; // Style overrides passed by `MessageContent`. styles?: { container?: ViewStyle; @@ -125,6 +131,7 @@ export const ReplyWithContext = (props: ReplyPropsWithContext) => { onDismiss, quotedMessage, styles: stylesProp, + title: titleProp, } = props; const { theme: { @@ -142,14 +149,17 @@ export const ReplyWithContext = (props: ReplyPropsWithContext) => { const title = useMemo( () => - mode === 'edit' + titleProp ?? + (mode === 'edit' ? t('message.editMessage.label', 'Edit Message') - : isMyMessage - ? t('common.you.label', 'You') - : quotedMessage?.user?.name - ? t('reply.replyTo.title', 'Reply to {{name}}', { name: quotedMessage?.user?.name }) - : t('message.reply.label', 'Reply'), - [mode, isMyMessage, quotedMessage?.user?.name, t], + : mode === 'editScheduled' + ? t('scheduledMessages.editScheduledMessage.label', 'Edit scheduled message') + : isMyMessage + ? t('common.you.label', 'You') + : quotedMessage?.user?.name + ? t('reply.replyTo.title', 'Reply to {{name}}', { name: quotedMessage?.user?.name }) + : t('message.reply.label', 'Reply')), + [mode, isMyMessage, quotedMessage?.user?.name, t, titleProp], ); if (!quotedMessage) { @@ -182,7 +192,7 @@ export const ReplyWithContext = (props: ReplyPropsWithContext) => { { - if (mode === 'edit') { + if (mode === 'edit' || mode === 'editScheduled') { return truncatedText ? t('reply.editingMessage.withText.accessibilityLabel', 'Editing message: {{text}}', { text: truncatedText, @@ -302,11 +318,12 @@ export const Reply = (props: ReplyProps) => { const { client } = useChatContext(); const { ImageComponent } = useComponentsContext(); - const messageComposer = useMessageComposer(); - const { quotedMessage: quotedMessageFromComposer } = useStateStore( - messageComposer.state, - messageComposerStateStoreSelector, - ); + // Read without throwing, as the schedule sheets show a preview outside any `Channel` too. + const { messageComposer } = useContext( + MessageComposerContext, + ) as Partial; + const { quotedMessage: quotedMessageFromComposer } = + useStateStore(messageComposer?.state, messageComposerStateStoreSelector) ?? {}; const quotedMessage = messageFromContext ? (messageFromContext.quoted_message as ReplyPropsWithContext['quotedMessage']) diff --git a/package/src/components/ScheduledMessages/ChannelScheduledMessages.tsx b/package/src/components/ScheduledMessages/ChannelScheduledMessages.tsx new file mode 100644 index 0000000000..1b4a55698a --- /dev/null +++ b/package/src/components/ScheduledMessages/ChannelScheduledMessages.tsx @@ -0,0 +1,80 @@ +import React from 'react'; +import { StyleSheet, View } from 'react-native'; + +import type { ScheduledMessagesView } from 'stream-chat'; + +import { useChannelWideScheduledMessagesView } from './hooks/useChannelWideScheduledMessagesView'; +import { useEditedScheduledMessage } from './hooks/useEditedScheduledMessage'; +import { ScheduledMessageEditComposer } from './ScheduledMessageEditComposer'; +import { ScheduledMessageList, type ScheduledMessageListProps } from './ScheduledMessageList'; + +import { useChannelContext } from '../../contexts/channelContext/ChannelContext'; +import { useMessageComposerAPIContext } from '../../contexts/messageComposerContext/MessageComposerAPIContext'; +import { useMessageInputContext } from '../../contexts/messageInputContext/MessageInputContext'; +import { useStateStore } from '../../hooks/useStateStore'; +import type { MessageInputHeightState } from '../../state-store/message-input-height-store'; +import { NotificationList } from '../Notifications/NotificationList'; +import { getChannelNotificationHostId } from '../Notifications/notificationTarget'; + +export type ChannelScheduledMessagesProps = Omit< + ScheduledMessageListProps, + 'onEditScheduledMessage' | 'view' +> & { + /** The thread's with `thread.scheduledMessages`. Defaults to the channel's, thread replies included. */ + view?: ScheduledMessagesView; +}; + +const messageInputHeightSelector = (state: MessageInputHeightState) => ({ height: state.height }); + +/** + * The edit composer's toasts. A floating composer covers the bottom of the list, so they sit above + * it, as on a channel screen. + */ +const EditNotifications = ({ cid }: { cid: string }) => { + const { messageInputFloating, messageInputHeightStore } = useMessageInputContext(); + const { height } = useStateStore(messageInputHeightStore.store, messageInputHeightSelector); + + return ( + + ); +}; + +/** + * The scheduled messages of the surrounding `Channel`, thread replies included, or of a thread, + * with editing in a composer under the list. + * + * Render it inside a `Channel` for the channel, on a screen of its own, as you would a message + * list. That `Channel` configures the edit composer, its keyboard handling and its attachment + * picker, so give it the props your channel screen uses. Pass `initializeOnMount={false}` and + * `markReadOnMount={false}` so opening the list doesn't load messages or mark the channel read. + */ +export const ChannelScheduledMessages = ({ view, ...props }: ChannelScheduledMessagesProps) => { + const { channel } = useChannelContext(); + const channelWideView = useChannelWideScheduledMessagesView(channel); + const { editScheduledMessage } = useMessageComposerAPIContext(); + const { editedScheduledMessage } = useEditedScheduledMessage(); + + return ( + + + + {editedScheduledMessage ? : null} + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); diff --git a/package/src/components/ScheduledMessages/QuoteDeletedNotice.tsx b/package/src/components/ScheduledMessages/QuoteDeletedNotice.tsx new file mode 100644 index 0000000000..4bdc980dd0 --- /dev/null +++ b/package/src/components/ScheduledMessages/QuoteDeletedNotice.tsx @@ -0,0 +1,74 @@ +import React from 'react'; +import { Pressable, StyleSheet, Text, View } from 'react-native'; + +import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer'; +import { useTheme } from '../../contexts/themeContext/ThemeContext'; +import { useTranslationContext } from '../../contexts/translationContext/TranslationContext'; +import { components, primitives } from '../../theme'; + +/** Shown in the composer while editing a scheduled message whose quoted message was deleted. */ +export const QuoteDeletedNotice = () => { + const messageComposer = useMessageComposer(); + const { icons } = useComponentsContext(); + const { t } = useTranslationContext(); + const { + theme: { + scheduledMessages: { notice: noticeTheme }, + semantics, + }, + } = useTheme(); + + return ( + + + + {t('scheduledMessages.quoteDeleted.title', 'The quoted message was deleted')} + + messageComposer.setQuotedMessage(null)} + testID='scheduled-message-remove-quote' + > + + {t('scheduledMessages.removeQuote.label', 'Remove quote')} + + + + ); +}; + +const styles = StyleSheet.create({ + action: { + fontSize: primitives.typographyFontSizeXs, + fontWeight: primitives.typographyFontWeightSemiBold, + lineHeight: primitives.typographyLineHeightTight, + }, + container: { + alignItems: 'center', + borderRadius: primitives.radiusLg, + flexDirection: 'row', + gap: primitives.spacingXs, + paddingHorizontal: primitives.spacingXs, + paddingVertical: primitives.spacingSm, + }, + title: { + flex: 1, + fontSize: primitives.typographyFontSizeXs, + fontWeight: primitives.typographyFontWeightSemiBold, + lineHeight: primitives.typographyLineHeightTight, + }, +}); diff --git a/package/src/components/ScheduledMessages/RescheduleFailedMessageButton.tsx b/package/src/components/ScheduledMessages/RescheduleFailedMessageButton.tsx new file mode 100644 index 0000000000..f11bdc7959 --- /dev/null +++ b/package/src/components/ScheduledMessages/RescheduleFailedMessageButton.tsx @@ -0,0 +1,51 @@ +import React, { useState } from 'react'; + +import { nsToDate } from 'stream-chat'; + +import { useEditedScheduledMessage } from './hooks/useEditedScheduledMessage'; +import { + RescheduleSheet, + type RescheduleSheetRequest, + useOpenRescheduleSheet, +} from './RescheduleSheet'; + +import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer'; +import { useStableCallback } from '../../hooks/useStableCallback'; +import { EditButton } from '../MessageInput/components/OutputButtons/EditButton'; + +export type RescheduleFailedMessageButtonProps = { + disabled: boolean; +}; + +/** + * The save button while the composer edits a failed scheduled message. Saving schedules it again + * as a new message, so it opens the date and time sheet first. + */ +export const RescheduleFailedMessageButton = ({ disabled }: RescheduleFailedMessageButtonProps) => { + const messageComposer = useMessageComposer(); + const { editedScheduledMessage } = useEditedScheduledMessage(); + const openHostedSheet = useOpenRescheduleSheet(); + const [request, setRequest] = useState(); + + const open = useStableCallback(async () => { + // nothing is returned when the composer can't send yet, i.e while an upload is running. + const composition = await messageComposer.compose(); + if (!composition) return; + const nextRequest = { + initialDate: editedScheduledMessage + ? nsToDate(editedScheduledMessage.scheduled_at) + : undefined, + message: composition.localMessage, + }; + (openHostedSheet ?? setRequest)(nextRequest); + }); + + const close = useStableCallback(() => setRequest(undefined)); + + return ( + <> + + {openHostedSheet ? null : } + + ); +}; diff --git a/package/src/components/ScheduledMessages/RescheduleSheet.tsx b/package/src/components/ScheduledMessages/RescheduleSheet.tsx new file mode 100644 index 0000000000..f5a0c0382f --- /dev/null +++ b/package/src/components/ScheduledMessages/RescheduleSheet.tsx @@ -0,0 +1,66 @@ +import React, { createContext, useContext } from 'react'; + +import type { LocalMessage } from 'stream-chat'; + +import { useScheduleComposerMessage } from './hooks/useScheduleComposerMessage'; + +import { formatScheduledDateTime } from './utils/scheduledTimeLabels'; + +import { useChannelContext } from '../../contexts/channelContext/ChannelContext'; +import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { useTranslationContext } from '../../contexts/translationContext/TranslationContext'; +import { useStableCallback } from '../../hooks/useStableCallback'; + +/** What the Reschedule sheet shows, copied when it opens so it outlives the edit. */ +export type RescheduleSheetRequest = { + message: LocalMessage; + initialDate?: Date; +}; + +type OpenRescheduleSheet = (request: RescheduleSheetRequest) => void; + +/** + * Lets the save button open a Reschedule sheet rendered next to the edit rather than inside it. + * Scheduling a failed message again ends the edit, so a sheet inside the composer would vanish + * instead of sliding closed. + */ +export const RescheduleSheetContext = createContext(undefined); + +/** Opens the hosted Reschedule sheet, or `undefined` when no host is around. */ +export const useOpenRescheduleSheet = () => useContext(RescheduleSheetContext); + +type RescheduleSheetProps = { + onClose: () => void; + request?: RescheduleSheetRequest; +}; + +/** The date and time sheet for saving a failed scheduled message, which schedules it again. */ +export const RescheduleSheet = ({ onClose, request }: RescheduleSheetProps) => { + const { ScheduleTimeSheet } = useComponentsContext(); + const { channel } = useChannelContext(); + const { t, tDateTimeParser } = useTranslationContext(); + const schedule = useScheduleComposerMessage(); + + const confirm = useStableCallback((scheduledAt: Date) => + schedule(scheduledAt, { fromTimeSheet: true }), + ); + + return ( + + ); +}; diff --git a/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx b/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx new file mode 100644 index 0000000000..aa4db03bc8 --- /dev/null +++ b/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx @@ -0,0 +1,240 @@ +import React, { useCallback, useMemo, useState } from 'react'; +import { + I18nManager, + Pressable, + type PressableStateCallbackType, + StyleSheet, + Text, + View, +} from 'react-native'; + +import type { LocalMessage } from 'stream-chat'; + +import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit'; +import { useScheduleComposerMessage } from './hooks/useScheduleComposerMessage'; + +import { ScheduleSheetHeader } from './ScheduleSheetHeader'; + +import { formatSchedulePreset } from './utils/scheduledTimeLabels'; +import { getAvailableSchedulePresets, getScheduleTimeBounds } from './utils/scheduleTime'; + +import { useBottomSheetContext } from '../../contexts/bottomSheetContext/BottomSheetContext'; +import { useChannelContext } from '../../contexts/channelContext/ChannelContext'; +import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer'; +import { + type ScheduleSheetState, + useMessageInputContext, +} from '../../contexts/messageInputContext/MessageInputContext'; +import { useTheme } from '../../contexts/themeContext/ThemeContext'; +import { useTranslationContext } from '../../contexts/translationContext/TranslationContext'; +import { useStableCallback } from '../../hooks/useStableCallback'; +import { useStateStore } from '../../hooks/useStateStore'; +import { components, primitives } from '../../theme'; +import { BottomSheetModal } from '../UIComponents/BottomSheetModal'; + +const scheduleSheetSelector = ({ isOpen }: ScheduleSheetState) => ({ isOpen }); + +type ScheduleOptionProps = { + disabled: boolean; + label: string; + onPress: () => void; + testID: string; + showChevron?: boolean; +}; + +const ScheduleOption = ({ disabled, label, onPress, showChevron, testID }: ScheduleOptionProps) => { + const { icons } = useComponentsContext(); + const { + theme: { + scheduledMessages: { presetSheet }, + semantics, + }, + } = useTheme(); + const color = disabled ? semantics.textDisabled : semantics.textPrimary; + const iconColor = disabled ? semantics.textDisabled : semantics.textSecondary; + const Chevron = I18nManager.isRTL ? icons.ChevronLeft : icons.ChevronRight; + + const style = useCallback( + ({ pressed }: PressableStateCallbackType) => [ + styles.option, + pressed ? { backgroundColor: semantics.backgroundUtilityPressed } : null, + presetSheet.option, + ], + [presetSheet.option, semantics.backgroundUtilityPressed], + ); + + return ( + + + + {label} + + {showChevron ? ( + + ) : null} + + ); +}; + +type PresetOptionProps = { + disabled: boolean; + label: string; + onSelect: (preset: Date) => void; + preset: Date; +}; + +const PresetOption = ({ disabled, label, onSelect, preset }: PresetOptionProps) => { + const onPress = useStableCallback(() => onSelect(preset)); + + return ( + + ); +}; + +/** `Custom time`, which opens the date and time sheet on top of the quick times. */ +const CustomTimeOption = ({ disabled }: { disabled: boolean }) => { + const { close } = useBottomSheetContext(); + const { ScheduleTimeSheet } = useComponentsContext(); + const { channel } = useChannelContext(); + const messageComposer = useMessageComposer(); + const { t } = useTranslationContext(); + const schedule = useScheduleComposerMessage(); + const [customTimePreviewMessage, setCustomTimePreviewMessage] = useState(); + + const open = useStableCallback(async () => { + // Nothing is returned when the composer can't send yet, e.g. while an upload is running. + const composition = await messageComposer.compose(); + if (composition) setCustomTimePreviewMessage(composition.localMessage); + }); + + const closeCustomTime = useStableCallback(() => setCustomTimePreviewMessage(undefined)); + + const confirmCustomTime = useStableCallback(async (scheduledAt: Date) => { + const result = await schedule(scheduledAt, { fromTimeSheet: true }); + // Scheduled, so the quick times close along with this sheet. + if (!result.errorText) close(); + return result; + }); + + return ( + <> + + + + ); +}; + +const ScheduleMessageSheetContent = () => { + const { close } = useBottomSheetContext(); + const { channel } = useChannelContext(); + const { isLimitReached, maxPerChannel } = useChannelScheduledMessageLimit(channel); + const schedule = useScheduleComposerMessage(); + const { t, tDateTimeParser } = useTranslationContext(); + const { + theme: { + scheduledMessages: { presetSheet }, + }, + } = useTheme(); + + // The presets are worked out when the sheet opens, in the device's time zone. + const { now, presets } = useMemo(() => { + const openedAt = new Date(); + return { + now: openedAt, + presets: getAvailableSchedulePresets(openedAt, getScheduleTimeBounds(channel, openedAt)), + }; + }, [channel]); + + const closeSheet = useStableCallback(() => close()); + + const selectPreset = useStableCallback((preset: Date) => { + schedule(preset).catch(() => undefined); + close(); + }); + + // A failed message comes back as a new one, so it counts against the limit like any other. + const title = isLimitReached + ? t('scheduledMessages.limitReached.title', 'Limit reached ({{ count }} max)', { + count: maxPerChannel, + }) + : t('scheduledMessages.scheduleMessage.title', 'Schedule message'); + + return ( + + + + {presets.map((preset) => ( + + ))} + + + + ); +}; + +/** The sheet a long press on the send button opens: quick times and `Custom time`. */ +export const ScheduleMessageSheet = () => { + const { closeScheduleSheet, scheduleSheetStore } = useMessageInputContext(); + const { isOpen } = useStateStore(scheduleSheetStore, scheduleSheetSelector); + + return ( + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + paddingBottom: primitives.spacingMd, + }, + option: { + alignItems: 'center', + borderRadius: primitives.radiusMd, + flexDirection: 'row', + gap: primitives.spacingSm, + minHeight: 48, + paddingHorizontal: primitives.spacingSm, + paddingVertical: primitives.spacingXs, + }, + optionLabel: { + flex: 1, + fontSize: primitives.typographyFontSizeMd, + lineHeight: primitives.typographyLineHeightNormal, + }, + options: { + paddingHorizontal: primitives.spacingXxs, + }, +}); diff --git a/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx b/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx new file mode 100644 index 0000000000..8d30804278 --- /dev/null +++ b/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx @@ -0,0 +1,105 @@ +import React, { useCallback } from 'react'; +import { StyleSheet, Text, View } from 'react-native'; + +import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { useTheme } from '../../contexts/themeContext/ThemeContext'; +import type { IconProps } from '../../icons'; +import { components, primitives } from '../../theme'; +import { Button } from '../ui'; + +export type ScheduleSheetHeaderProps = { + onClose: () => void; + title: string; + /** Renders the confirm button when set. */ + onConfirm?: () => void; + confirmDisabled?: boolean; +}; + +/** The header of the schedule sheets: close on the start, the title, and an optional confirm. */ +export const ScheduleSheetHeader = ({ + confirmDisabled = false, + onClose, + onConfirm, + title, +}: ScheduleSheetHeaderProps) => { + const { icons } = useComponentsContext(); + const { + theme: { + scheduledMessages: { sheetHeader }, + semantics, + }, + } = useTheme(); + + const renderConfirmIcon = useCallback( + (props: IconProps) => ( + + ), + [confirmDisabled, icons, semantics.textDisabled, semantics.textOnAccent], + ); + + return ( + + +