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 (
+
+
+
+
+
+ {title}
+
+
+ {onConfirm ? (
+
+ ) : null}
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: primitives.spacingSm,
+ paddingBottom: primitives.spacingSm,
+ paddingHorizontal: primitives.spacingSm,
+ },
+ // A 48 wide hit area for each 40 wide button, as in the design.
+ side: {
+ alignItems: 'center',
+ minWidth: 48,
+ },
+ title: {
+ flex: 1,
+ fontSize: primitives.typographyFontSizeMd,
+ fontWeight: primitives.typographyFontWeightSemiBold,
+ lineHeight: primitives.typographyLineHeightNormal,
+ textAlign: 'center',
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduleSheetNotice.tsx b/package/src/components/ScheduledMessages/ScheduleSheetNotice.tsx
new file mode 100644
index 0000000000..1733fcb3db
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduleSheetNotice.tsx
@@ -0,0 +1,91 @@
+import React from 'react';
+import { StyleSheet, Text, View } from 'react-native';
+
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { components, primitives } from '../../theme';
+
+export type ScheduleSheetNoticeProps = {
+ /** The bold first line. */
+ title: string;
+ type: 'error' | 'info';
+ /** An optional second, regular-weight line. */
+ description?: string;
+};
+
+/** The error and info boxes of the schedule sheets. */
+export const ScheduleSheetNotice = ({ description, title, type }: ScheduleSheetNoticeProps) => {
+ const { icons } = useComponentsContext();
+ const {
+ theme: {
+ scheduledMessages: { notice: noticeTheme },
+ semantics,
+ },
+ } = useTheme();
+ const isError = type === 'error';
+ const Icon = isError ? icons.ExclamationCircleOutline : icons.InfoTooltip;
+
+ return (
+
+
+
+
+ {title}
+
+ {description ? (
+
+ {description}
+
+ ) : null}
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ alignItems: 'center',
+ borderRadius: primitives.radiusMd,
+ flexDirection: 'row',
+ gap: primitives.spacingXs,
+ minHeight: 46,
+ paddingHorizontal: primitives.spacingSm,
+ paddingVertical: primitives.spacingSm,
+ },
+ description: {
+ fontSize: primitives.typographyFontSizeXs,
+ lineHeight: primitives.typographyLineHeightTight,
+ },
+ texts: {
+ flex: 1,
+ gap: primitives.spacingXxxs,
+ },
+ title: {
+ fontSize: primitives.typographyFontSizeXs,
+ fontWeight: primitives.typographyFontWeightSemiBold,
+ lineHeight: primitives.typographyLineHeightTight,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduleTimeSheet.tsx b/package/src/components/ScheduledMessages/ScheduleTimeSheet.tsx
new file mode 100644
index 0000000000..9d3795d6c7
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduleTimeSheet.tsx
@@ -0,0 +1,383 @@
+import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ Pressable,
+ type PressableStateCallbackType,
+ StyleSheet,
+ Text,
+ useWindowDimensions,
+ View,
+} from 'react-native';
+
+import type { Channel, LocalMessage } from 'stream-chat';
+import { ScheduledMessageBlockReason } from 'stream-chat';
+
+import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit';
+import type { ScheduleComposerMessageResult } from './hooks/useScheduleComposerMessage';
+import { ScheduleSheetHeader } from './ScheduleSheetHeader';
+import { ScheduleSheetNotice } from './ScheduleSheetNotice';
+import { formatScheduledDate, formatScheduledTime } from './utils/scheduledTimeLabels';
+import {
+ formatTimeZoneOffset,
+ getDefaultScheduledAt,
+ getScheduleTimeBounds,
+ getScheduleTimeError,
+} from './utils/scheduleTime';
+
+import { useBottomSheetContext } from '../../contexts/bottomSheetContext/BottomSheetContext';
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import {
+ MessageComposerContext,
+ type MessageComposerContextValue,
+} from '../../contexts/messageComposerContext/MessageComposerContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { useTranslationContext } from '../../contexts/translationContext/TranslationContext';
+import { useStableCallback } from '../../hooks/useStableCallback';
+import type { IconProps } from '../../icons/utils/base';
+import { NativeHandlers, type PickDateTimeOptions } from '../../native';
+import { components, primitives } from '../../theme';
+import { useChannelPreviewDisplayName } from '../ChannelPreview/hooks/useChannelPreviewDisplayName';
+import { BottomSheetModal } from '../UIComponents/BottomSheetModal';
+
+export type ScheduleTimeSheetProps = {
+ channel: Channel;
+ /** The message being scheduled, shown in the preview card. */
+ message?: LocalMessage;
+ /** Called with the picked time. Resolves with the error to show, or nothing on success. */
+ onConfirm: (scheduledAt: Date) => Promise;
+ onClose: () => void;
+ visible: boolean;
+ /** The time the sheet opens with. Defaults to tomorrow at 09:00. */
+ initialDate?: Date;
+ /** Replaces the sheet's title, e.g. `Reschedule message`. */
+ title?: string;
+ /** Replaces the preview card's first line, e.g. `Scheduled for Fri, Oct 23 at 09:00`. */
+ previewTitle?: string;
+ /**
+ * `reschedule` moves a scheduled message to another time. That adds no message, so the count
+ * note is left out, and the server never sends it right away, so a too-soon time says so.
+ */
+ mode?: 'schedule' | 'reschedule';
+};
+
+const NOW_REFRESH_INTERVAL_MS = 15_000;
+
+type ScheduleTimeRowProps = {
+ disabled: boolean;
+ Icon: React.ComponentType;
+ label: string;
+ onPress: () => void;
+ testID: string;
+ value: string;
+};
+
+/** A `Date` or `Time` row, with the label on the left and the selected value on the right. */
+const ScheduleTimeRow = ({
+ disabled,
+ Icon,
+ label,
+ onPress,
+ testID,
+ value,
+}: ScheduleTimeRowProps) => {
+ const {
+ theme: {
+ scheduledMessages: { timeSheet },
+ semantics,
+ },
+ } = useTheme();
+
+ const style = useCallback(
+ ({ pressed }: PressableStateCallbackType) => [
+ styles.row,
+ pressed ? { backgroundColor: semantics.backgroundUtilityPressed } : null,
+ timeSheet.row,
+ ],
+ [semantics.backgroundUtilityPressed, timeSheet.row],
+ );
+
+ return (
+
+
+
+ {label}
+
+
+ {value}
+
+
+ );
+};
+
+const ScheduleTimeSheetContent = ({
+ channel,
+ initialDate,
+ message,
+ mode = 'schedule',
+ onConfirm,
+ previewTitle: previewTitleProp,
+ title: titleProp,
+}: Omit) => {
+ const { close } = useBottomSheetContext();
+ const { icons, Reply } = useComponentsContext();
+ // Read without throwing, as a list across channels reschedules outside any `Channel`.
+ const { messageComposer } = useContext(
+ MessageComposerContext,
+ ) as Partial;
+ const { t, tDateTimeParser } = useTranslationContext();
+ const channelName = useChannelPreviewDisplayName(channel)?.trim();
+ const { maxPerChannel, pendingCount } = useChannelScheduledMessageLimit(channel);
+
+ const title = titleProp ?? t('scheduledMessages.scheduleMessage.title', 'Schedule message');
+
+ const quotedName = message?.quoted_message?.user?.name;
+ const previewTitle =
+ previewTitleProp ??
+ (quotedName
+ ? t('reply.replyTo.title', 'Reply to {{name}}', { name: quotedName })
+ : channelName
+ ? t('scheduledMessages.messageTo.title', 'Message to {{ name }}', { name: channelName })
+ : t('scheduledMessages.message.title', 'Scheduled message'));
+
+ const usageText =
+ mode === 'schedule' && maxPerChannel !== undefined && pendingCount > 0
+ ? t('scheduledMessages.usage.text', '{{ count }} of {{ max }} scheduled in this channel', {
+ count: pendingCount,
+ max: maxPerChannel,
+ })
+ : undefined;
+ const {
+ theme: {
+ scheduledMessages: { timeSheet },
+ },
+ } = useTheme();
+
+ const [now, setNow] = useState(() => new Date());
+ useEffect(() => {
+ const interval = setInterval(() => setNow(new Date()), NOW_REFRESH_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, []);
+
+ const bounds = useMemo(() => getScheduleTimeBounds(channel, now), [channel, now]);
+ const [scheduledAt, setScheduledAt] = useState(
+ () => initialDate ?? getDefaultScheduledAt(new Date(), bounds),
+ );
+ const [submitError, setSubmitError] = useState();
+ // Set once the server refuses for the per-user limit. Any other time would be refused the same
+ // way, so it keeps confirm disabled and stays when the time changes.
+ const [userLimitError, setUserLimitError] = useState();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const blockedText =
+ mode === 'schedule' &&
+ messageComposer?.scheduleBlockReason === ScheduledMessageBlockReason.Command
+ ? t(
+ 'scheduledMessages.commandBlocked.error',
+ "Commands can't be scheduled. Remove the / command to continue.",
+ )
+ : userLimitError;
+
+ const timeError = getScheduleTimeError(scheduledAt, bounds);
+ const timeErrorText =
+ timeError === 'too_soon'
+ ? mode === 'reschedule'
+ ? t(
+ 'scheduledMessages.rescheduleTooSoon.error',
+ "Pick a later time. Editing can't send a message right away.",
+ )
+ : t('scheduledMessages.tooSoon.error', 'Pick a time at least 1 minute from now')
+ : timeError === 'too_far'
+ ? t('scheduledMessages.tooFar.error', "That's further ahead than your app allows")
+ : undefined;
+
+ const errorText = blockedText ?? timeErrorText ?? submitError;
+ const confirmDisabled = isSubmitting || !!blockedText || !!timeError;
+
+ const changeTime = useStableCallback((next: Date) => {
+ setSubmitError(undefined);
+ setScheduledAt(next);
+ });
+
+ const closeSheet = useStableCallback(() => close());
+
+ const pickDateTime = NativeHandlers.pickDateTime;
+ const isPickingRef = useRef(false);
+ // Aborted on unmount, so a picker that is still open closes together with the sheet.
+ const pickerAbortRef = useRef(undefined);
+ useEffect(() => {
+ const controller = new AbortController();
+ pickerAbortRef.current = controller;
+ return () => controller.abort();
+ }, []);
+
+ const pick = (mode: PickDateTimeOptions['mode'], value: Date) =>
+ pickDateTime
+ ? pickDateTime({
+ cancelLabel: t('common.cancel.label', 'Cancel'),
+ confirmLabel: t('scheduledMessages.pickerConfirm.label', 'Confirm'),
+ maximumDate: bounds.latest,
+ minimumDate: bounds.earliest,
+ mode,
+ signal: pickerAbortRef.current?.signal,
+ value,
+ }).catch(() => null)
+ : Promise.resolve(null);
+
+ // Presses are ignored while a picker is open or being opened.
+ const runPicker = async (picker: () => Promise) => {
+ if (isPickingRef.current) return;
+ isPickingRef.current = true;
+ try {
+ await picker();
+ } finally {
+ isPickingRef.current = false;
+ }
+ };
+
+ // Confirming a date opens the time picker next, as the design specifies for both platforms.
+ const pickDate = useStableCallback(() =>
+ runPicker(async () => {
+ const date = await pick('date', scheduledAt);
+ if (!date) return;
+ changeTime(date);
+ const time = await pick('time', date);
+ if (time) changeTime(time);
+ }),
+ );
+
+ const pickTime = useStableCallback(() =>
+ runPicker(async () => {
+ const time = await pick('time', scheduledAt);
+ if (time) changeTime(time);
+ }),
+ );
+
+ const confirm = useStableCallback(async () => {
+ if (confirmDisabled) return;
+ setIsSubmitting(true);
+ setSubmitError(undefined);
+ try {
+ const { errorText: error, isUserLimit } = await onConfirm(scheduledAt);
+ if (isUserLimit) {
+ setUserLimitError(error);
+ } else if (error) {
+ setSubmitError(error);
+ } else {
+ close();
+ }
+ } finally {
+ setIsSubmitting(false);
+ }
+ });
+
+ return (
+
+
+
+ {message ? : null}
+ {errorText ? : null}
+
+
+
+
+
+
+
+ );
+};
+
+/** The date and time sheet for `Custom time`, rescheduling, and saving a failed message. */
+export const ScheduleTimeSheet = ({ onClose, visible, ...props }: ScheduleTimeSheetProps) => {
+ const { height } = useWindowDimensions();
+
+ return (
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ paddingBottom: primitives.spacingMd,
+ },
+ content: {
+ gap: primitives.spacingMd,
+ paddingHorizontal: primitives.spacingMd,
+ paddingTop: primitives.spacingXs,
+ },
+ row: {
+ alignItems: 'center',
+ borderRadius: primitives.radiusMd,
+ flexDirection: 'row',
+ gap: primitives.spacingSm,
+ minHeight: 48,
+ paddingHorizontal: primitives.spacingSm,
+ paddingVertical: primitives.spacingXs,
+ },
+ rowLabel: {
+ flex: 1,
+ fontSize: primitives.typographyFontSizeMd,
+ lineHeight: primitives.typographyLineHeightNormal,
+ },
+ // List items extend beyond the horizontal padding of the surrounding content.
+ rows: {
+ marginHorizontal: primitives.spacingXxs - primitives.spacingMd,
+ },
+ rowValue: {
+ fontSize: primitives.typographyFontSizeSm,
+ lineHeight: primitives.typographyLineHeightNormal,
+ width: 120,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageActionsSheet.tsx b/package/src/components/ScheduledMessages/ScheduledMessageActionsSheet.tsx
new file mode 100644
index 0000000000..23636a8d3f
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageActionsSheet.tsx
@@ -0,0 +1,89 @@
+import React from 'react';
+import { StyleSheet, View } from 'react-native';
+
+import type { ScheduledMessageResponse } from 'stream-chat';
+
+import {
+ GetScheduledMessageActionItems,
+ ScheduledMessageActions,
+ useScheduledMessageActionItems,
+} from './hooks/useScheduledMessageActionItems';
+
+import { useBottomSheetContext } from '../../contexts/bottomSheetContext/BottomSheetContext';
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { primitives } from '../../theme';
+import { BottomSheetModal } from '../UIComponents/BottomSheetModal';
+
+export type ScheduledMessageActionsSheetProps = {
+ /** The actions of `scheduledMessage`, bound to it. */
+ actions: ScheduledMessageActions | undefined;
+ onClose: () => void;
+ scheduledMessage: ScheduledMessageResponse | undefined;
+ /** Customizes the default action items. */
+ getScheduledMessageActionItems?: GetScheduledMessageActionItems;
+};
+
+const ScheduledMessageActionsSheetContent = ({
+ actions,
+ getScheduledMessageActionItems,
+ scheduledMessage,
+}: {
+ actions: ScheduledMessageActions;
+ getScheduledMessageActionItems?: GetScheduledMessageActionItems;
+ scheduledMessage: ScheduledMessageResponse;
+}) => {
+ const { ChannelDetailsActionItem } = useComponentsContext();
+ const { dismiss } = useBottomSheetContext();
+ const {
+ theme: {
+ scheduledMessages: { actionsSheet },
+ },
+ } = useTheme();
+
+ const actionItems = useScheduledMessageActionItems({
+ actions,
+ getScheduledMessageActionItems,
+ scheduledMessage,
+ });
+
+ return (
+
+ {actionItems.map((item) => (
+ dismiss(() => item.action())}
+ testID={`scheduled-message-action-${item.id}`}
+ />
+ ))}
+
+ );
+};
+
+/** The actions of a scheduled message, customizable through `getScheduledMessageActionItems`. */
+export const ScheduledMessageActionsSheet = ({
+ actions,
+ onClose,
+ scheduledMessage,
+ ...props
+}: ScheduledMessageActionsSheetProps) => (
+
+ {scheduledMessage && actions ? (
+
+ ) : null}
+
+);
+
+const styles = StyleSheet.create({
+ container: {
+ paddingBottom: primitives.spacingMd,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageEditComposer.tsx b/package/src/components/ScheduledMessages/ScheduledMessageEditComposer.tsx
new file mode 100644
index 0000000000..831944a4e2
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageEditComposer.tsx
@@ -0,0 +1,86 @@
+import React, { useEffect, useState } from 'react';
+import { Keyboard } from 'react-native';
+
+import type { ScheduledMessageResponse } from 'stream-chat';
+
+import { useEditedScheduledMessage } from './hooks/useEditedScheduledMessage';
+import {
+ RescheduleSheet,
+ RescheduleSheetContext,
+ type RescheduleSheetRequest,
+} from './RescheduleSheet';
+
+import { useMessageComposerAPIContext } from '../../contexts/messageComposerContext/MessageComposerAPIContext';
+import { useFocusMessageInput } from '../../hooks/useFocusMessageInput';
+import { useStableCallback } from '../../hooks/useStableCallback';
+import { MessageComposer } from '../MessageInput/MessageComposer';
+
+export type ScheduledMessageEditComposerProps = {
+ /**
+ * Called once the edit ends: saved, cancelled, or ended by the server. For an app that mounts a
+ * `Channel` for each edit, so it knows when to remove it.
+ */
+ onClose?: () => void;
+ /**
+ * Starts editing this message when the component mounts. For a list outside the message's
+ * `Channel`, e.g. one across channels; a channel's own list starts edits itself.
+ */
+ scheduledMessage?: ScheduledMessageResponse;
+};
+
+/**
+ * Shows the composer while a scheduled message is being edited, and nothing otherwise. Render it
+ * inside the `Channel` the message belongs to. The edit starts with `editScheduledMessage` from
+ * `useMessageComposerAPIContext`, or from `scheduledMessage`. Saving or cancelling ends it.
+ *
+ * The composer's notifications go to the channel's notification host, so the screen should show a
+ * `NotificationList` for it, as a channel screen does.
+ */
+export const ScheduledMessageEditComposer = ({
+ onClose,
+ scheduledMessage,
+}: ScheduledMessageEditComposerProps) => {
+ const { editScheduledMessage } = useMessageComposerAPIContext();
+ const { editedScheduledMessage } = useEditedScheduledMessage();
+ const editedId = editedScheduledMessage?.id;
+ // Kept here rather than in the save button, so the sheet outlives the edit and slides closed.
+ const [rescheduleRequest, setRescheduleRequest] = useState();
+
+ // Nothing is being edited and no Reschedule sheet is still closing over the edit.
+ const closeIfDone = useStableCallback(() => {
+ if (!editedId && !rescheduleRequest) onClose?.();
+ });
+
+ const closeRescheduleSheet = useStableCallback(() => {
+ setRescheduleRequest(undefined);
+ if (!editedId) onClose?.();
+ });
+
+ const startEdit = useStableCallback(() => {
+ if (scheduledMessage) editScheduledMessage(scheduledMessage);
+ });
+
+ useEffect(() => {
+ startEdit();
+ }, [scheduledMessage?.id, startEdit]);
+
+ // Opens the keyboard when an edit starts, as editing a sent message does.
+ useFocusMessageInput(editedId);
+
+ // Closes the keyboard when the edit ends. Unmounting leaves `editedId` as it was, so it doesn't
+ // count as an end.
+ useEffect(() => {
+ if (!editedId) return;
+ return () => {
+ Keyboard.dismiss();
+ closeIfDone();
+ };
+ }, [closeIfDone, editedId]);
+
+ return (
+
+ {editedScheduledMessage ? : null}
+
+
+ );
+};
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageList.tsx b/package/src/components/ScheduledMessages/ScheduledMessageList.tsx
new file mode 100644
index 0000000000..5cd0091484
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageList.tsx
@@ -0,0 +1,363 @@
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { Alert, FlatList, type FlatListProps, StyleSheet, Text, View } from 'react-native';
+
+import type { ScheduledMessageResponse, ScheduledMessagesView } from 'stream-chat';
+import { nsToDate, SCHEDULED_MESSAGE_STATUS, toScheduledMessagePreview } from 'stream-chat';
+
+import {
+ getScheduledMessageChannel,
+ useScheduledMessageActionHandlers,
+} from './hooks/useScheduledMessageActionHandlers';
+
+import type {
+ GetScheduledMessageActionItems,
+ ScheduledMessageActions,
+} from './hooks/useScheduledMessageActionItems';
+import { useScheduledMessageList } from './hooks/useScheduledMessageList';
+
+import { ScheduledMessageListLoadingSkeleton } from './ScheduledMessageListLoadingSkeleton';
+
+import { formatScheduledDateTime } from './utils/scheduledTimeLabels';
+import { isScheduledMessageLocked } from './utils/status';
+
+import { useChatContext } from '../../contexts/chatContext/ChatContext';
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { useTranslationContext } from '../../contexts/translationContext/TranslationContext';
+import { useStableCallback } from '../../hooks/useStableCallback';
+import { components, primitives } from '../../theme';
+import { useChannelPreviewDisplayName } from '../ChannelPreview/hooks/useChannelPreviewDisplayName';
+import { NotificationList } from '../Notifications/NotificationList';
+import { NotificationTargetProvider } from '../Notifications/NotificationTargetContext';
+import { Button } from '../ui';
+import { EmptyList } from '../UIComponents/EmptyList';
+import { EmptySearchResult } from '../UIComponents/EmptySearchResult';
+import { SearchInput, SearchInputProps } from '../UIComponents/SearchInput';
+
+export type ScheduledMessageListProps = {
+ /**
+ * What to list: `channel.scheduledMessages`, `thread.scheduledMessages`, or a view of a list
+ * across channels, e.g. `new ScheduledMessagesView({ paginator })`. It loads the first page
+ * if needed, and the next ones on scroll.
+ */
+ view: ScheduledMessagesView;
+ /** Additional props passed to the underlying `FlatList`. */
+ additionalFlatListProps?: Partial>;
+ /** Customizes the actions offered for a scheduled message. */
+ getScheduledMessageActionItems?: GetScheduledMessageActionItems;
+ /** Called when `Edit message` is tapped. Without it, `Edit message` isn't offered. */
+ onEditScheduledMessage?: (scheduledMessage: ScheduledMessageResponse) => void;
+ /** Replaces the default text search, e.g. to also match the channel name. */
+ searchFilter?: ScheduledMessageSearchFilter;
+ searchInputProps?: SearchInputProps;
+};
+
+const keyExtractor = (scheduledMessage: ScheduledMessageResponse) => scheduledMessage.id;
+
+/** Whether a scheduled message matches the search; `searchQuery` is the search field's text. */
+export type ScheduledMessageSearchFilter = (
+ scheduledMessage: ScheduledMessageResponse,
+ searchQuery: string,
+) => boolean;
+
+/** The default search: the message text contains the query, ignoring case. */
+export const matchesScheduledMessageText: ScheduledMessageSearchFilter = (
+ { message },
+ searchQuery,
+) => !!message.text?.toLocaleLowerCase().includes(searchQuery.trim().toLocaleLowerCase());
+
+const ScheduledMessageListLoadError = ({ onRetry }: { onRetry: () => void }) => {
+ const { icons } = useComponentsContext();
+ const { t } = useTranslationContext();
+ const {
+ theme: { semantics },
+ } = useTheme();
+
+ return (
+
+
+
+
+ {t('scheduledMessages.loadFailed.error', "Couldn't load scheduled messages")}
+
+
+
+
+ );
+};
+
+const ScheduledMessageListContent = ({
+ additionalFlatListProps,
+ getScheduledMessageActionItems,
+ onEditScheduledMessage,
+ searchFilter = matchesScheduledMessageText,
+ searchInputProps,
+ view,
+}: ScheduledMessageListProps) => {
+ const { error, hasMoreTail, isLoading, items, loadMore, reload } = useScheduledMessageList(view);
+ const { client } = useChatContext();
+ const { t, tDateTimeParser } = useTranslationContext();
+ const {
+ theme: {
+ scheduledMessages: { list: listTheme },
+ semantics,
+ },
+ } = useTheme();
+ const { icons, ScheduledMessageActionsSheet, ScheduledMessageListItem, ScheduleTimeSheet } =
+ useComponentsContext();
+ const {
+ copyScheduledMessageText,
+ deleteScheduledMessage,
+ notifyStillSending,
+ refuseDeletedQuote,
+ rescheduleScheduledMessage,
+ sendScheduledMessageNow,
+ } = useScheduledMessageActionHandlers();
+
+ const [searchQuery, setSearchQuery] = useState('');
+ const [actionTarget, setActionTarget] = useState();
+ const [rescheduleTarget, setRescheduleTarget] = useState();
+ const actionTargetDisplayName = useChannelPreviewDisplayName(
+ actionTarget ? getScheduledMessageChannel(client, actionTarget) : undefined,
+ )?.trim();
+
+ const visibleItems = useMemo(
+ () =>
+ items && searchQuery.trim() ? items.filter((item) => searchFilter(item, searchQuery)) : items,
+ [items, searchFilter, searchQuery],
+ );
+
+ // With nothing shown there is nothing to scroll, so the next page loads by itself: what the view
+ // or the search accepts may be on a page that isn't loaded yet.
+ const loadsFurther = !!visibleItems && !visibleItems.length && hasMoreTail && !error;
+ useEffect(() => {
+ if (loadsFurther && !isLoading) loadMore();
+ }, [isLoading, loadMore, loadsFurther]);
+
+ const confirmDelete = useCallback(
+ (scheduledMessage: ScheduledMessageResponse) => {
+ const name = scheduledMessage.channel?.name || actionTargetDisplayName;
+ Alert.alert(
+ t('scheduledMessages.deleteConfirm.title', 'Delete scheduled message?'),
+ name
+ ? t(
+ 'scheduledMessages.deleteConfirm.withName.text',
+ "This message to {{ name }} won't be sent. This can't be undone.",
+ { name },
+ )
+ : t(
+ 'scheduledMessages.deleteConfirm.text',
+ "This message won't be sent. This can't be undone.",
+ ),
+ [
+ { style: 'cancel', text: t('common.cancel.label', 'Cancel') },
+ {
+ onPress: () => {
+ deleteScheduledMessage(scheduledMessage);
+ },
+ style: 'destructive',
+ text: t('scheduledMessages.delete.label', 'Delete'),
+ },
+ ],
+ );
+ },
+ [actionTargetDisplayName, deleteScheduledMessage, t],
+ );
+
+ const actionTargetActions = useMemo(() => {
+ if (!actionTarget) return undefined;
+ return {
+ copyMessageText: () => copyScheduledMessageText(actionTarget),
+ delete: () => confirmDelete(actionTarget),
+ edit: onEditScheduledMessage ? () => onEditScheduledMessage(actionTarget) : undefined,
+ reschedule: () => {
+ if (!refuseDeletedQuote(actionTarget)) setRescheduleTarget(actionTarget);
+ },
+ sendNow: () => {
+ sendScheduledMessageNow(actionTarget);
+ },
+ };
+ }, [
+ actionTarget,
+ confirmDelete,
+ copyScheduledMessageText,
+ onEditScheduledMessage,
+ refuseDeletedQuote,
+ sendScheduledMessageNow,
+ ]);
+
+ const onPressItem = useCallback(
+ (scheduledMessage: ScheduledMessageResponse) => {
+ if (isScheduledMessageLocked(scheduledMessage)) {
+ notifyStillSending();
+ return;
+ }
+ setActionTarget(scheduledMessage);
+ },
+ [notifyStillSending],
+ );
+
+ const renderItem = useCallback(
+ ({ item }: { item: ScheduledMessageResponse }) => (
+
+ ),
+ [onPressItem, ScheduledMessageListItem],
+ );
+
+ const hasItems = !!items?.length;
+ const emptyState =
+ !items && error ? (
+
+ ) : !items || (isLoading && !hasItems) ? (
+
+ ) : !hasItems ? (
+
+ ) : (
+
+ );
+
+ const rescheduleChannel = rescheduleTarget
+ ? getScheduledMessageChannel(client, rescheduleTarget)
+ : undefined;
+
+ const closeActions = useStableCallback(() => setActionTarget(undefined));
+ const closeReschedule = useStableCallback(() => setRescheduleTarget(undefined));
+
+ const confirmReschedule = useStableCallback(async (scheduledAt: Date) => {
+ if (!rescheduleTarget) return {};
+ return { errorText: await rescheduleScheduledMessage(rescheduleTarget, scheduledAt) };
+ });
+
+ return (
+
+ {/* Shown while the first page loads too, so the screen doesn't shift once it arrives. */}
+ {hasItems || searchQuery || (!items && !error) ? (
+
+ ) : null}
+
+
+
+
+
+ {rescheduleTarget && rescheduleChannel ? (
+
+ ) : null}
+
+ );
+};
+
+/**
+ * A list of scheduled messages with search and actions: Reschedule, Send now, Delete and Copy, and
+ * Edit through `onEditScheduledMessage`. It works for any view and needs no `Channel`, so it also
+ * lists messages across channels. `ChannelScheduledMessages` renders it for a channel or thread,
+ * with editing in place.
+ */
+export const ScheduledMessageList = (props: ScheduledMessageListProps) => {
+ const { paginator, parentId } = props.view;
+ const hostId = `scheduled-message-list:${paginator.id}${parentId ? `:${parentId}` : ''}`;
+
+ return (
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ centered: {
+ alignItems: 'center',
+ flex: 1,
+ gap: primitives.spacingSm,
+ justifyContent: 'center',
+ paddingHorizontal: primitives.spacingMd,
+ paddingVertical: primitives.spacing3xl,
+ },
+ container: {
+ flex: 1,
+ },
+ errorBody: {
+ alignItems: 'center',
+ gap: primitives.spacingMd,
+ },
+ errorText: {
+ fontSize: primitives.typographyFontSizeMd,
+ lineHeight: primitives.typographyLineHeightNormal,
+ maxWidth: 200,
+ textAlign: 'center',
+ },
+ list: {
+ flex: 1,
+ },
+ listContent: {
+ flexGrow: 1,
+ paddingBottom: primitives.spacing3xl,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageListItem.tsx b/package/src/components/ScheduledMessages/ScheduledMessageListItem.tsx
new file mode 100644
index 0000000000..9809874265
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageListItem.tsx
@@ -0,0 +1,248 @@
+import React, { useMemo } from 'react';
+import { I18nManager, Pressable, StyleSheet, Text, View } from 'react-native';
+
+import type { LocalScheduledMessage } from 'stream-chat';
+import { nsToDate, SCHEDULED_MESSAGE_STATUS, toScheduledMessagePreview } from 'stream-chat';
+
+import { getScheduledMessageChannel } from './hooks/useScheduledMessageActionHandlers';
+
+import { getScheduledMessageFailureText } from './utils/failureReason';
+import { hasDeletedQuote } from './utils/quote';
+
+import { formatScheduledDateTime } from './utils/scheduledTimeLabels';
+import { isScheduledMessageSending, isScheduledMessageUploading } from './utils/status';
+
+import { useChatContext } from '../../contexts/chatContext/ChatContext';
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { useTranslationContext } from '../../contexts/translationContext/TranslationContext';
+import { useMessagePreviewIcon, useMessagePreviewText } from '../../hooks';
+import { components, primitives } from '../../theme';
+import { useChannelPreviewDisplayName } from '../ChannelPreview/hooks/useChannelPreviewDisplayName';
+import { ChannelAvatar } from '../ui/Avatar/ChannelAvatar';
+import { Spinner } from '../UIComponents/Spinner';
+
+export type ScheduledMessageListItemProps = {
+ onPress: (scheduledMessage: LocalScheduledMessage) => void;
+ scheduledMessage: LocalScheduledMessage;
+};
+
+export const ScheduledMessageListItem = ({
+ onPress,
+ scheduledMessage,
+}: ScheduledMessageListItemProps) => {
+ const { client } = useChatContext();
+ const { icons } = useComponentsContext();
+ const { t, tDateTimeParser } = useTranslationContext();
+ const {
+ theme: {
+ scheduledMessages: { listItem },
+ semantics,
+ },
+ } = useTheme();
+
+ const channel = useMemo(
+ () => getScheduledMessageChannel(client, scheduledMessage),
+ [client, scheduledMessage],
+ );
+ const displayName = useChannelPreviewDisplayName(channel)?.trim();
+ const channelName = scheduledMessage.channel?.name || displayName;
+
+ const message = useMemo(() => toScheduledMessagePreview(scheduledMessage), [scheduledMessage]);
+ const PreviewIcon = useMessagePreviewIcon({ message });
+ const previewText = useMessagePreviewText({ message });
+
+ const {
+ parent_id: parentId,
+ quoted_message: quotedMessage,
+ quoted_message_id: quotedMessageId,
+ } = scheduledMessage.message;
+ const quotedName = quotedMessage?.user?.name;
+ const prefix = parentId
+ ? t('scheduledMessages.threadReply.prefix', 'Thread reply:')
+ : quotedMessageId
+ ? quotedName
+ ? t('scheduledMessages.replyTo.prefix', 'Reply to {{ name }}:', { name: quotedName })
+ : t('scheduledMessages.reply.prefix', 'Reply:')
+ : undefined;
+
+ const isFailed = scheduledMessage.status === SCHEDULED_MESSAGE_STATUS.Failed;
+ const isSending = isScheduledMessageSending(scheduledMessage);
+ const failureText = isFailed
+ ? getScheduledMessageFailureText(t, scheduledMessage)
+ : hasDeletedQuote(scheduledMessage)
+ ? t(
+ 'scheduledMessages.quoteDeleted.text',
+ 'The quoted message was deleted. Edit it to remove the quote.',
+ )
+ : undefined;
+ const sendTime = t('scheduledMessages.sendTime.label', 'Send {{ time }}', {
+ time: formatScheduledDateTime(nsToDate(scheduledMessage.scheduled_at), { t, tDateTimeParser }),
+ });
+
+ return (
+ onPress(scheduledMessage)}
+ style={[
+ styles.container,
+ { borderBottomColor: semantics.borderCoreSubtle },
+ listItem.container,
+ ]}
+ testID={`scheduled-message-item-${scheduledMessage.id}`}
+ >
+ {({ pressed }) => (
+
+
+ {sendTime}
+
+
+
+
+
+ {channelName ? (
+
+ {channelName}
+
+ ) : null}
+
+ {PreviewIcon && !!message.attachments?.length ? (
+
+ ) : null}
+
+ {prefix ? `${prefix} ${previewText?.trim() ?? ''}` : previewText?.trim()}
+
+
+
+ {failureText ? (
+
+
+
+
+
+ {failureText}
+
+
+ ) : isSending ? (
+
+
+
+
+
+ {isScheduledMessageUploading(scheduledMessage)
+ ? t('scheduledMessages.uploading.label', 'Uploading…')
+ : t('scheduledMessages.sending.label', 'Sending…')}
+
+
+ ) : null}
+
+
+
+ )}
+
+ );
+};
+
+const styles = StyleSheet.create({
+ channelName: {
+ fontSize: primitives.typographyFontSizeSm,
+ fontWeight: primitives.typographyFontWeightSemiBold,
+ lineHeight: primitives.typographyLineHeightNormal,
+ writingDirection: I18nManager.isRTL ? 'rtl' : 'ltr',
+ },
+ container: {
+ borderBottomWidth: 1,
+ minHeight: 48,
+ paddingHorizontal: primitives.spacingXxs,
+ },
+ content: {
+ flex: 1,
+ gap: primitives.spacingXs,
+ },
+ contentContainer: {
+ borderRadius: primitives.radiusMd,
+ gap: primitives.spacingXs,
+ minHeight: 48,
+ padding: primitives.spacingMd,
+ },
+ messageGroup: {
+ gap: primitives.spacingXxs,
+ paddingVertical: primitives.spacingXxxs,
+ },
+ preview: {
+ flexShrink: 1,
+ fontSize: primitives.typographyFontSizeMd,
+ lineHeight: primitives.typographyLineHeightNormal,
+ },
+ previewRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: primitives.spacingXxs,
+ },
+ row: {
+ alignItems: 'flex-start',
+ flexDirection: 'row',
+ gap: primitives.spacingSm,
+ },
+ status: {
+ alignItems: 'flex-start',
+ flexDirection: 'row',
+ gap: primitives.spacingXxs,
+ },
+ // Keeps the icon level with the first line when the reason wraps.
+ statusIcon: {
+ paddingVertical: primitives.spacingXxxs,
+ },
+ statusText: {
+ flexShrink: 1,
+ fontSize: primitives.typographyFontSizeSm,
+ lineHeight: primitives.typographyLineHeightNormal,
+ },
+ time: {
+ fontSize: primitives.typographyFontSizeSm,
+ lineHeight: primitives.typographyLineHeightNormal,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageListLoadingSkeleton.tsx b/package/src/components/ScheduledMessages/ScheduledMessageListLoadingSkeleton.tsx
new file mode 100644
index 0000000000..da4dddc0df
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageListLoadingSkeleton.tsx
@@ -0,0 +1,131 @@
+import React, { useMemo } from 'react';
+import { StyleSheet, View } from 'react-native';
+
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { primitives } from '../../theme';
+import { NativeShimmerView } from '../UIComponents/NativeShimmerView';
+
+const ROW_COUNT = 6;
+
+const SkeletonBlock = ({ style }: { style: React.ComponentProps['style'] }) => {
+ const {
+ theme: {
+ scheduledMessageListSkeleton: { animationTime },
+ semantics,
+ },
+ } = useTheme();
+
+ return (
+
+
+
+ );
+};
+
+/** A loading row shaped like `ScheduledMessageListItem`: the send time, then avatar and message. */
+const SkeletonRow = () => {
+ const styles = useStyles();
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export const ScheduledMessageListLoadingSkeleton = () => {
+ const styles = useStyles();
+
+ return (
+
+ {Array.from({ length: ROW_COUNT }).map((_, index) => (
+
+ ))}
+
+ );
+};
+
+ScheduledMessageListLoadingSkeleton.displayName =
+ 'ScheduledMessageListLoadingSkeleton{scheduledMessageListSkeleton}';
+
+const useStyles = () => {
+ const {
+ theme: { scheduledMessageListSkeleton, semantics },
+ } = useTheme();
+
+ return useMemo(
+ () =>
+ StyleSheet.create({
+ avatar: {
+ borderRadius: primitives.radiusMax,
+ height: 48,
+ overflow: 'hidden',
+ width: 48,
+ ...scheduledMessageListSkeleton.avatar,
+ },
+ body: {
+ flexDirection: 'row',
+ gap: primitives.spacingSm,
+ ...scheduledMessageListSkeleton.body,
+ },
+ container: {
+ borderBottomColor: semantics.borderCoreSubtle,
+ borderBottomWidth: 1,
+ paddingHorizontal: primitives.spacingXxs,
+ ...scheduledMessageListSkeleton.container,
+ },
+ content: {
+ gap: primitives.spacingMd,
+ padding: primitives.spacingMd,
+ ...scheduledMessageListSkeleton.content,
+ },
+ list: {
+ gap: primitives.spacingXs,
+ paddingTop: primitives.spacingXs,
+ ...scheduledMessageListSkeleton.list,
+ },
+ message: {
+ borderRadius: primitives.radiusMax,
+ height: 16,
+ maxWidth: 260,
+ overflow: 'hidden',
+ width: '100%',
+ ...scheduledMessageListSkeleton.message,
+ },
+ textContainer: {
+ flex: 1,
+ gap: primitives.spacingXs,
+ ...scheduledMessageListSkeleton.textContainer,
+ },
+ time: {
+ borderRadius: primitives.radiusMax,
+ height: 12,
+ overflow: 'hidden',
+ width: 120,
+ ...scheduledMessageListSkeleton.time,
+ },
+ title: {
+ borderRadius: primitives.radiusMax,
+ height: 12,
+ overflow: 'hidden',
+ width: 96,
+ ...scheduledMessageListSkeleton.title,
+ },
+ }),
+ [scheduledMessageListSkeleton, semantics.borderCoreSubtle],
+ );
+};
diff --git a/package/src/components/ScheduledMessages/ScheduledMessageSaveButton.tsx b/package/src/components/ScheduledMessages/ScheduledMessageSaveButton.tsx
new file mode 100644
index 0000000000..281738770e
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessageSaveButton.tsx
@@ -0,0 +1,52 @@
+import React, { useEffect } from 'react';
+
+import type { EditingAuditState, MessageComposerState } from 'stream-chat';
+import { CORE_NOTIFICATION_TYPE, ScheduledMessageBlockReason } from 'stream-chat';
+
+import { useEditedScheduledMessage } from './hooks/useEditedScheduledMessage';
+import { RescheduleFailedMessageButton } from './RescheduleFailedMessageButton';
+import { isDeletedQuotedMessage } from './utils/quote';
+
+import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer';
+import { useStateStore } from '../../hooks/useStateStore';
+import { EditButton } from '../MessageInput/components/OutputButtons/EditButton';
+
+const quotedMessageSelector = (state: MessageComposerState) => ({
+ quotedMessage: state.quotedMessage,
+});
+
+const editingAuditSelector = (state: EditingAuditState) => state;
+
+/**
+ * The save button while the composer edits a scheduled message. Save is disabled while the message
+ * can't be scheduled or quotes a deleted message, and a toast says so when a command is the reason.
+ */
+export const ScheduledMessageSaveButton = () => {
+ const messageComposer = useMessageComposer();
+ const { isFailed } = useEditedScheduledMessage();
+ const { quotedMessage } = useStateStore(messageComposer.state, quotedMessageSelector);
+ // The block reason and the empty check read the composition, so this re-renders on every change
+ // to it. The parent's re-render isn't enough: React Compiler caches this element (it has no props).
+ useStateStore(messageComposer.editingAuditState, editingAuditSelector);
+
+ const { scheduleBlockReason } = messageComposer;
+ const blockedByCommand = scheduleBlockReason === ScheduledMessageBlockReason.Command;
+ const disabled =
+ messageComposer.compositionIsEmpty ||
+ !!scheduleBlockReason ||
+ isDeletedQuotedMessage(quotedMessage);
+
+ useEffect(() => {
+ if (!blockedByCommand) return;
+ messageComposer.notifyWarning('This message cannot be scheduled', {
+ metadata: { reason: ScheduledMessageBlockReason.Command },
+ type: CORE_NOTIFICATION_TYPE.scheduledMessageBlocked,
+ });
+ }, [blockedByCommand, messageComposer]);
+
+ return isFailed ? (
+
+ ) : (
+
+ );
+};
diff --git a/package/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/package/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx
new file mode 100644
index 0000000000..60e76527bc
--- /dev/null
+++ b/package/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx
@@ -0,0 +1,213 @@
+import React, { useEffect, useMemo } from 'react';
+import { Pressable, StyleSheet, Text, useColorScheme } from 'react-native';
+
+import Animated from 'react-native-reanimated';
+
+import type { ChannelLifecycleState } from 'stream-chat';
+import { nsToDate, SCHEDULED_MESSAGE_STATUS } from 'stream-chat';
+
+import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit';
+import { useChannelScheduledMessages } from './hooks/useChannelScheduledMessages';
+import { useChannelWideScheduledMessagesView } from './hooks/useChannelWideScheduledMessagesView';
+import { useEditedScheduledMessage } from './hooks/useEditedScheduledMessage';
+
+import { isPendingScheduledMessage } from './utils/actions';
+
+import { formatScheduledDateTime } from './utils/scheduledTimeLabels';
+
+import { useAnnounceOnStateChange } from '../../a11y/hooks/useAnnounceOnStateChange';
+
+import { useChannelContext } from '../../contexts/channelContext/ChannelContext';
+import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext';
+import { useMessageInputContext } from '../../contexts/messageInputContext/MessageInputContext';
+import { useMessagesContext } from '../../contexts/messagesContext/MessagesContext';
+import { useTheme } from '../../contexts/themeContext/ThemeContext';
+import { useThreadContext } from '../../contexts/threadContext/ThreadContext';
+import { useTranslationContext } from '../../contexts/translationContext/TranslationContext';
+import { useStateStore } from '../../hooks/useStateStore';
+import { components, primitives } from '../../theme';
+import { transitions } from '../../utils/animations/transitions';
+
+/** The gap between the banner and the composer. */
+const COMPOSER_GAP = 16;
+
+// The list keeps this much room above the banner, as it does above a floating composer.
+const LIST_GAP = 16;
+
+const pendingDisposalSelector = ({ pendingDisposal }: ChannelLifecycleState) => ({
+ pendingDisposal,
+});
+
+const ScheduledMessagesBannerContent = () => {
+ const { channel } = useChannelContext();
+ const { thread } = useThreadContext();
+ const { onScheduledMessagesBannerPress } = useMessagesContext();
+ const { messageInputHeightStore } = useMessageInputContext();
+ const { icons } = useComponentsContext();
+ const { t, tDateTimeParser } = useTranslationContext();
+ const {
+ theme: {
+ scheduledMessages: { banner: bannerTheme },
+ semantics,
+ },
+ } = useTheme();
+ const scheme = useColorScheme();
+ const shadow = scheme === 'dark' ? primitives.darkElevation3 : primitives.lightElevation3;
+
+ const channelWideView = useChannelWideScheduledMessagesView(channel);
+ // A thread's banner counts only the thread's scheduled replies.
+ const view = thread ? thread.scheduledMessages : channelWideView;
+ const { scheduledMessages } = useChannelScheduledMessages(view);
+ const { isLimitReached, maxPerChannel } = useChannelScheduledMessageLimit(channel);
+ const { failed, pending } = useMemo(
+ () => ({
+ failed: scheduledMessages.filter(({ status }) => status === SCHEDULED_MESSAGE_STATUS.Failed),
+ pending: scheduledMessages.filter(isPendingScheduledMessage),
+ }),
+ [scheduledMessages],
+ );
+ const failedCount = failed.length;
+ const pendingCount = pending.length;
+
+ const { editedScheduledMessage } = useEditedScheduledMessage();
+
+ // Hidden while the composer edits a scheduled message, which the banner would point back to.
+ const isVisible = !editedScheduledMessage && (failedCount > 0 || pendingCount > 0);
+
+ useEffect(() => {
+ if (!isVisible) messageInputHeightStore.setBannerHeight(0);
+ }, [isVisible, messageInputHeightStore]);
+
+ useEffect(() => () => messageInputHeightStore.setBannerHeight(0), [messageInputHeightStore]);
+
+ const isFailure = failedCount > 0;
+ const count = isFailure ? failedCount : pendingCount;
+ const single = isFailure ? failed[0] : pending[0];
+
+ let label: string;
+ if (isFailure) {
+ label = t('scheduledMessages.banner.failed.text', '{{ count }} failed to send', {
+ count: failedCount,
+ });
+ } else if (!thread && isLimitReached && maxPerChannel !== undefined) {
+ label = t(
+ 'scheduledMessages.banner.limit.text',
+ '{{ count }} of {{ max }} scheduled messages',
+ {
+ count: pendingCount,
+ max: maxPerChannel,
+ },
+ );
+ } else if (pendingCount === 1 && single) {
+ label = t('scheduledMessages.banner.single.text', 'Scheduled for {{ time }}', {
+ time: formatScheduledDateTime(nsToDate(single.scheduled_at), { t, tDateTimeParser }),
+ });
+ } else {
+ label = t('scheduledMessages.banner.count.text', '{{ count }} scheduled messages', {
+ count: pendingCount,
+ });
+ }
+
+ // `accessibilityLiveRegion` is Android-only, so changes are announced through the SDK's announcer.
+ useAnnounceOnStateChange(isVisible ? label : null);
+
+ if (!isVisible) return null;
+
+ const linkLabel =
+ count === 1
+ ? t('scheduledMessages.view.label', 'View')
+ : t('scheduledMessages.viewAll.label', 'View all');
+
+ const onPress = onScheduledMessagesBannerPress
+ ? () => onScheduledMessagesBannerPress({ channel, thread: thread ?? undefined })
+ : undefined;
+
+ const Icon = isFailure ? icons.ExclamationCircleOutline : icons.Time;
+
+ return (
+
+ messageInputHeightStore.setBannerHeight(layout.height + LIST_GAP)
+ }
+ pointerEvents='box-none'
+ style={[styles.container, bannerTheme.container]}
+ >
+
+
+
+ {label}
+
+ {onPress ? (
+
+ {linkLabel}
+
+ ) : null}
+
+
+ );
+};
+
+/**
+ * The banner above the composer that sums up the scheduled messages of the channel, or of the
+ * thread in a thread. It opens them through `onScheduledMessagesBannerPress`.
+ */
+export const ScheduledMessagesBanner = () => {
+ const { channel } = useChannelContext();
+ const { pendingDisposal } = useStateStore(channel.state, pendingDisposalSelector);
+
+ // A deleted or left channel stays on screen, but can't be read or scheduled in any more.
+ return pendingDisposal ? null : ;
+};
+
+const styles = StyleSheet.create({
+ banner: {
+ alignItems: 'center',
+ borderRadius: primitives.radiusMax,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: primitives.spacingSm,
+ minHeight: 44,
+ paddingHorizontal: primitives.spacingMd,
+ paddingVertical: primitives.spacingSm,
+ },
+ container: {
+ marginBottom: COMPOSER_GAP,
+ marginHorizontal: primitives.spacingMd,
+ },
+ label: {
+ flex: 1,
+ fontSize: primitives.typographyFontSizeXs,
+ fontWeight: primitives.typographyFontWeightSemiBold,
+ lineHeight: primitives.typographyLineHeightTight,
+ },
+ link: {
+ fontSize: primitives.typographyFontSizeXs,
+ fontWeight: primitives.typographyFontWeightRegular,
+ lineHeight: primitives.typographyLineHeightTight,
+ },
+});
diff --git a/package/src/components/ScheduledMessages/__tests__/ScheduledMessages.test.tsx b/package/src/components/ScheduledMessages/__tests__/ScheduledMessages.test.tsx
new file mode 100644
index 0000000000..15a0b62155
--- /dev/null
+++ b/package/src/components/ScheduledMessages/__tests__/ScheduledMessages.test.tsx
@@ -0,0 +1,1380 @@
+import React from 'react';
+import { Alert, AppState, Keyboard, Platform, Pressable, Text } from 'react-native';
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react-native';
+import type {
+ Channel as ChannelType,
+ MessageComposer,
+ ScheduledMessageResponse,
+ StreamChat,
+} from 'stream-chat';
+import {
+ CORE_NOTIFICATION_TYPE,
+ dateToNs,
+ nsToDate,
+ ScheduledMessageBlockReason,
+ ScheduledMessagePaginator,
+ ScheduledMessagesView,
+ StreamAPIError,
+} from 'stream-chat';
+
+import { OverlayProvider } from '../../../contexts';
+import {
+ type MessageComposerAPIContextValue,
+ useMessageComposerAPIContext,
+} from '../../../contexts/messageComposerContext/MessageComposerAPIContext';
+import { useMessageComposer } from '../../../contexts/messageInputContext/hooks/useMessageComposer';
+import {
+ type MessageInputContextValue,
+ useMessageInputContext,
+} from '../../../contexts/messageInputContext/MessageInputContext';
+import { initiateClientWithChannels } from '../../../mock-builders/api/initiateClientWithChannels';
+import { NativeHandlers, type PickDateTimeOptions } from '../../../native';
+import { Channel } from '../../Channel/Channel';
+import { Chat } from '../../Chat/Chat';
+import { SendButton } from '../../MessageInput/components/OutputButtons/SendButton';
+import { MessageComposer as MessageComposerView } from '../../MessageInput/MessageComposer';
+import { ChannelScheduledMessages } from '../ChannelScheduledMessages';
+import { useEditedScheduledMessage } from '../hooks/useEditedScheduledMessage';
+import { ScheduledMessageEditComposer } from '../ScheduledMessageEditComposer';
+import { ScheduledMessageList } from '../ScheduledMessageList';
+import { ScheduledMessagesBanner } from '../ScheduledMessagesBanner';
+import { ScheduleMessageSheet } from '../ScheduleMessageSheet';
+import { ScheduleTimeSheet } from '../ScheduleTimeSheet';
+
+// The real modal runs `dismiss` callbacks only after iOS reports the dismissal, which never
+// happens in tests. This one runs `onClose` and then the callback, as the modal does. While
+// `mockHeldSheetCloses` is set, a close waits in it, as if the sheet were still sliding away.
+let mockHeldSheetCloses: Array<() => void> | undefined;
+jest.mock('../../UIComponents/BottomSheetModal', () => {
+ const React = require('react');
+ const {
+ BottomSheetProvider,
+ } = require('../../../contexts/bottomSheetContext/BottomSheetContext');
+ return {
+ BottomSheetModal: ({
+ children,
+ onClose,
+ visible,
+ }: {
+ children: React.ReactNode;
+ onClose: () => void;
+ visible: boolean;
+ }) => {
+ if (!visible) {
+ return null;
+ }
+ const runClose = (callback?: () => void) => {
+ const finish = () => {
+ onClose();
+ callback?.();
+ };
+ if (mockHeldSheetCloses) mockHeldSheetCloses.push(finish);
+ else finish();
+ };
+ return (
+
+ {children}
+
+ );
+ },
+ };
+});
+
+let idCounter = 0;
+
+const generateScheduledMessage = (
+ channel: ChannelType,
+ overrides: Partial & {
+ message?: Partial;
+ } = {},
+): ScheduledMessageResponse => {
+ idCounter += 1;
+ const { message, ...rest } = overrides;
+ const now = dateToNs(new Date());
+ return {
+ cid: channel.cid,
+ created_at: now,
+ id: `scheduled-${idCounter}`,
+ message: { custom: {}, text: `Scheduled text ${idCounter}`, ...message },
+ scheduled_at: dateToNs(new Date(Date.now() + 24 * 60 * 60 * 1000)),
+ status: 'scheduled',
+ updated_at: now,
+ user: { id: 'me' } as ScheduledMessageResponse['user'],
+ ...rest,
+ } as ScheduledMessageResponse;
+};
+
+const ingest = (channel: ChannelType, scheduledMessages: ScheduledMessageResponse[]) =>
+ act(() => {
+ channel.scheduledMessagesPaginator.hydrate(scheduledMessages);
+ });
+
+describe('ScheduledMessagesBanner', () => {
+ let client: StreamChat;
+ let channel: ChannelType;
+
+ const renderBanner = (onScheduledMessagesBannerPress?: jest.Mock) =>
+ render(
+
+
+
+
+
+
+ ,
+ );
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ jest.spyOn(channel, 'ensureScheduledMessagesLoaded').mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ });
+
+ it('renders nothing without scheduled messages', async () => {
+ renderBanner();
+ ingest(channel, []);
+
+ await waitFor(() => expect(screen.queryByTestId('scheduled-messages-banner')).toBeNull());
+ });
+
+ it('shows the time of a single scheduled message and opens the list', async () => {
+ const onPress = jest.fn();
+ renderBanner(onPress);
+ ingest(channel, [generateScheduledMessage(channel)]);
+
+ await waitFor(() => expect(screen.getByText(/^Scheduled for /)).toBeTruthy());
+ fireEvent.press(screen.getByTestId('scheduled-messages-banner'));
+
+ expect(screen.getByText('View')).toBeTruthy();
+ expect(onPress).toHaveBeenCalledWith({ channel, thread: undefined });
+ });
+
+ it('counts several scheduled messages, thread replies included', async () => {
+ renderBanner(jest.fn());
+ ingest(channel, [
+ generateScheduledMessage(channel),
+ generateScheduledMessage(channel, { message: { parent_id: 'parent-1' } }),
+ ]);
+
+ await waitFor(() => expect(screen.getByText('2 scheduled messages')).toBeTruthy());
+ expect(screen.getByText('View all')).toBeTruthy();
+ });
+
+ it('shows failed messages before the scheduled ones', async () => {
+ renderBanner(jest.fn());
+ ingest(channel, [
+ generateScheduledMessage(channel),
+ generateScheduledMessage(channel, { failure_reason: 'internal_error', status: 'failed' }),
+ ]);
+
+ await waitFor(() => expect(screen.getByText('1 failed to send')).toBeTruthy());
+ });
+
+ it('hides the link when the app has nowhere to open the list', async () => {
+ renderBanner();
+ ingest(channel, [generateScheduledMessage(channel)]);
+
+ await waitFor(() => expect(screen.getByTestId('scheduled-messages-banner')).toBeTruthy());
+ expect(screen.queryByText('View')).toBeNull();
+ });
+});
+
+describe('ScheduledMessageList', () => {
+ let client: StreamChat;
+ let channel: ChannelType;
+
+ const renderList = (props: Partial> = {}) =>
+ render(
+
+
+
+
+
+
+ ,
+ );
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ jest.spyOn(channel.scheduledMessagesPaginator, 'reload').mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ });
+
+ // A list across channels: a view of a paginator of its own, with no Channel around it.
+ const renderGlobalList = async (
+ scheduledMessages: ScheduledMessageResponse[],
+ props: Partial> = {},
+ ) => {
+ const paginator = new ScheduledMessagePaginator({ client });
+ jest.spyOn(paginator, 'reload').mockResolvedValue(undefined);
+ const view = new ScheduledMessagesView({ paginator });
+ render(
+
+
+
+
+ ,
+ );
+ act(() => {
+ paginator.hydrate(scheduledMessages);
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId(`scheduled-message-item-${scheduledMessages[0].id}`)).toBeTruthy(),
+ );
+ return paginator;
+ };
+
+ it('lists the earliest message first and shows the failure reason', async () => {
+ const later = generateScheduledMessage(channel, {
+ message: { text: 'later' },
+ scheduled_at: dateToNs(new Date(Date.now() + 2 * 60 * 60 * 1000)),
+ });
+ const earlier = generateScheduledMessage(channel, {
+ failure_reason: 'channel_frozen',
+ message: { text: 'earlier' },
+ scheduled_at: dateToNs(new Date(Date.now() + 60 * 60 * 1000)),
+ status: 'failed',
+ });
+ renderList();
+ ingest(channel, [later, earlier]);
+
+ await waitFor(() => expect(screen.getByText('earlier')).toBeTruthy());
+ const texts = screen.getAllByText(/^(earlier|later)$/).map((node) => node.props.children);
+ expect(texts).toEqual(['earlier', 'later']);
+ expect(screen.getByText('This channel is frozen.')).toBeTruthy();
+ });
+
+ it("lists only a thread's replies when given the thread's view", async () => {
+ const view = new ScheduledMessagesView({
+ paginator: channel.scheduledMessagesPaginator,
+ scope: { parentId: 'parent-1', type: 'thread' },
+ });
+ renderList({ view });
+ ingest(channel, [
+ generateScheduledMessage(channel, { message: { text: 'In the channel' } }),
+ generateScheduledMessage(channel, {
+ message: { parent_id: 'parent-1', text: 'In the thread' },
+ }),
+ ]);
+
+ await waitFor(() => expect(screen.getByText(/In the thread/)).toBeTruthy());
+ expect(screen.queryByText(/In the channel/)).toBeNull();
+ });
+
+ it('filters by the search text', async () => {
+ renderList();
+ ingest(channel, [
+ generateScheduledMessage(channel, { message: { text: 'Launch moved to Monday' } }),
+ generateScheduledMessage(channel, { message: { text: 'Kickoff notes' } }),
+ ]);
+
+ await waitFor(() => expect(screen.getByText('Kickoff notes')).toBeTruthy());
+ fireEvent.changeText(screen.getByLabelText('Search scheduled messages'), 'launch');
+
+ await waitFor(() => expect(screen.queryByText('Kickoff notes')).toBeNull());
+ expect(screen.getByText('Launch moved to Monday')).toBeTruthy();
+ });
+
+ it('keeps the paginator order for messages due at the same time', async () => {
+ const at = dateToNs(new Date(Date.now() + 60 * 60 * 1000));
+ const older = generateScheduledMessage(channel, {
+ created_at: dateToNs(new Date(Date.now() - 2000)),
+ message: { text: 'zulu' },
+ scheduled_at: at,
+ });
+ const newer = generateScheduledMessage(channel, {
+ created_at: dateToNs(new Date(Date.now() - 1000)),
+ message: { text: 'alpha' },
+ scheduled_at: at,
+ });
+ await renderGlobalList([newer, older]);
+
+ const texts = screen.getAllByText(/^(zulu|alpha)$/).map((node) => node.props.children);
+ expect(texts).toEqual(['zulu', 'alpha']);
+ });
+
+ it('searches with the filter the app passes', async () => {
+ const byChannel = generateScheduledMessage(channel, {
+ channel: { name: 'Launch room' } as never,
+ message: { text: 'Agenda' },
+ });
+ const other = generateScheduledMessage(channel, { message: { text: 'Notes' } });
+ await renderGlobalList([byChannel, other], {
+ searchFilter: (scheduledMessage, query) =>
+ !!scheduledMessage.channel?.name?.toLowerCase().includes(query.toLowerCase()),
+ });
+
+ fireEvent.changeText(screen.getByLabelText('Search scheduled messages'), 'launch');
+
+ await waitFor(() => expect(screen.queryByText('Notes')).toBeNull());
+ expect(screen.getByText('Agenda')).toBeTruthy();
+ });
+
+ it('loads the next page while nothing loaded matches the search', async () => {
+ const paginator = await renderGlobalList([
+ generateScheduledMessage(channel, { message: { text: 'Kickoff notes' } }),
+ ]);
+ const toTail = jest.spyOn(paginator, 'toTail').mockResolvedValue(undefined);
+ act(() => {
+ paginator.state.partialNext({ hasMoreTail: true });
+ });
+ expect(toTail).not.toHaveBeenCalled();
+
+ fireEvent.changeText(screen.getByLabelText('Search scheduled messages'), 'launch');
+
+ await waitFor(() => expect(toTail).toHaveBeenCalled());
+ });
+
+ it('shows the empty state', async () => {
+ renderList();
+ ingest(channel, []);
+
+ await waitFor(() => expect(screen.getByText('No scheduled messages')).toBeTruthy());
+ });
+
+ it('shows the scheduled messages skeleton until the first page arrives', async () => {
+ renderList();
+
+ expect(screen.getByTestId('scheduled-message-list-loading-skeleton')).toBeTruthy();
+
+ ingest(channel, []);
+
+ await waitFor(() => expect(screen.getByText('No scheduled messages')).toBeTruthy());
+ expect(screen.queryByTestId('scheduled-message-list-loading-skeleton')).toBeNull();
+ });
+
+ it('shows a message the server is sending as sending and keeps it from being acted on', async () => {
+ const sending = generateScheduledMessage(channel, {
+ message: { text: 'On its way' },
+ status: 'sending',
+ });
+ const notify = jest.spyOn(client.notifications, 'add');
+ renderList();
+ ingest(channel, [sending]);
+
+ await waitFor(() => expect(screen.getByText('Sending…')).toBeTruthy());
+ expect(screen.queryByText('Uploading…')).toBeNull();
+
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${sending.id}`));
+
+ expect(screen.queryByTestId('scheduled-message-action-delete')).toBeNull();
+ expect(notify).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Still sending. Try again in a moment.' }),
+ );
+ });
+
+ it('lets a message being scheduled be acted on while its request waits in the offline queue', async () => {
+ const pending = {
+ ...generateScheduledMessage(channel, { message: { text: 'Queued' } }),
+ localMetadata: { pending: true, requestState: 'queued' as const },
+ };
+ const notify = jest.spyOn(client.notifications, 'add');
+ renderList();
+ ingest(channel, [pending]);
+ await waitFor(() => expect(screen.getByText('Sending…')).toBeTruthy());
+
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${pending.id}`));
+
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-delete')).toBeTruthy());
+ expect(screen.getByTestId('scheduled-message-action-sendNow')).toBeTruthy();
+ expect(notify).not.toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Still sending. Try again in a moment.' }),
+ );
+ });
+
+ it('shows a message being scheduled as uploading, then sending, and keeps it from being acted on', async () => {
+ const upload = (() => {
+ let resolve: (value: { file: string }) => void = () => undefined;
+ const promise = new Promise<{ file: string }>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+ })();
+ jest.spyOn(client.uploadManager, 'upload').mockReturnValue(upload.promise as never);
+ let respond: (value: unknown) => void = () => undefined;
+ jest.spyOn(client, 'sendMessage').mockReturnValue(
+ new Promise((resolve) => {
+ respond = resolve;
+ }) as never,
+ );
+ const notify = jest.spyOn(client.notifications, 'add');
+ renderList();
+ ingest(channel, []);
+
+ let scheduling: Promise = Promise.resolve();
+ act(() => {
+ scheduling = channel.messageOperations.scheduleMessage({
+ localMessage: {
+ attachments: [
+ {
+ localMetadata: {
+ file: { name: 'photo.png', type: 'image/png', uri: 'file://photo.png' },
+ id: 'upload-1',
+ uploadState: 'uploading',
+ },
+ type: 'image',
+ },
+ ],
+ id: 'pending-1',
+ text: 'With a photo',
+ } as never,
+ message: { id: 'pending-1', text: 'With a photo' },
+ options: { scheduled_at: new Date(Date.now() + 60 * 60 * 1000) },
+ });
+ });
+
+ await waitFor(() => expect(screen.getByText('Uploading…')).toBeTruthy());
+ fireEvent.press(screen.getByTestId('scheduled-message-item-pending-1'));
+ expect(screen.queryByTestId('scheduled-message-action-delete')).toBeNull();
+ expect(notify).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Still sending. Try again in a moment.' }),
+ );
+
+ await act(async () => {
+ upload.resolve({ file: 'https://example.com/photo.png' });
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(screen.getByText('Sending…')).toBeTruthy());
+ expect(screen.queryByText('Uploading…')).toBeNull();
+
+ const confirmed = generateScheduledMessage(channel, {
+ id: 'pending-1',
+ message: { text: 'With a photo' },
+ });
+ await act(async () => {
+ respond({ duration: '', message: { id: 'pending-1' }, scheduled_message: confirmed });
+ await scheduling;
+ });
+
+ expect(screen.queryByText('Sending…')).toBeNull();
+ fireEvent.press(screen.getByTestId('scheduled-message-item-pending-1'));
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-delete')).toBeTruthy());
+ });
+
+ it('deletes a scheduled message after the confirmation', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'To delete' } });
+ const { data } = channel.state.getLatestValue();
+ channel.state.partialNext({
+ data: { ...data, custom: { ...data?.custom, name: 'Maya Ross' } },
+ });
+ const deleteSpy = jest
+ .spyOn(channel.messageOperations, 'deleteScheduledMessage')
+ .mockResolvedValue(scheduledMessage);
+ const alertSpy = jest.spyOn(Alert, 'alert');
+ renderList();
+ ingest(channel, [scheduledMessage]);
+
+ await waitFor(() => expect(screen.getByText('To delete')).toBeTruthy());
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-delete')).toBeTruthy());
+ expect(screen.getByTestId('scheduled-message-action-edit')).toBeTruthy();
+
+ fireEvent.press(screen.getByTestId('scheduled-message-action-delete'));
+ await waitFor(() => expect(alertSpy).toHaveBeenCalled());
+ expect(alertSpy.mock.calls[0][1]).toBe(
+ "This message to Maya Ross won't be sent. This can't be undone.",
+ );
+ const buttons = alertSpy.mock.calls[0][2] ?? [];
+ await act(() => {
+ buttons.find((button) => button.style === 'destructive')?.onPress?.();
+ return Promise.resolve();
+ });
+
+ expect(deleteSpy).toHaveBeenCalledWith(scheduledMessage.id);
+ });
+
+ it('opens the message in a composer of its own, leaving the channel draft alone', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Edit me' } });
+ act(() => {
+ channel.messageComposer.textComposer.setText('My draft');
+ });
+ renderList();
+ ingest(channel, [scheduledMessage]);
+
+ await waitFor(() =>
+ expect(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`)).toBeTruthy(),
+ );
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-edit')).toBeTruthy());
+ fireEvent.press(screen.getByTestId('scheduled-message-action-edit'));
+
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ expect(channel.messageComposer.textComposer.text).toBe('My draft');
+ expect(channel.messageComposer.editedScheduledMessage).toBeUndefined();
+ });
+
+ it('offers no Edit in a list across channels that has nowhere to edit', async () => {
+ const scheduledMessage = generateScheduledMessage(channel);
+ await renderGlobalList([scheduledMessage]);
+
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() =>
+ expect(screen.getByTestId('scheduled-message-action-reschedule')).toBeTruthy(),
+ );
+ expect(screen.queryByTestId('scheduled-message-action-edit')).toBeNull();
+ });
+
+ it('refuses send now and reschedule while the quoted message is deleted', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, {
+ message: { quoted_message_id: 'gone', text: 'Quotes a deleted message' },
+ });
+ const sendNowSpy = jest.spyOn(channel.messageOperations, 'sendScheduledMessageNow');
+ renderList();
+ ingest(channel, [scheduledMessage]);
+ const openActions = async () => {
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() =>
+ expect(screen.getByTestId('scheduled-message-action-sendNow')).toBeTruthy(),
+ );
+ };
+
+ await waitFor(() =>
+ expect(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`)).toBeTruthy(),
+ );
+ await openActions();
+ fireEvent.press(screen.getByTestId('scheduled-message-action-sendNow'));
+ await openActions();
+ fireEvent.press(screen.getByTestId('scheduled-message-action-reschedule'));
+
+ await waitFor(() =>
+ expect(
+ screen.getAllByText('The quoted message was deleted. Edit it to remove the quote.').length,
+ ).toBeGreaterThan(1),
+ );
+ expect(sendNowSpy).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('schedule-time-sheet')).toBeNull();
+ });
+
+ it('lets the app customize the actions', async () => {
+ const scheduledMessage = generateScheduledMessage(channel);
+ const sendNowSpy = jest.spyOn(channel.messageOperations, 'sendScheduledMessageNow');
+ const share = jest.fn();
+ renderList({
+ getScheduledMessageActionItems: ({ context, defaultItems }) => [
+ ...defaultItems.filter(({ id }) => id !== 'reschedule'),
+ {
+ action: () => share(context.scheduledMessage.id),
+ Icon: () => null,
+ id: 'share',
+ label: 'Share',
+ type: 'standard',
+ },
+ ],
+ });
+ ingest(channel, [scheduledMessage]);
+
+ await waitFor(() =>
+ expect(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`)).toBeTruthy(),
+ );
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-share')).toBeTruthy());
+ expect(screen.queryByTestId('scheduled-message-action-reschedule')).toBeNull();
+ fireEvent.press(screen.getByTestId('scheduled-message-action-share'));
+
+ await waitFor(() => expect(share).toHaveBeenCalledWith(scheduledMessage.id));
+ expect(sendNowSpy).not.toHaveBeenCalled();
+ });
+
+ const openReschedule = async (scheduledMessage: ScheduledMessageResponse) => {
+ await waitFor(() =>
+ expect(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`)).toBeTruthy(),
+ );
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() =>
+ expect(screen.getByTestId('scheduled-message-action-reschedule')).toBeTruthy(),
+ );
+ fireEvent.press(screen.getByTestId('scheduled-message-action-reschedule'));
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+ };
+
+ it('reschedules a message and keeps the sheet until it has closed', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Move me' } });
+ const updateSpy = jest
+ .spyOn(channel.messageOperations, 'updateScheduledMessage')
+ .mockResolvedValue(scheduledMessage);
+ renderList();
+ ingest(channel, [scheduledMessage]);
+
+ await openReschedule(scheduledMessage);
+ expect(screen.getByText('Reschedule message')).toBeTruthy();
+ expect(screen.getByText(/^Scheduled for /)).toBeTruthy();
+
+ mockHeldSheetCloses = [];
+ try {
+ await act(() => {
+ fireEvent.press(screen.getByTestId('schedule-sheet-confirm'));
+ return Promise.resolve();
+ });
+ await waitFor(() => expect(mockHeldSheetCloses).toHaveLength(1));
+ expect(updateSpy).toHaveBeenCalledWith(scheduledMessage.id, {
+ request: { scheduled_at: nsToDate(scheduledMessage.scheduled_at) },
+ });
+ // Still showing the message while it slides away.
+ expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy();
+ expect(screen.getAllByText('Move me').length).toBeGreaterThan(1);
+
+ act(() => mockHeldSheetCloses?.forEach((finish) => finish()));
+ } finally {
+ mockHeldSheetCloses = undefined;
+ }
+ await waitFor(() => expect(screen.queryByTestId('schedule-time-sheet')).toBeNull());
+ });
+
+ it('reschedules a failed message from its own time, as a new message', async () => {
+ const failed = generateScheduledMessage(channel, {
+ message: { text: 'Retry me' },
+ status: 'failed',
+ });
+ const scheduleSpy = jest.spyOn(channel.messageOperations, 'scheduleMessage').mockResolvedValue({
+ scheduled_message: generateScheduledMessage(channel),
+ } as never);
+ const deleteSpy = jest
+ .spyOn(channel.messageOperations, 'deleteScheduledMessage')
+ .mockResolvedValue(failed);
+ renderList();
+ ingest(channel, [failed]);
+
+ await openReschedule(failed);
+ await act(() => {
+ fireEvent.press(screen.getByTestId('schedule-sheet-confirm'));
+ return Promise.resolve();
+ });
+
+ await waitFor(() => expect(deleteSpy).toHaveBeenCalledWith(failed.id));
+ expect(scheduleSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ options: { scheduled_at: nsToDate(failed.scheduled_at) } }),
+ );
+ });
+
+ it('says a reschedule never sends right away when the time is too soon', async () => {
+ // The mock channel sets no minimum lead time, so only a time that has passed is too soon.
+ const scheduledMessage = generateScheduledMessage(channel, {
+ scheduled_at: dateToNs(new Date(Date.now() - 60 * 1000)),
+ });
+ renderList();
+ ingest(channel, [scheduledMessage]);
+
+ await openReschedule(scheduledMessage);
+
+ expect(
+ screen.getByText("Pick a later time. Editing can't send a message right away."),
+ ).toBeTruthy();
+ });
+
+ it('reschedules from a list across channels, outside any Channel', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Anywhere' } });
+ await renderGlobalList([scheduledMessage]);
+
+ await openReschedule(scheduledMessage);
+
+ expect(screen.getByText('Reschedule message')).toBeTruthy();
+ expect(screen.getAllByText('Anywhere').length).toBeGreaterThan(1);
+ });
+
+ it('hands editing to the app in a list across channels', async () => {
+ const scheduledMessage = generateScheduledMessage(channel);
+ const onEditScheduledMessage = jest.fn();
+ await renderGlobalList([scheduledMessage], { onEditScheduledMessage });
+
+ fireEvent.press(screen.getByTestId(`scheduled-message-item-${scheduledMessage.id}`));
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-action-edit')).toBeTruthy());
+ fireEvent.press(screen.getByTestId('scheduled-message-action-edit'));
+
+ await waitFor(() => expect(onEditScheduledMessage).toHaveBeenCalledWith(scheduledMessage));
+ });
+});
+
+describe('ScheduleTimeSheet', () => {
+ let client: StreamChat;
+ let channel: ChannelType;
+
+ // The sheet opens on tomorrow at 09:00.
+ const tomorrowAt = (hours: number, minutes = 0) => {
+ const date = new Date();
+ date.setDate(date.getDate() + 1);
+ date.setHours(hours, minutes, 0, 0);
+ return date;
+ };
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ NativeHandlers.pickDateTime = undefined;
+ });
+
+ const renderSheet = (onConfirm = jest.fn().mockResolvedValue({})) =>
+ render(
+
+
+
+
+ ,
+ );
+
+ it('picks the date and then the time, with the bounds and the translated buttons', async () => {
+ const pickedDay = tomorrowAt(9);
+ pickedDay.setDate(pickedDay.getDate() + 2);
+ const pickedTime = new Date(pickedDay);
+ pickedTime.setHours(14, 30);
+ const pickDateTime = jest
+ .fn()
+ .mockResolvedValueOnce(pickedDay)
+ .mockResolvedValueOnce(pickedTime);
+ NativeHandlers.pickDateTime = pickDateTime;
+ const onConfirm = jest.fn().mockResolvedValue({});
+ renderSheet(onConfirm);
+
+ await act(() => fireEvent.press(screen.getByTestId('schedule-time-sheet-date')));
+
+ expect(pickDateTime).toHaveBeenCalledTimes(2);
+ expect(pickDateTime).toHaveBeenNthCalledWith(1, {
+ cancelLabel: 'Cancel',
+ confirmLabel: 'Confirm',
+ maximumDate: undefined,
+ minimumDate: expect.any(Date),
+ mode: 'date',
+ signal: expect.objectContaining({ aborted: false }),
+ value: tomorrowAt(9),
+ });
+ expect(pickDateTime).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ mode: 'time', value: pickedDay }),
+ );
+
+ await act(() => fireEvent.press(screen.getByTestId('schedule-sheet-confirm')));
+ expect(onConfirm).toHaveBeenCalledWith(pickedTime);
+ });
+
+ it('keeps the time when the date picker is cancelled, and opens no time picker', async () => {
+ const pickDateTime = jest.fn().mockResolvedValue(null);
+ NativeHandlers.pickDateTime = pickDateTime;
+ const onConfirm = jest.fn().mockResolvedValue({});
+ renderSheet(onConfirm);
+
+ await act(() => fireEvent.press(screen.getByTestId('schedule-time-sheet-date')));
+
+ expect(pickDateTime).toHaveBeenCalledTimes(1);
+ await act(() => fireEvent.press(screen.getByTestId('schedule-sheet-confirm')));
+ expect(onConfirm).toHaveBeenCalledWith(tomorrowAt(9));
+ });
+
+ it('picks only the time from the time row', async () => {
+ const pickDateTime = jest.fn().mockResolvedValue(tomorrowAt(18, 15));
+ NativeHandlers.pickDateTime = pickDateTime;
+ const onConfirm = jest.fn().mockResolvedValue({});
+ renderSheet(onConfirm);
+
+ await act(() => fireEvent.press(screen.getByTestId('schedule-time-sheet-time')));
+
+ expect(pickDateTime).toHaveBeenCalledTimes(1);
+ expect(pickDateTime).toHaveBeenCalledWith(expect.objectContaining({ mode: 'time' }));
+ await act(() => fireEvent.press(screen.getByTestId('schedule-sheet-confirm')));
+ expect(onConfirm).toHaveBeenCalledWith(tomorrowAt(18, 15));
+ });
+
+ it('closes an open picker when the sheet unmounts', () => {
+ const pickDateTime = jest.fn(
+ (_options: PickDateTimeOptions) => new Promise(() => undefined),
+ );
+ NativeHandlers.pickDateTime = pickDateTime;
+ const { unmount } = renderSheet();
+
+ fireEvent.press(screen.getByTestId('schedule-time-sheet-date'));
+ const { signal } = pickDateTime.mock.calls[0][0];
+ expect(signal?.aborted).toBe(false);
+
+ unmount();
+ expect(signal?.aborted).toBe(true);
+ });
+
+ it('opens one picker at a time', async () => {
+ let resolvePick: (date: Date | null) => void = () => undefined;
+ const pickDateTime = jest.fn(
+ () => new Promise((resolve) => (resolvePick = resolve)),
+ );
+ NativeHandlers.pickDateTime = pickDateTime;
+ renderSheet();
+
+ fireEvent.press(screen.getByTestId('schedule-time-sheet-time'));
+ fireEvent.press(screen.getByTestId('schedule-time-sheet-date'));
+ expect(pickDateTime).toHaveBeenCalledTimes(1);
+
+ await act(() => {
+ resolvePick(null);
+ return Promise.resolve();
+ });
+ fireEvent.press(screen.getByTestId('schedule-time-sheet-date'));
+ expect(pickDateTime).toHaveBeenCalledTimes(2);
+ });
+
+ it('shows the time but disables the rows without a native picker', () => {
+ renderSheet();
+
+ expect(screen.getByTestId('schedule-time-sheet-date').props.accessibilityState.disabled).toBe(
+ true,
+ );
+ expect(screen.getByTestId('schedule-time-sheet-time').props.accessibilityState.disabled).toBe(
+ true,
+ );
+ });
+});
+
+describe('ScheduleMessageSheet', () => {
+ let client: StreamChat;
+ let channel: ChannelType;
+
+ const OpenScheduleSheet = () => {
+ const { openScheduleSheet } = useMessageInputContext();
+ return ;
+ };
+
+ const renderSheets = () => {
+ // An empty message isn't composed, so the custom time sheet wouldn't open.
+ channel.messageComposer.textComposer.setText('Heads up');
+ return render(
+
+
+
+
+
+
+
+ ,
+ );
+ };
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ jest.spyOn(channel, 'ensureScheduledMessagesLoaded').mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ });
+
+ it('opens the quick times on a long press on send', async () => {
+ // The mock channel's server config has no scheduled message limits, which turns scheduling off.
+ jest.spyOn(channel, 'scheduledMessagesEnabled', 'get').mockReturnValue(true);
+ render(
+
+
+
+
+
+
+
+ ,
+ );
+
+ expect(screen.queryByText('Custom time')).toBeNull();
+ fireEvent(screen.getByTestId('send-button'), 'longPress');
+
+ await waitFor(() => expect(screen.getByText('Custom time')).toBeTruthy());
+ });
+
+ it('opens custom time over the quick times and goes back to them on close', async () => {
+ renderSheets();
+
+ fireEvent.press(screen.getByTestId('open-schedule-sheet'));
+ fireEvent.press(await screen.findByTestId('schedule-custom-time'));
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+ expect(screen.getByTestId('schedule-message-sheet')).toBeTruthy();
+ expect(screen.getByText('Heads up')).toBeTruthy();
+
+ const closeButtons = screen.getAllByTestId('schedule-sheet-close');
+ fireEvent.press(closeButtons[closeButtons.length - 1]);
+
+ await waitFor(() => expect(screen.queryByTestId('schedule-time-sheet')).toBeNull());
+ expect(screen.getByTestId('schedule-message-sheet')).toBeTruthy();
+ });
+
+ it('keeps confirm disabled once the per-user limit is reached', async () => {
+ const error = new StreamAPIError('you can schedule at most 100 messages', {
+ code: 118,
+ status: 400,
+ });
+ const scheduleSpy = jest
+ .spyOn(channel.messageComposer, 'scheduleMessage')
+ .mockResolvedValue({ error, status: 'failed' });
+ renderSheets();
+
+ fireEvent.press(screen.getByTestId('open-schedule-sheet'));
+ fireEvent.press(await screen.findByTestId('schedule-custom-time'));
+ await waitFor(() => expect(screen.getByTestId('schedule-sheet-confirm')).toBeTruthy());
+ await act(() => {
+ fireEvent.press(screen.getByTestId('schedule-sheet-confirm'));
+ return Promise.resolve();
+ });
+
+ await waitFor(() => expect(screen.getByText(/You've reached your limit of/)).toBeTruthy());
+ expect(screen.getByTestId('schedule-sheet-confirm').props.accessibilityState?.disabled).toBe(
+ true,
+ );
+ fireEvent.press(screen.getByTestId('schedule-sheet-confirm'));
+ expect(scheduleSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('ScheduledMessageEditComposer', () => {
+ let client: StreamChat;
+ let channel: ChannelType;
+ let editScheduledMessage: MessageComposerAPIContextValue['editScheduledMessage'];
+ let currentComposer: MessageComposer;
+
+ const ApiProbe = () => {
+ ({ editScheduledMessage } = useMessageComposerAPIContext());
+ currentComposer = useMessageComposer();
+ return null;
+ };
+
+ const EditProbe = () => {
+ const { editedScheduledMessage } = useEditedScheduledMessage();
+ return editedScheduledMessage ? {`editing ${editedScheduledMessage.id}`} : null;
+ };
+
+ const renderEdit = () =>
+ render(
+
+
+
+
+
+
+
+
+ ,
+ );
+
+ const startEdit = (scheduledMessage: ScheduledMessageResponse) =>
+ act(() => editScheduledMessage(scheduledMessage));
+
+ const press = (testID: string) =>
+ act(() => {
+ fireEvent.press(screen.getByTestId(testID));
+ return Promise.resolve();
+ });
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ jest.spyOn(channel, 'ensureScheduledMessagesLoaded').mockImplementation(() => undefined);
+ // The mock channel's server config has no scheduled message limits, which turns scheduling off.
+ jest.spyOn(channel, 'scheduledMessagesEnabled', 'get').mockReturnValue(true);
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ });
+
+ it('renders nothing until the edit has loaded', async () => {
+ let resolveQuoted: (value: unknown) => void = () => undefined;
+ jest
+ .spyOn(client, 'getMessage')
+ .mockReturnValue(new Promise((resolve) => (resolveQuoted = resolve)) as never);
+ const scheduledMessage = generateScheduledMessage(channel, {
+ message: { quoted_message_id: 'not-loaded', text: 'Replying' },
+ });
+ renderEdit();
+
+ act(() => {
+ void editScheduledMessage(scheduledMessage);
+ });
+ await waitFor(() => expect(client.getMessage).toHaveBeenCalled());
+ expect(screen.queryByTestId('send-button')).toBeNull();
+ expect(screen.queryByText(`editing ${scheduledMessage.id}`)).toBeNull();
+ expect(currentComposer).toBe(channel.messageComposer);
+
+ await act(async () => {
+ resolveQuoted({ message: { id: 'not-loaded', text: 'Quoted' } });
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(screen.getByText(`editing ${scheduledMessage.id}`)).toBeTruthy());
+ expect(screen.getByTestId('send-button')).toBeTruthy();
+ });
+
+ it('shows the last message opened when an earlier one finishes loading after it', async () => {
+ let resolveQuoted: (value: unknown) => void = () => undefined;
+ jest
+ .spyOn(client, 'getMessage')
+ .mockReturnValue(new Promise((resolve) => (resolveQuoted = resolve)) as never);
+ const slow = generateScheduledMessage(channel, {
+ message: { quoted_message_id: 'not-loaded', text: 'Slow' },
+ });
+ const fast = generateScheduledMessage(channel, { message: { text: 'Fast' } });
+ renderEdit();
+
+ act(() => {
+ void editScheduledMessage(slow);
+ });
+ await startEdit(fast);
+ await waitFor(() => expect(screen.getByText(`editing ${fast.id}`)).toBeTruthy());
+
+ await act(async () => {
+ resolveQuoted({ message: { id: 'not-loaded', text: 'Quoted' } });
+ await Promise.resolve();
+ });
+
+ expect(screen.getByText(`editing ${fast.id}`)).toBeTruthy();
+ expect(screen.queryByText(`editing ${slow.id}`)).toBeNull();
+ });
+
+ it('saves an edited scheduled message in place and hides the composer', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Old text' } });
+ const updateSpy = jest
+ .spyOn(channel.messageOperations, 'updateScheduledMessage')
+ .mockImplementation((id) => Promise.resolve({ ...scheduledMessage, id }));
+ const scheduleSpy = jest.spyOn(channel.messageOperations, 'scheduleMessage');
+ const dismissSpy = jest.spyOn(Keyboard, 'dismiss');
+ renderEdit();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ expect(dismissSpy).not.toHaveBeenCalled();
+ await press('send-button');
+
+ await waitFor(() => expect(screen.queryByTestId('send-button')).toBeNull());
+ expect(updateSpy).toHaveBeenCalledWith(scheduledMessage.id, expect.anything());
+ expect(scheduleSpy).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('schedule-time-sheet')).toBeNull();
+ expect(dismissSpy).toHaveBeenCalled();
+ });
+
+ describe('focusing the input once the window has focus', () => {
+ const originalOS = Platform.OS;
+ const setPlatform = (os: typeof Platform.OS) =>
+ Object.defineProperty(Platform, 'OS', { configurable: true, get: () => os });
+
+ let windowFocusListeners: (() => void)[];
+ let inputBoxRef: MessageInputContextValue['inputBoxRef'];
+
+ const InputRefProbe = () => {
+ ({ inputBoxRef } = useMessageInputContext());
+ return null;
+ };
+
+ const renderEditWithInputRef = () =>
+ render(
+
+
+
+
+
+
+
+
+ ,
+ );
+
+ beforeEach(() => {
+ windowFocusListeners = [];
+ jest.spyOn(AppState, 'addEventListener').mockImplementation((type, listener) => {
+ if (type === 'focus') windowFocusListeners.push(listener as () => void);
+ return { remove: jest.fn() } as never;
+ });
+ });
+
+ afterEach(() => setPlatform(originalOS));
+
+ it('focuses the input again on Android, where a closing sheet can still hold the window', async () => {
+ setPlatform('android');
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Edit me' } });
+ renderEditWithInputRef();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ const focusSpy = jest.spyOn(
+ inputBoxRef.current as NonNullable,
+ 'focus',
+ );
+ expect(windowFocusListeners).toHaveLength(1);
+
+ focusSpy.mockClear();
+
+ act(() => windowFocusListeners.forEach((listener) => listener()));
+
+ expect(focusSpy).toHaveBeenCalled();
+ });
+
+ it('does not wait for the window on iOS', async () => {
+ setPlatform('ios');
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Edit me' } });
+ renderEditWithInputRef();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+
+ expect(windowFocusListeners).toHaveLength(0);
+ });
+ });
+
+ it('hides the composer when the edit is cancelled', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Keep me' } });
+ const updateSpy = jest.spyOn(channel.messageOperations, 'updateScheduledMessage');
+ renderEdit();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ act(() => {
+ fireEvent.press(screen.getByTestId('remove-upload-preview'));
+ });
+
+ await waitFor(() => expect(screen.queryByTestId('send-button')).toBeNull());
+ expect(screen.queryByText(`editing ${scheduledMessage.id}`)).toBeNull();
+ expect(updateSpy).not.toHaveBeenCalled();
+ await waitFor(() => expect(currentComposer).toBe(channel.messageComposer));
+ });
+
+ it('asks for a new time before saving a failed message, then schedules it again', async () => {
+ const scheduledAt = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
+ scheduledAt.setSeconds(0, 0);
+ const failed = generateScheduledMessage(channel, {
+ message: { text: 'Retry me' },
+ scheduled_at: dateToNs(scheduledAt),
+ status: 'failed',
+ });
+ const updateSpy = jest.spyOn(channel.messageOperations, 'updateScheduledMessage');
+ const scheduleSpy = jest.spyOn(channel.messageOperations, 'scheduleMessage').mockResolvedValue({
+ scheduled_message: generateScheduledMessage(channel, { message: { text: 'Retry me' } }),
+ } as never);
+ const deleteSpy = jest
+ .spyOn(channel.messageOperations, 'deleteScheduledMessage')
+ .mockResolvedValue(failed);
+ renderEdit();
+
+ await startEdit(failed);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ await press('send-button');
+
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+ expect(screen.getByText('Reschedule message')).toBeTruthy();
+ expect(screen.getByText(/^Scheduled for /)).toBeTruthy();
+ expect(scheduleSpy).not.toHaveBeenCalled();
+
+ await press('schedule-sheet-confirm');
+
+ await waitFor(() => expect(screen.queryByTestId('send-button')).toBeNull());
+ expect(scheduleSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ options: expect.objectContaining({ scheduled_at: scheduledAt }) }),
+ );
+ expect(deleteSpy).toHaveBeenCalledWith(failed.id);
+ expect(updateSpy).not.toHaveBeenCalled();
+ });
+
+ it('keeps the reschedule sheet open when the edit ends under it', async () => {
+ const failed = generateScheduledMessage(channel, {
+ message: { text: 'Retry me' },
+ status: 'failed',
+ });
+ renderEdit();
+
+ await startEdit(failed);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ await press('send-button');
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+
+ // Scheduling it again ends the edit the same way, before the sheet starts closing.
+ act(() => currentComposer.cancelScheduledMessageEdit());
+
+ await waitFor(() => expect(screen.queryByTestId('send-button')).toBeNull());
+ expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy();
+ expect(screen.getByText('Retry me')).toBeTruthy();
+ });
+
+ it('reschedules a failed message from a channel screen composer too', async () => {
+ const failed = generateScheduledMessage(channel, {
+ message: { text: 'Retry me' },
+ status: 'failed',
+ });
+ const scheduleSpy = jest.spyOn(channel.messageOperations, 'scheduleMessage').mockResolvedValue({
+ scheduled_message: generateScheduledMessage(channel, { message: { text: 'Retry me' } }),
+ } as never);
+ jest.spyOn(channel.messageOperations, 'deleteScheduledMessage').mockResolvedValue(failed);
+ render(
+
+
+
+
+
+
+
+ ,
+ );
+
+ await startEdit(failed);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ await press('send-button');
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+ await press('schedule-sheet-confirm');
+
+ await waitFor(() => expect(scheduleSpy).toHaveBeenCalled());
+ await waitFor(() => expect(screen.queryByTestId('schedule-time-sheet')).toBeNull());
+ });
+
+ // An app that mounts a Channel for each edit, as a list across channels does.
+ const renderStartedEdit = (scheduledMessage: ScheduledMessageResponse, onClose: jest.Mock) => {
+ const tree = (show: boolean) => (
+
+
+
+
+ {show ? (
+
+ ) : null}
+
+
+
+ );
+ const { rerender } = render(tree(true));
+ return { unmountEdit: () => rerender(tree(false)) };
+ };
+
+ it('starts the edit it is given and reports when a save ends it', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Old text' } });
+ jest
+ .spyOn(channel.messageOperations, 'updateScheduledMessage')
+ .mockImplementation((id) => Promise.resolve({ ...scheduledMessage, id }));
+ const onClose = jest.fn();
+ renderStartedEdit(scheduledMessage, onClose);
+
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ expect(onClose).not.toHaveBeenCalled();
+ await press('send-button');
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ });
+
+ it('reports a cancelled edit, but not an unmount that leaves it open', async () => {
+ const first = generateScheduledMessage(channel, { message: { text: 'Cancel me' } });
+ const onCancelClose = jest.fn();
+ renderStartedEdit(first, onCancelClose);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ act(() => {
+ fireEvent.press(screen.getByTestId('remove-upload-preview'));
+ });
+ await waitFor(() => expect(onCancelClose).toHaveBeenCalledTimes(1));
+ cleanup();
+
+ const second = generateScheduledMessage(channel, { message: { text: 'Leave me' } });
+ const onUnmountClose = jest.fn();
+ const { unmountEdit } = renderStartedEdit(second, onUnmountClose);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ unmountEdit();
+
+ expect(onUnmountClose).not.toHaveBeenCalled();
+ });
+
+ it('waits for the reschedule sheet to close before reporting the end', async () => {
+ const failed = generateScheduledMessage(channel, {
+ message: { text: 'Retry me' },
+ status: 'failed',
+ });
+ jest.spyOn(channel.messageOperations, 'scheduleMessage').mockResolvedValue({
+ scheduled_message: generateScheduledMessage(channel, { message: { text: 'Retry me' } }),
+ } as never);
+ jest.spyOn(channel.messageOperations, 'deleteScheduledMessage').mockResolvedValue(failed);
+ const onClose = jest.fn();
+ renderStartedEdit(failed, onClose);
+
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ await press('send-button');
+ await waitFor(() => expect(screen.getByTestId('schedule-time-sheet')).toBeTruthy());
+
+ mockHeldSheetCloses = [];
+ try {
+ await press('schedule-sheet-confirm');
+ await waitFor(() => expect(mockHeldSheetCloses).toHaveLength(1));
+ await waitFor(() => expect(screen.queryByTestId('send-button')).toBeNull());
+ expect(onClose).not.toHaveBeenCalled();
+
+ act(() => mockHeldSheetCloses?.forEach((finish) => finish()));
+ } finally {
+ mockHeldSheetCloses = undefined;
+ }
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables save and says why once a command is typed', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, { message: { text: 'Launch day' } });
+ const blockedToasts = () =>
+ client.notifications.notifications.filter(
+ ({ type }) => type === CORE_NOTIFICATION_TYPE.scheduledMessageBlocked,
+ );
+ renderEdit();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByText('Edit scheduled message')).toBeTruthy());
+ expect(screen.getByTestId('send-button').props.accessibilityState?.disabled).toBe(false);
+ expect(blockedToasts()).toHaveLength(0);
+
+ act(() => currentComposer.textComposer.setText('/giphy launch day'));
+ await waitFor(() =>
+ expect(screen.getByTestId('send-button').props.accessibilityState?.disabled).toBe(true),
+ );
+ act(() => currentComposer.textComposer.setText('/giphy launch day!'));
+
+ expect(blockedToasts()).toHaveLength(1);
+ expect(blockedToasts()[0].metadata).toEqual({ reason: ScheduledMessageBlockReason.Command });
+
+ act(() => currentComposer.textComposer.setText('Launch day'));
+ await waitFor(() =>
+ expect(screen.getByTestId('send-button').props.accessibilityState?.disabled).toBe(false),
+ );
+ });
+
+ it('blocks saving while the quoted message is deleted, until the quote is removed', async () => {
+ const scheduledMessage = generateScheduledMessage(channel, {
+ message: {
+ quoted_message: { id: 'quoted', text: '', type: 'deleted' } as never,
+ quoted_message_id: 'quoted',
+ text: 'Replying',
+ },
+ });
+ renderEdit();
+
+ await startEdit(scheduledMessage);
+ await waitFor(() => expect(screen.getByTestId('scheduled-message-quote-deleted')).toBeTruthy());
+ expect(screen.getByTestId('send-button').props.accessibilityState?.disabled).toBe(true);
+
+ await press('scheduled-message-remove-quote');
+
+ await waitFor(() => expect(screen.queryByTestId('scheduled-message-quote-deleted')).toBeNull());
+ expect(screen.getByTestId('send-button').props.accessibilityState?.disabled).toBe(false);
+ });
+});
diff --git a/package/src/components/ScheduledMessages/__tests__/scheduleTime.test.ts b/package/src/components/ScheduledMessages/__tests__/scheduleTime.test.ts
new file mode 100644
index 0000000000..4fc5d66c7a
--- /dev/null
+++ b/package/src/components/ScheduledMessages/__tests__/scheduleTime.test.ts
@@ -0,0 +1,145 @@
+import type { Channel } from 'stream-chat';
+import { StreamAPIError } from 'stream-chat';
+
+import { getScheduleErrorText } from '../utils/scheduleErrors';
+import {
+ formatTimeZoneOffset,
+ getAvailableSchedulePresets,
+ getDefaultScheduledAt,
+ getSchedulePresets,
+ getScheduleTimeBounds,
+ getScheduleTimeError,
+} from '../utils/scheduleTime';
+
+const channelWithLimits = (limits: { maxLeadTimeSeconds: number; minLeadTimeSeconds: number }) =>
+ ({
+ serverConfig: {
+ scheduled_messages_max_lead_time_seconds: limits.maxLeadTimeSeconds,
+ scheduled_messages_max_per_channel: 10,
+ scheduled_messages_max_per_user: 100,
+ scheduled_messages_min_lead_time_seconds: limits.minLeadTimeSeconds,
+ },
+ }) as unknown as Channel;
+
+const DAY_SECONDS = 24 * 60 * 60;
+
+describe('getSchedulePresets', () => {
+ it('offers tomorrow morning, tomorrow afternoon and next Monday morning', () => {
+ // A Wednesday.
+ const now = new Date(2026, 9, 21, 15, 30);
+ const presets = getSchedulePresets(now);
+
+ expect(presets.map((preset) => [preset.getDate(), preset.getHours()])).toEqual([
+ [22, 9],
+ [22, 13],
+ [26, 9],
+ ]);
+ });
+
+ it('leaves out Monday when tomorrow is Monday', () => {
+ // A Sunday.
+ const now = new Date(2026, 9, 25, 20, 0);
+
+ expect(getSchedulePresets(now)).toHaveLength(2);
+ });
+
+ it('drops the presets beyond the maximum lead time', () => {
+ const now = new Date(2026, 9, 21, 15, 30);
+ const bounds = getScheduleTimeBounds(
+ channelWithLimits({ maxLeadTimeSeconds: DAY_SECONDS, minLeadTimeSeconds: 60 }),
+ now,
+ );
+
+ expect(getAvailableSchedulePresets(now, bounds).map((preset) => preset.getHours())).toEqual([
+ 9, 13,
+ ]);
+ });
+});
+
+describe('getScheduleTimeError', () => {
+ const now = new Date(2026, 9, 21, 9, 41, 0);
+ const bounds = getScheduleTimeBounds(
+ channelWithLimits({ maxLeadTimeSeconds: 7 * DAY_SECONDS, minLeadTimeSeconds: 60 }),
+ now,
+ );
+
+ it('rejects a time under the minimum lead time', () => {
+ expect(getScheduleTimeError(new Date(2026, 9, 21, 9, 41, 30), bounds)).toBe('too_soon');
+ });
+
+ it('accepts a time at the minimum lead time', () => {
+ expect(getScheduleTimeError(new Date(2026, 9, 21, 9, 42, 0), bounds)).toBeUndefined();
+ });
+
+ it('rejects a time beyond the maximum lead time', () => {
+ expect(getScheduleTimeError(new Date(2026, 9, 29, 9, 0), bounds)).toBe('too_far');
+ });
+
+ it('has no upper bound when the app sets no limits', () => {
+ const unbounded = getScheduleTimeBounds({ serverConfig: {} } as unknown as Channel, now);
+ expect(getScheduleTimeError(new Date(2030, 0, 1), unbounded)).toBeUndefined();
+ });
+});
+
+describe('getDefaultScheduledAt', () => {
+ it('opens on tomorrow at 09:00', () => {
+ const now = new Date(2026, 9, 21, 15, 30);
+ const bounds = getScheduleTimeBounds(
+ channelWithLimits({ maxLeadTimeSeconds: 7 * DAY_SECONDS, minLeadTimeSeconds: 60 }),
+ now,
+ );
+ const defaultAt = getDefaultScheduledAt(now, bounds);
+
+ expect([defaultAt.getDate(), defaultAt.getHours(), defaultAt.getMinutes()]).toEqual([22, 9, 0]);
+ });
+
+ it('falls back to the earliest allowed minute when tomorrow is out of bounds', () => {
+ const now = new Date(2026, 9, 21, 15, 30);
+ const bounds = getScheduleTimeBounds(
+ channelWithLimits({ maxLeadTimeSeconds: 60 * 60, minLeadTimeSeconds: 60 }),
+ now,
+ );
+ const defaultAt = getDefaultScheduledAt(now, bounds);
+
+ expect(getScheduleTimeError(defaultAt, bounds)).toBeUndefined();
+ expect(defaultAt.getHours()).toBe(15);
+ });
+});
+
+describe('formatTimeZoneOffset', () => {
+ it('formats whole and half hour offsets', () => {
+ const at = (offsetMinutes: number) =>
+ ({ getTimezoneOffset: () => offsetMinutes }) as unknown as Date;
+
+ expect(formatTimeZoneOffset(at(-120))).toBe('GMT+2');
+ expect(formatTimeZoneOffset(at(-330))).toBe('GMT+5:30');
+ expect(formatTimeZoneOffset(at(300))).toBe('GMT-5');
+ expect(formatTimeZoneOffset(at(0))).toBe('GMT');
+ });
+});
+
+describe('getScheduleErrorText', () => {
+ const t = ((_key: string, defaultValue: string, options?: Record) =>
+ Object.entries(options ?? {}).reduce(
+ (text, [name, value]) => text.replace(`{{ ${name} }}`, String(value)),
+ defaultValue,
+ )) as never;
+ const userLimitError = new StreamAPIError('you can schedule at most 100 messages', {
+ code: 118,
+ status: 400,
+ });
+
+ it("names the per-user limit from the channel's config", () => {
+ const channel = channelWithLimits({ maxLeadTimeSeconds: DAY_SECONDS, minLeadTimeSeconds: 60 });
+
+ expect(getScheduleErrorText(t, userLimitError, 'schedule', channel)).toBe(
+ "You've reached your limit of 100 scheduled messages.",
+ );
+ });
+
+ it('leaves the number out when the limit is unknown', () => {
+ expect(getScheduleErrorText(t, userLimitError)).toBe(
+ "You've reached your limit of scheduled messages.",
+ );
+ });
+});
diff --git a/package/src/components/ScheduledMessages/__tests__/scheduledMessageActionItems.test.ts b/package/src/components/ScheduledMessages/__tests__/scheduledMessageActionItems.test.ts
new file mode 100644
index 0000000000..cd02701d3e
--- /dev/null
+++ b/package/src/components/ScheduledMessages/__tests__/scheduledMessageActionItems.test.ts
@@ -0,0 +1,102 @@
+import type { LocalScheduledMessage } from 'stream-chat';
+
+import type { IconsMap } from '../../../contexts/componentsContext/defaultComponents';
+import { buildDefaultScheduledMessageActionItems } from '../hooks/useScheduledMessageActionItems';
+
+const Icon = () => null;
+const icons = new Proxy({}, { get: () => Icon }) as unknown as IconsMap;
+const t = ((_key: string, defaultValue: string) => defaultValue) as never;
+
+const actions = {
+ copyMessageText: jest.fn(),
+ delete: jest.fn(),
+ edit: jest.fn(),
+ reschedule: jest.fn(),
+ sendNow: jest.fn(),
+};
+
+const idsFor = (
+ scheduledMessage: Pick,
+ overrides: Partial = {},
+) =>
+ buildDefaultScheduledMessageActionItems({
+ actions: { ...actions, ...overrides },
+ icons,
+ scheduledMessage: scheduledMessage as LocalScheduledMessage,
+ t,
+ }).map(({ id }) => id);
+
+describe('buildDefaultScheduledMessageActionItems', () => {
+ it('offers every action for a scheduled message', () => {
+ expect(idsFor({ status: 'scheduled' })).toEqual(['edit', 'reschedule', 'sendNow', 'delete']);
+ });
+
+ it('offers no send now for a failed message', () => {
+ expect(idsFor({ failure_reason: 'internal_error', status: 'failed' })).toEqual([
+ 'edit',
+ 'reschedule',
+ 'delete',
+ ]);
+ });
+
+ it('offers only copy and delete when the channel was deleted', () => {
+ expect(idsFor({ failure_reason: 'channel_deleted', status: 'failed' })).toEqual([
+ 'copyMessageText',
+ 'delete',
+ ]);
+ });
+
+ it('offers nothing while the message is sending', () => {
+ expect(idsFor({ status: 'sending' })).toEqual([]);
+ });
+
+ it('offers nothing while the request scheduling it is in flight', () => {
+ expect(
+ idsFor({ localMetadata: { pending: true, requestState: 'inFlight' }, status: 'scheduled' }),
+ ).toEqual([]);
+ });
+
+ it('offers nothing while a request changing it is in flight', () => {
+ expect(idsFor({ localMetadata: { requestState: 'inFlight' }, status: 'scheduled' })).toEqual(
+ [],
+ );
+ expect(idsFor({ localMetadata: { requestState: 'inFlight' }, status: 'sending' })).toEqual([]);
+ });
+
+ describe('while its request waits in the offline queue', () => {
+ it('offers every action for a message still being scheduled', () => {
+ expect(
+ idsFor({ localMetadata: { pending: true, requestState: 'queued' }, status: 'scheduled' }),
+ ).toEqual(['edit', 'reschedule', 'sendNow', 'delete']);
+ });
+
+ it('offers only delete for a message whose send now waits', () => {
+ expect(idsFor({ localMetadata: { requestState: 'queued' }, status: 'sending' })).toEqual([
+ 'delete',
+ ]);
+ expect(
+ idsFor({ localMetadata: { pending: true, requestState: 'queued' }, status: 'sending' }),
+ ).toEqual(['delete']);
+ });
+ });
+
+ it('leaves out edit when there is nowhere to edit', () => {
+ expect(idsFor({ status: 'scheduled' }, { edit: undefined })).toEqual([
+ 'reschedule',
+ 'sendNow',
+ 'delete',
+ ]);
+ });
+
+ it('binds each item to its action', () => {
+ const items = buildDefaultScheduledMessageActionItems({
+ actions,
+ icons,
+ scheduledMessage: { status: 'scheduled' } as ScheduledMessageResponse,
+ t,
+ });
+ items.find(({ id }) => id === 'sendNow')?.action();
+ expect(actions.sendNow).toHaveBeenCalledTimes(1);
+ expect(items.find(({ id }) => id === 'delete')?.type).toBe('destructive');
+ });
+});
diff --git a/package/src/components/ScheduledMessages/__tests__/scheduledTimeLabels.test.ts b/package/src/components/ScheduledMessages/__tests__/scheduledTimeLabels.test.ts
new file mode 100644
index 0000000000..96a91dc745
--- /dev/null
+++ b/package/src/components/ScheduledMessages/__tests__/scheduledTimeLabels.test.ts
@@ -0,0 +1,43 @@
+import { Streami18n } from '../../../utils/i18n/Streami18n';
+import {
+ formatScheduledDate,
+ formatScheduledDateTime,
+ formatScheduledTime,
+ formatSchedulePreset,
+} from '../utils/scheduledTimeLabels';
+
+// Friday, October 23 2026, in the UTC time zone the tests run in.
+const at = (hours: number, minutes = 0, day = 23) => new Date(2026, 9, day, hours, minutes);
+const now = at(18);
+
+describe('scheduled time labels', () => {
+ it('uses the 24 hour format of the design by default', async () => {
+ const translators = await new Streami18n({ logger: () => {} }).init();
+
+ expect(formatScheduledTime(at(13, 5), translators)).toBe('13:05');
+ expect(formatScheduledDate(at(13, 5), translators)).toBe('Fri, Oct 23');
+ expect(formatScheduledDateTime(at(9), translators)).toBe('Fri, Oct 23 at 09:00');
+ });
+
+ it('names tomorrow and later days in the quick options', async () => {
+ const translators = await new Streami18n({ logger: () => {} }).init();
+
+ expect(formatSchedulePreset(at(9, 0, 24), now, translators)).toBe('Tomorrow at 09:00');
+ expect(formatSchedulePreset(at(9, 0, 26), now, translators)).toBe('Monday at 09:00');
+ });
+
+ it('follows the translations an app registers for the format keys', async () => {
+ const translators = await new Streami18n({
+ logger: () => {},
+ translationsForLanguage: {
+ 'timestamp.ScheduledMessageDate': '{{ timestamp | timestampFormatter(format: D MMMM) }}',
+ 'timestamp.ScheduledMessageTime': '{{ timestamp | timestampFormatter(format: LT) }}',
+ 'timestamp.ScheduledMessageWeekday': '{{ timestamp | timestampFormatter(format: ddd) }}',
+ },
+ }).init();
+
+ expect(formatScheduledDateTime(at(13, 5), translators)).toBe('23 October at 1:05 PM');
+ expect(formatSchedulePreset(at(9, 0, 24), now, translators)).toBe('Tomorrow at 9:00 AM');
+ expect(formatSchedulePreset(at(9, 0, 26), now, translators)).toBe('Mon at 9:00 AM');
+ });
+});
diff --git a/package/src/components/ScheduledMessages/__tests__/useChannelScheduledMessages.test.tsx b/package/src/components/ScheduledMessages/__tests__/useChannelScheduledMessages.test.tsx
new file mode 100644
index 0000000000..1f9629d63b
--- /dev/null
+++ b/package/src/components/ScheduledMessages/__tests__/useChannelScheduledMessages.test.tsx
@@ -0,0 +1,50 @@
+import React, { PropsWithChildren } from 'react';
+
+import { act, cleanup, renderHook } from '@testing-library/react-native';
+import type { Channel, StreamChat } from 'stream-chat';
+
+import { ChatProvider } from '../../../contexts/chatContext/ChatContext';
+import { initiateClientWithChannels } from '../../../mock-builders/api/initiateClientWithChannels';
+import { useChannelScheduledMessages } from '../hooks/useChannelScheduledMessages';
+
+describe('useChannelScheduledMessages', () => {
+ let client: StreamChat;
+ let channel: Channel;
+
+ const wrapper = ({ children }: PropsWithChildren) => (
+ {children}
+ );
+
+ beforeEach(async () => {
+ const { client: chatClient, channels } = await initiateClientWithChannels();
+ client = chatClient;
+ channel = channels[0];
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.restoreAllMocks();
+ });
+
+ it('loads the list only once the channel is initialized, and again when capabilities change', () => {
+ const ensureSpy = jest
+ .spyOn(channel, 'ensureScheduledMessagesLoaded')
+ .mockImplementation(() => undefined);
+ act(() => {
+ channel.state.partialNext({ initialized: false });
+ });
+
+ renderHook(() => useChannelScheduledMessages(channel.scheduledMessages), { wrapper });
+ expect(ensureSpy).not.toHaveBeenCalled();
+
+ act(() => {
+ channel.state.partialNext({ initialized: true });
+ });
+ expect(ensureSpy).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ channel.state.partialNext({ ownCapabilities: ['schedule-message'] });
+ });
+ expect(ensureSpy).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts b/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts
new file mode 100644
index 0000000000..3f6fbfd37b
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts
@@ -0,0 +1,24 @@
+import type { Channel, PaginatorState, ScheduledMessageResponse } from 'stream-chat';
+import { getScheduledMessageLimits } from 'stream-chat';
+
+import { useStateStore } from '../../../hooks/useStateStore';
+import { isPendingScheduledMessage } from '../utils/actions';
+
+const pendingCountSelector = ({ items }: PaginatorState) => ({
+ pendingCount: items?.filter(isPendingScheduledMessage).length ?? 0,
+});
+
+/** The per-channel limit, which counts the channel's pending messages, thread replies included. */
+export const useChannelScheduledMessageLimit = (channel: Channel) => {
+ const { pendingCount } = useStateStore(
+ channel.scheduledMessagesPaginator.state,
+ pendingCountSelector,
+ );
+ const maxPerChannel = getScheduledMessageLimits(channel)?.maxPerChannel;
+
+ return {
+ isLimitReached: maxPerChannel !== undefined && pendingCount >= maxPerChannel,
+ maxPerChannel,
+ pendingCount,
+ };
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts b/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts
new file mode 100644
index 0000000000..6a84dbbfa1
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts
@@ -0,0 +1,42 @@
+import { useEffect } from 'react';
+
+import type { ChannelConfig, ChannelStateData, ScheduledMessagesView } from 'stream-chat';
+
+import { useScheduledMessages } from './useScheduledMessages';
+
+import { useChatContext } from '../../../contexts/chatContext/ChatContext';
+import { useStateStore } from '../../../hooks/useStateStore';
+
+const loadConditionsSelector = ({
+ initialized,
+ ownCapabilities,
+}: Pick) => ({
+ initialized,
+ ownCapabilities,
+});
+
+const enabledByConfigSelector = ({ scheduledMessages }: ChannelConfig) => ({
+ isEnabledByConfig: scheduledMessages.enabled,
+});
+
+/**
+ * The messages of a channel's scheduled-message view, such as `thread.scheduledMessages` or the
+ * channel-wide view. The channel query usually fills the list. This loads it only for a channel
+ * queried without it, once the channel is initialized, and again when the user's capabilities or
+ * the scheduled messages config change.
+ */
+export const useChannelScheduledMessages = (view: ScheduledMessagesView) => {
+ const { client } = useChatContext();
+ const { cid } = view.paginator;
+ const channel = cid ? client.channelManager.get(cid) : undefined;
+ const { initialized, ownCapabilities } =
+ useStateStore(channel?.state, loadConditionsSelector) ?? {};
+ const { isEnabledByConfig } = useStateStore(channel?.configState, enabledByConfigSelector) ?? {};
+
+ useEffect(() => {
+ if (!channel || !initialized) return;
+ channel.ensureScheduledMessagesLoaded();
+ }, [channel, initialized, isEnabledByConfig, ownCapabilities]);
+
+ return useScheduledMessages(view);
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts b/package/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts
new file mode 100644
index 0000000000..4fdd4c7e7e
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts
@@ -0,0 +1,14 @@
+import { useMemo } from 'react';
+
+import type { Channel } from 'stream-chat';
+import { ScheduledMessagesView } from 'stream-chat';
+
+/**
+ * Every scheduled message of the channel, thread replies included. `channel.scheduledMessages`
+ * leaves the replies out, so this is a view of the channel's whole list.
+ */
+export const useChannelWideScheduledMessagesView = (channel: Channel) =>
+ useMemo(
+ () => new ScheduledMessagesView({ paginator: channel.scheduledMessagesPaginator }),
+ [channel],
+ );
diff --git a/package/src/components/ScheduledMessages/hooks/useEditedScheduledMessage.ts b/package/src/components/ScheduledMessages/hooks/useEditedScheduledMessage.ts
new file mode 100644
index 0000000000..e1b86bd9e8
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useEditedScheduledMessage.ts
@@ -0,0 +1,23 @@
+import type { MessageComposerState } from 'stream-chat';
+import { SCHEDULED_MESSAGE_STATUS } from 'stream-chat';
+
+import { useMessageComposer } from '../../../contexts/messageInputContext/hooks/useMessageComposer';
+import { useStateStore } from '../../../hooks/useStateStore';
+
+const selector = (state: MessageComposerState) => ({
+ editedScheduledMessage: state.editedScheduledMessage,
+});
+
+/**
+ * The scheduled message open in the composer. `isFailed` means it failed to send, so saving
+ * schedules it again instead of updating it.
+ */
+export const useEditedScheduledMessage = () => {
+ const messageComposer = useMessageComposer();
+ const { editedScheduledMessage } = useStateStore(messageComposer.state, selector);
+
+ return {
+ editedScheduledMessage: editedScheduledMessage ?? undefined,
+ isFailed: editedScheduledMessage?.status === SCHEDULED_MESSAGE_STATUS.Failed,
+ };
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useScheduleComposerMessage.ts b/package/src/components/ScheduledMessages/hooks/useScheduleComposerMessage.ts
new file mode 100644
index 0000000000..7fc641faa0
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useScheduleComposerMessage.ts
@@ -0,0 +1,98 @@
+import {
+ CORE_NOTIFICATION_TYPE,
+ getScheduledMessageErrorReason,
+ ScheduledMessageErrorReason,
+} from 'stream-chat';
+
+import { useChannelContext } from '../../../contexts/channelContext/ChannelContext';
+import { useChatContext } from '../../../contexts/chatContext/ChatContext';
+import { useMessageComposer } from '../../../contexts/messageInputContext/hooks/useMessageComposer';
+import { useThreadContext } from '../../../contexts/threadContext/ThreadContext';
+import { useTranslationContext } from '../../../contexts/translationContext/TranslationContext';
+import { useStableCallback } from '../../../hooks/useStableCallback';
+import { DEFAULT_HIGHLIGHT_DURATION } from '../../MessageList/hooks/useMessageListFocus';
+import { useNotificationApi } from '../../Notifications/hooks/useNotificationApi';
+import { getScheduleErrorText } from '../utils/scheduleErrors';
+
+export type ScheduleComposerMessageResult = {
+ /** The error to show, when the message wasn't scheduled. */
+ errorText?: string;
+ /** The server refused because the user has reached their limit. */
+ isUserLimit?: boolean;
+};
+
+/**
+ * Schedules the composer's message. With `fromTimeSheet`, the time sheet shows a failure itself,
+ * so the composer's toast for it is removed.
+ */
+export const useScheduleComposerMessage = () => {
+ const { channel } = useChannelContext();
+ const { thread } = useThreadContext();
+ const { client } = useChatContext();
+ const messageComposer = useMessageComposer();
+ const { t } = useTranslationContext();
+ const { addNotification } = useNotificationApi();
+
+ const showSentNow = useStableCallback((messageId: string) => {
+ const paginator = thread ? thread.messagePaginator : channel.messagePaginator;
+ addNotification({
+ message: t('scheduledMessages.sentNow.text', 'Scheduled message sent'),
+ options: {
+ actions: [
+ {
+ handler: () => {
+ paginator
+ .jumpToMessage(messageId, {
+ focusReason: 'jump-to-message',
+ focusSignalTtlMs: DEFAULT_HIGHLIGHT_DURATION,
+ })
+ .catch(() => undefined);
+ },
+ label: t('scheduledMessages.view.label', 'View'),
+ },
+ ],
+ severity: 'success',
+ type: 'api:scheduled-message:send-now:success',
+ },
+ origin: { context: { channel }, emitter: 'ScheduleMessageSheet' },
+ });
+ });
+
+ return useStableCallback(
+ async (
+ scheduledAt: Date,
+ { fromTimeSheet = false }: { fromTimeSheet?: boolean } = {},
+ ): Promise => {
+ const messageId = messageComposer.id;
+ const result = await messageComposer.scheduleMessage(scheduledAt);
+
+ switch (result.status) {
+ case 'failed': {
+ if (fromTimeSheet) {
+ client.notifications.notifications
+ .filter(({ type }) => type === CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed)
+ .forEach(({ id }) => client.notifications.remove(id));
+ }
+ return {
+ errorText: getScheduleErrorText(t, result.error, 'schedule', channel),
+ isUserLimit:
+ getScheduledMessageErrorReason(result.error) ===
+ ScheduledMessageErrorReason.UserLimit,
+ };
+ }
+ case 'blocked':
+ return {
+ errorText: t(
+ 'scheduledMessages.commandBlocked.error',
+ "Commands can't be scheduled. Remove the / command to continue.",
+ ),
+ };
+ case 'sent':
+ showSentNow(messageId);
+ return {};
+ default:
+ return {};
+ }
+ },
+ );
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionHandlers.ts b/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionHandlers.ts
new file mode 100644
index 0000000000..dd4ad0e13e
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionHandlers.ts
@@ -0,0 +1,161 @@
+import { useMemo } from 'react';
+
+import type { ScheduledMessageResponse, StreamChat } from 'stream-chat';
+import {
+ getScheduledMessageErrorReason,
+ isScheduledMessageNotFoundError,
+ ScheduledMessageErrorReason,
+} from 'stream-chat';
+
+import { useChatContext } from '../../../contexts/chatContext/ChatContext';
+import { useTranslationContext } from '../../../contexts/translationContext/TranslationContext';
+import { getNotificationErrorOptions } from '../../../hooks/actions/useChannelActions';
+import { NativeHandlers } from '../../../native';
+import { useNotificationApi } from '../../Notifications/hooks/useNotificationApi';
+import { hasDeletedQuote } from '../utils/quote';
+import { getScheduleErrorText } from '../utils/scheduleErrors';
+
+/** The channel a scheduled message belongs to, whether or not the app has loaded it. */
+export const getScheduledMessageChannel = (
+ client: StreamChat,
+ scheduledMessage: ScheduledMessageResponse,
+) => {
+ const [type, ...idParts] = scheduledMessage.cid.split(':');
+ return client.channel(type, idParts.join(':'));
+};
+
+/** The requests behind the actions of a scheduled messages list, with their notifications. */
+export const useScheduledMessageActionHandlers = () => {
+ const { client } = useChatContext();
+ const { t } = useTranslationContext();
+ const { addNotification } = useNotificationApi();
+
+ return useMemo(() => {
+ const notifyAlreadySent = () =>
+ addNotification({
+ message: t('scheduledMessages.alreadySent.text', "Already sent. It's in the channel now."),
+ options: { severity: 'info', type: 'api:scheduled-message:already-sent' },
+ origin: { emitter: 'ScheduledMessageList' },
+ });
+
+ const notifyStillSending = () =>
+ addNotification({
+ message: t('scheduledMessages.stillSending.text', 'Still sending. Try again in a moment.'),
+ options: { severity: 'info', type: 'api:scheduled-message:sending' },
+ origin: { emitter: 'ScheduledMessageList' },
+ });
+
+ // Sending or rescheduling a message whose quote was deleted is refused here, with no request.
+ const refuseDeletedQuote = (scheduledMessage: ScheduledMessageResponse) => {
+ if (!hasDeletedQuote(scheduledMessage)) return false;
+ addNotification({
+ message: t(
+ 'scheduledMessages.quoteDeleted.text',
+ 'The quoted message was deleted. Edit it to remove the quote.',
+ ),
+ options: { severity: 'info', type: 'api:scheduled-message:quote-deleted' },
+ origin: { emitter: 'ScheduledMessageList' },
+ });
+ return true;
+ };
+
+ const notifyError = (message: string, error: unknown, type: string) =>
+ addNotification({
+ message,
+ options: { ...getNotificationErrorOptions(error), severity: 'error', type },
+ origin: { emitter: 'ScheduledMessageList' },
+ });
+
+ const deleteScheduledMessage = async (scheduledMessage: ScheduledMessageResponse) => {
+ const channel = getScheduledMessageChannel(client, scheduledMessage);
+ try {
+ await channel.messageOperations.deleteScheduledMessage(scheduledMessage.id);
+ } catch (error) {
+ if (isScheduledMessageNotFoundError(error)) {
+ notifyAlreadySent();
+ return;
+ }
+ if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.Sending) {
+ notifyStillSending();
+ return;
+ }
+ notifyError(
+ t(
+ 'scheduledMessages.deleteFailed.error',
+ "Couldn't delete the scheduled message. Try again",
+ ),
+ error,
+ 'api:scheduled-message:delete:failed',
+ );
+ }
+ };
+
+ const sendScheduledMessageNow = async (scheduledMessage: ScheduledMessageResponse) => {
+ if (refuseDeletedQuote(scheduledMessage)) return;
+ const channel = getScheduledMessageChannel(client, scheduledMessage);
+ try {
+ await channel.messageOperations.sendScheduledMessageNow(scheduledMessage.id);
+ addNotification({
+ message: t('scheduledMessages.sentNow.text', 'Scheduled message sent'),
+ options: { severity: 'success', type: 'api:scheduled-message:send-now:success' },
+ origin: { emitter: 'ScheduledMessageList' },
+ });
+ } catch (error) {
+ if (isScheduledMessageNotFoundError(error)) {
+ notifyAlreadySent();
+ return;
+ }
+ if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.Sending) {
+ notifyStillSending();
+ return;
+ }
+ notifyError(
+ t('scheduledMessages.sendNowFailed.error', "Couldn't send the message. Try again"),
+ error,
+ 'api:scheduled-message:send-now:failed',
+ );
+ }
+ };
+
+ /** Moves a scheduled message to `scheduledAt`. Resolves with an error to show, or nothing. */
+ const rescheduleScheduledMessage = async (
+ scheduledMessage: ScheduledMessageResponse,
+ scheduledAt: Date,
+ ) => {
+ const channel = getScheduledMessageChannel(client, scheduledMessage);
+ try {
+ // A failed message comes back as a new one, and the failed one is deleted.
+ await channel.messageOperations.rescheduleScheduledMessage(scheduledMessage, scheduledAt);
+ return undefined;
+ } catch (error) {
+ if (isScheduledMessageNotFoundError(error)) {
+ notifyAlreadySent();
+ return undefined;
+ }
+ return getScheduleErrorText(t, error, 'reschedule', channel);
+ }
+ };
+
+ const copyScheduledMessageText = (scheduledMessage: ScheduledMessageResponse) => {
+ const { text } = scheduledMessage.message;
+ if (!text) return;
+ NativeHandlers.setClipboardString(text, {
+ onFailure: (error) =>
+ notifyError(
+ t('message.copyMessage.error', 'Failed to copy message'),
+ error,
+ 'clipboard:message:copy:failed',
+ ),
+ });
+ };
+
+ return {
+ copyScheduledMessageText,
+ deleteScheduledMessage,
+ notifyStillSending,
+ refuseDeletedQuote,
+ rescheduleScheduledMessage,
+ sendScheduledMessageNow,
+ };
+ }, [addNotification, client, t]);
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionItems.tsx b/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionItems.tsx
new file mode 100644
index 0000000000..c95e71fba0
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useScheduledMessageActionItems.tsx
@@ -0,0 +1,168 @@
+import { useMemo } from 'react';
+
+import type { LocalScheduledMessage } from 'stream-chat';
+import { SCHEDULED_MESSAGE_FAILURE_REASON, SCHEDULED_MESSAGE_STATUS } from 'stream-chat';
+
+import { useComponentsContext } from '../../../contexts/componentsContext/ComponentsContext';
+import type { IconsMap } from '../../../contexts/componentsContext/defaultComponents';
+import type { TranslationContextValue } from '../../../contexts/translationContext/TranslationContext';
+import { useTranslationContext } from '../../../contexts/translationContext/TranslationContext';
+import type { ActionItem } from '../../../hooks/actions/types';
+import { isScheduledMessageLocked } from '../utils/status';
+
+// Required lazily: a static import of defaultComponents.ts would form a cycle
+// (defaultComponents -> ScheduledMessageActionsSheet -> this file) and corrupt init order.
+let cachedDefaultIcons: IconsMap | undefined;
+const getDefaultIcons = (): IconsMap => {
+ if (!cachedDefaultIcons) {
+ cachedDefaultIcons = (
+ require('../../../contexts/componentsContext/defaultComponents') as { defaultIcons: IconsMap }
+ ).defaultIcons;
+ }
+ return cachedDefaultIcons;
+};
+
+export type ScheduledMessageActionItem = ActionItem<
+ 'copyMessageText' | 'delete' | 'edit' | 'reschedule' | 'sendNow' | string
+>;
+
+/** The actions of one scheduled message, bound to it. */
+export type ScheduledMessageActions = {
+ copyMessageText: () => void;
+ /** Asks for confirmation, then deletes the message. */
+ delete: () => void;
+ /** Opens the date and time sheet. */
+ reschedule: () => void;
+ sendNow: () => void;
+ /** Opens the message in a composer. Absent where the list has nowhere to edit. */
+ edit?: () => void;
+};
+
+export type ScheduledMessageActionItemsParams = {
+ actions: ScheduledMessageActions;
+ icons: IconsMap;
+ scheduledMessage: LocalScheduledMessage;
+ t: TranslationContextValue['t'];
+};
+
+export type BuildDefaultScheduledMessageActionItems = (
+ scheduledMessageActionItemsParams: Omit & {
+ icons?: IconsMap;
+ },
+) => ScheduledMessageActionItem[];
+
+/**
+ * The default actions of a scheduled message, by its status: none while the client's request for it
+ * is in flight or the server is sending it; edit, reschedule, send now and delete while it waits;
+ * edit, reschedule and delete once it failed; copy and delete once its channel was deleted; delete
+ * alone while its send now waits in the offline queue. Edit also needs `actions.edit`.
+ */
+export const buildDefaultScheduledMessageActionItems: BuildDefaultScheduledMessageActionItems = ({
+ actions,
+ icons = getDefaultIcons(),
+ scheduledMessage: { failure_reason, localMetadata, status },
+ t,
+}) => {
+ if (isScheduledMessageLocked({ localMetadata, status })) return [];
+
+ const copyMessageText: ScheduledMessageActionItem = {
+ action: actions.copyMessageText,
+ Icon: icons.Copy,
+ id: 'copyMessageText',
+ label: t('scheduledMessages.copyText.label', 'Copy text'),
+ type: 'standard',
+ };
+ const deleteItem: ScheduledMessageActionItem = {
+ action: actions.delete,
+ Icon: icons.Delete,
+ id: 'delete',
+ label: t('scheduledMessages.delete.label', 'Delete'),
+ type: 'destructive',
+ };
+
+ if (
+ status === SCHEDULED_MESSAGE_STATUS.Failed &&
+ failure_reason === SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted
+ ) {
+ return [copyMessageText, deleteItem];
+ }
+
+ // Its send now waits in the offline queue: it can only be taken back.
+ if (status === SCHEDULED_MESSAGE_STATUS.Sending && localMetadata?.requestState === 'queued') {
+ return [deleteItem];
+ }
+
+ const items: ScheduledMessageActionItem[] = [];
+ if (actions.edit) {
+ items.push({
+ action: actions.edit,
+ Icon: icons.Edit,
+ id: 'edit',
+ label: t('scheduledMessages.editMessage.label', 'Edit message'),
+ type: 'standard',
+ });
+ }
+ items.push({
+ action: actions.reschedule,
+ Icon: icons.Time,
+ id: 'reschedule',
+ label: t('scheduledMessages.reschedule.label', 'Reschedule'),
+ type: 'standard',
+ });
+ // A failed message can't be sent as it is.
+ if (status !== SCHEDULED_MESSAGE_STATUS.Failed) {
+ items.push({
+ action: actions.sendNow,
+ Icon: icons.SendRight,
+ id: 'sendNow',
+ label: t('scheduledMessages.sendNow.label', 'Send now'),
+ type: 'standard',
+ });
+ }
+ items.push(deleteItem);
+ return items;
+};
+
+export type GetScheduledMessageActionItems = (params: {
+ context: ScheduledMessageActionItemsParams;
+ defaultItems: ScheduledMessageActionItem[];
+}) => ScheduledMessageActionItem[];
+
+export const getScheduledMessageActionItems: GetScheduledMessageActionItems = ({ defaultItems }) =>
+ defaultItems;
+
+type UseScheduledMessageActionItemsParams = {
+ actions: ScheduledMessageActions;
+ scheduledMessage: LocalScheduledMessage;
+ getScheduledMessageActionItems?: GetScheduledMessageActionItems;
+};
+
+/** The action items of a scheduled message: the defaults, customized by `getScheduledMessageActionItems`. */
+export const useScheduledMessageActionItems = ({
+ actions,
+ scheduledMessage,
+ getScheduledMessageActionItems:
+ getScheduledMessageActionItemsProp = getScheduledMessageActionItems,
+}: UseScheduledMessageActionItemsParams) => {
+ const { t } = useTranslationContext();
+ const { icons } = useComponentsContext();
+
+ const scheduledMessageActionItemsParams = useMemo(
+ () => ({ actions, icons, scheduledMessage, t }),
+ [actions, icons, scheduledMessage, t],
+ );
+
+ const defaultItems = useMemo(
+ () => buildDefaultScheduledMessageActionItems(scheduledMessageActionItemsParams),
+ [scheduledMessageActionItemsParams],
+ );
+
+ return useMemo(
+ () =>
+ getScheduledMessageActionItemsProp({
+ context: scheduledMessageActionItemsParams,
+ defaultItems,
+ }),
+ [defaultItems, getScheduledMessageActionItemsProp, scheduledMessageActionItemsParams],
+ );
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts b/package/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts
new file mode 100644
index 0000000000..6de0aa2ded
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts
@@ -0,0 +1,53 @@
+import { useEffect } from 'react';
+
+import type {
+ PaginatorState,
+ ScheduledMessageResponse,
+ ScheduledMessagesView,
+ ScheduledMessagesViewState,
+} from 'stream-chat';
+
+import { useScheduledMessages } from './useScheduledMessages';
+
+import { useStableCallback } from '../../../hooks/useStableCallback';
+import { useStateStore } from '../../../hooks/useStateStore';
+
+const paginatorSelector = ({
+ hasMoreTail,
+ isLoading,
+ lastQueryError,
+}: PaginatorState) => ({
+ error: lastQueryError,
+ hasMoreTail,
+ isLoading,
+});
+
+const itemsSelector = ({ items }: ScheduledMessagesViewState) => ({ items });
+
+/**
+ * A view's messages for a list screen, with its paginator's loading state. Loads the first page if
+ * it has not been loaded. `items` stays `undefined` until then, for the loading state.
+ */
+export const useScheduledMessageList = (view: ScheduledMessagesView) => {
+ const { paginator } = view;
+ const { error, hasMoreTail, isLoading } = useStateStore(paginator.state, paginatorSelector);
+ // keeps the view following its paginator while the list is shown
+ useScheduledMessages(view);
+ const { items } = useStateStore(view.state, itemsSelector);
+
+ useEffect(() => {
+ if (paginator.hasLoadedPage || paginator.isLoading) return;
+ paginator.reload().catch(() => undefined);
+ }, [paginator]);
+
+ const loadMore = useStableCallback(() => {
+ if (!hasMoreTail || isLoading) return;
+ paginator.toTail().catch(() => undefined);
+ });
+
+ const reload = useStableCallback(() => {
+ paginator.reload().catch(() => undefined);
+ });
+
+ return { error, hasMoreTail, isLoading, items, loadMore, reload };
+};
diff --git a/package/src/components/ScheduledMessages/hooks/useScheduledMessages.ts b/package/src/components/ScheduledMessages/hooks/useScheduledMessages.ts
new file mode 100644
index 0000000000..e91f613d84
--- /dev/null
+++ b/package/src/components/ScheduledMessages/hooks/useScheduledMessages.ts
@@ -0,0 +1,29 @@
+import { useEffect } from 'react';
+
+import type {
+ ScheduledMessageResponse,
+ ScheduledMessagesView,
+ ScheduledMessagesViewState,
+} from 'stream-chat';
+
+import { useStateStore } from '../../../hooks/useStateStore';
+
+const NO_SCHEDULED_MESSAGES: ScheduledMessageResponse[] = [];
+
+const itemsSelector = ({ items }: ScheduledMessagesViewState) => ({ items });
+
+/**
+ * The messages of a scheduled-message view, kept following its paginator while mounted. It loads
+ * nothing: `useChannelScheduledMessages` and `useScheduledMessageList` load the list too.
+ */
+export const useScheduledMessages = (view: ScheduledMessagesView) => {
+ useEffect(() => {
+ view.registerSubscriptions();
+ return () => {
+ view.unregisterSubscriptions();
+ };
+ }, [view]);
+
+ const { items } = useStateStore(view.state, itemsSelector);
+ return { scheduledMessages: items ?? NO_SCHEDULED_MESSAGES };
+};
diff --git a/package/src/components/ScheduledMessages/index.ts b/package/src/components/ScheduledMessages/index.ts
new file mode 100644
index 0000000000..4482dc3afb
--- /dev/null
+++ b/package/src/components/ScheduledMessages/index.ts
@@ -0,0 +1,29 @@
+export * from './ChannelScheduledMessages';
+export * from './ScheduledMessageActionsSheet';
+export * from './ScheduledMessageEditComposer';
+export * from './ScheduledMessageList';
+export * from './ScheduledMessageListItem';
+export * from './ScheduledMessageListLoadingSkeleton';
+export * from './ScheduledMessagesBanner';
+export * from './ScheduleMessageSheet';
+export * from './ScheduleSheetHeader';
+export * from './ScheduleSheetNotice';
+export * from './ScheduleTimeSheet';
+export * from './hooks/useChannelScheduledMessageLimit';
+export * from './hooks/useChannelScheduledMessages';
+export * from './hooks/useChannelWideScheduledMessagesView';
+export * from './hooks/useEditedScheduledMessage';
+export * from './hooks/useScheduleComposerMessage';
+export * from './hooks/useScheduledMessageActionHandlers';
+export * from './hooks/useScheduledMessageActionItems';
+export * from './hooks/useScheduledMessageList';
+export * from './hooks/useScheduledMessages';
+export * from './utils/actions';
+export * from './utils/failureReason';
+export * from './utils/scheduleErrors';
+export * from './utils/scheduleTime';
+export * from './utils/scheduledTimeLabels';
+export * from './utils/quote';
+export * from './QuoteDeletedNotice';
+export * from './RescheduleFailedMessageButton';
+export * from './ScheduledMessageSaveButton';
diff --git a/package/src/components/ScheduledMessages/utils/actions.ts b/package/src/components/ScheduledMessages/utils/actions.ts
new file mode 100644
index 0000000000..f6c340a85c
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/actions.ts
@@ -0,0 +1,5 @@
+import type { ScheduledMessageResponse } from 'stream-chat';
+import { SCHEDULED_MESSAGE_STATUS } from 'stream-chat';
+
+export const isPendingScheduledMessage = ({ status }: Pick) =>
+ status === SCHEDULED_MESSAGE_STATUS.Scheduled || status === SCHEDULED_MESSAGE_STATUS.Sending;
diff --git a/package/src/components/ScheduledMessages/utils/failureReason.ts b/package/src/components/ScheduledMessages/utils/failureReason.ts
new file mode 100644
index 0000000000..9e83ea5ae8
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/failureReason.ts
@@ -0,0 +1,46 @@
+import type { ScheduledMessageResponse } from 'stream-chat';
+import { SCHEDULED_MESSAGE_FAILURE_REASON } from 'stream-chat';
+
+import type { StreamTFunction } from '../../../i18n/types';
+
+/** The copy shown under a failed scheduled message, or `undefined` when there is nothing to say. */
+export const getScheduledMessageFailureText = (
+ t: StreamTFunction,
+ { failure_reason }: Pick,
+) => {
+ switch (failure_reason) {
+ case SCHEDULED_MESSAGE_FAILURE_REASON.Banned:
+ return t('scheduledMessages.failure.banned.text', "You can't send messages in this channel.");
+ case SCHEDULED_MESSAGE_FAILURE_REASON.NoPermission:
+ return t(
+ 'scheduledMessages.failure.noPermission.text',
+ "You're no longer allowed to post here.",
+ );
+ case SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen:
+ return t('scheduledMessages.failure.channelFrozen.text', 'This channel is frozen.');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted:
+ return t('scheduledMessages.failure.channelDeleted.text', 'This channel was deleted');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.ModerationBlocked:
+ return t('scheduledMessages.failure.moderationBlocked.text', 'Blocked by moderation.');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.HookRejected:
+ return t('scheduledMessages.failure.hookRejected.text', 'Rejected by the app.');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.Expired:
+ return t('scheduledMessages.failure.expired.text', 'Not sent: the service was delayed.');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.InvalidMessage:
+ return t(
+ 'scheduledMessages.failure.invalidMessage.text',
+ "The message no longer meets the app's limits. Edit it.",
+ );
+ case SCHEDULED_MESSAGE_FAILURE_REASON.PendingNotSupported:
+ return t(
+ 'scheduledMessages.failure.pendingNotSupported.text',
+ 'This channel now needs approval. Schedule it again.',
+ );
+ case SCHEDULED_MESSAGE_FAILURE_REASON.InternalError:
+ return t('scheduledMessages.failure.internalError.text', 'Something went wrong. Try again');
+ case SCHEDULED_MESSAGE_FAILURE_REASON.UserDeleted:
+ return undefined;
+ default:
+ return t('scheduledMessages.failure.default.text', "Couldn't send. Try again");
+ }
+};
diff --git a/package/src/components/ScheduledMessages/utils/quote.ts b/package/src/components/ScheduledMessages/utils/quote.ts
new file mode 100644
index 0000000000..9281599a6e
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/quote.ts
@@ -0,0 +1,13 @@
+import type { LocalMessage, ScheduledMessageResponse } from 'stream-chat';
+
+/** Whether a scheduled message quotes a message that no longer exists. */
+export const hasDeletedQuote = ({ message }: Pick) =>
+ !!message.quoted_message_id &&
+ (!message.quoted_message || message.quoted_message.type === 'deleted');
+
+/**
+ * Whether the composer's quoted message is gone. Editing a scheduled message whose quote can't be
+ * loaded leaves a placeholder with only the id.
+ */
+export const isDeletedQuotedMessage = (quotedMessage?: LocalMessage | null) =>
+ !!quotedMessage && (quotedMessage.type === 'deleted' || !quotedMessage.created_at);
diff --git a/package/src/components/ScheduledMessages/utils/scheduleErrors.ts b/package/src/components/ScheduledMessages/utils/scheduleErrors.ts
new file mode 100644
index 0000000000..18641c0416
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/scheduleErrors.ts
@@ -0,0 +1,71 @@
+import type { Channel } from 'stream-chat';
+import {
+ getScheduledMessageErrorReason,
+ getScheduledMessageLimits,
+ ScheduledMessageErrorReason,
+} from 'stream-chat';
+
+import type { StreamTFunction } from '../../../i18n/types';
+
+const getErrorStatus = (error: unknown) =>
+ typeof error === 'object' && error !== null && 'status' in error
+ ? (error as { status?: unknown }).status
+ : undefined;
+
+/**
+ * The copy shown in the date and time sheet when scheduling or rescheduling fails. `channel` supplies
+ * the per-user limit for its copy.
+ */
+export const getScheduleErrorText = (
+ t: StreamTFunction,
+ error: unknown,
+ action: 'schedule' | 'reschedule' | 'update' = 'schedule',
+ channel?: Channel,
+) => {
+ switch (getScheduledMessageErrorReason(error)) {
+ case ScheduledMessageErrorReason.TooSoon:
+ return t(
+ 'scheduledMessages.rescheduleTooSoon.error',
+ "Pick a later time. Editing can't send a message right away.",
+ );
+ case ScheduledMessageErrorReason.TooFar:
+ return t('scheduledMessages.tooFar.error', "That's further ahead than your app allows");
+ case ScheduledMessageErrorReason.ChannelLimit:
+ return t(
+ 'scheduledMessages.channelLimit.error',
+ "You've reached the limit of scheduled messages in this channel.",
+ );
+ case ScheduledMessageErrorReason.UserLimit: {
+ const maxPerUser = channel ? getScheduledMessageLimits(channel)?.maxPerUser : undefined;
+ // The limit is only known when the channel's config carries it.
+ return maxPerUser === undefined
+ ? t('scheduledMessages.userLimit.error', "You've reached your limit of scheduled messages.")
+ : t(
+ 'scheduledMessages.userLimitCount.error',
+ "You've reached your limit of {{ count }} scheduled messages.",
+ { count: maxPerUser },
+ );
+ }
+ case ScheduledMessageErrorReason.Disabled:
+ return t('scheduledMessages.disabled.error', 'Scheduled messages are turned off');
+ case ScheduledMessageErrorReason.AlreadySent:
+ return t('scheduledMessages.alreadySent.error', 'This message was already sent');
+ default:
+ if (getErrorStatus(error) === 403) {
+ return t('scheduledMessages.forbidden.error', "You can't schedule messages here");
+ }
+ if (action === 'reschedule') {
+ return t(
+ 'scheduledMessages.rescheduleFailed.error',
+ "Couldn't reschedule the message. Try again",
+ );
+ }
+ if (action === 'update') {
+ return t(
+ 'scheduledMessages.updateFailed.error',
+ "Couldn't update the scheduled message. Try again",
+ );
+ }
+ return t('scheduledMessages.scheduleFailed.error', "Couldn't schedule message. Try again");
+ }
+};
diff --git a/package/src/components/ScheduledMessages/utils/scheduleTime.ts b/package/src/components/ScheduledMessages/utils/scheduleTime.ts
new file mode 100644
index 0000000000..39605f6442
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/scheduleTime.ts
@@ -0,0 +1,90 @@
+import type { Channel } from 'stream-chat';
+import { getScheduledMessageLimits } from 'stream-chat';
+
+export const SCHEDULE_PRESET_HOURS = { afternoon: 13, morning: 9 } as const;
+
+export type ScheduleTimeBounds = {
+ /** The earliest time the server accepts. */
+ earliest: Date;
+ /** The latest time the server accepts, when the app sets a maximum lead time. */
+ latest?: Date;
+};
+
+export type ScheduleTimeError = 'too_soon' | 'too_far';
+
+/** Returns `date` moved by `dayOffset` days, at `hour`:00 in the device's time zone. */
+export const getLocalDateAtHour = (date: Date, dayOffset: number, hour: number) => {
+ const localDate = new Date(date);
+ localDate.setDate(date.getDate() + dayOffset);
+ localDate.setHours(hour, 0, 0, 0);
+ return localDate;
+};
+
+export const getDaysUntilNextMonday = (date: Date) => {
+ const daysUntilMonday = (7 - date.getDay() + 1) % 7;
+ return daysUntilMonday || 7;
+};
+
+export const isSameLocalDay = (a: Date, b: Date) => a.toDateString() === b.toDateString();
+
+/** Tomorrow morning, tomorrow afternoon and next Monday morning, unless Monday is tomorrow. */
+export const getSchedulePresets = (now: Date) => {
+ const tomorrowMorning = getLocalDateAtHour(now, 1, SCHEDULE_PRESET_HOURS.morning);
+ const tomorrowAfternoon = getLocalDateAtHour(now, 1, SCHEDULE_PRESET_HOURS.afternoon);
+ const nextMondayMorning = getLocalDateAtHour(
+ now,
+ getDaysUntilNextMonday(now),
+ SCHEDULE_PRESET_HOURS.morning,
+ );
+
+ return isSameLocalDay(nextMondayMorning, tomorrowMorning)
+ ? [tomorrowMorning, tomorrowAfternoon]
+ : [tomorrowMorning, tomorrowAfternoon, nextMondayMorning];
+};
+
+export const getScheduleTimeBounds = (channel: Channel, now: Date): ScheduleTimeBounds => {
+ const { maxLeadTimeSeconds, minLeadTimeSeconds = 0 } = getScheduledMessageLimits(channel) ?? {};
+ const nowMs = now.getTime();
+
+ return {
+ earliest: new Date(nowMs + minLeadTimeSeconds * 1000),
+ latest:
+ maxLeadTimeSeconds === undefined ? undefined : new Date(nowMs + maxLeadTimeSeconds * 1000),
+ };
+};
+
+export const getScheduleTimeError = (
+ scheduledAt: Date,
+ { earliest, latest }: ScheduleTimeBounds,
+): ScheduleTimeError | undefined => {
+ if (scheduledAt < earliest) return 'too_soon';
+ if (latest && scheduledAt > latest) return 'too_far';
+ return undefined;
+};
+
+export const getAvailableSchedulePresets = (now: Date, bounds: ScheduleTimeBounds) =>
+ getSchedulePresets(now).filter((preset) => !getScheduleTimeError(preset, bounds));
+
+/** The time the custom picker opens with: tomorrow at 09:00, or the earliest allowed after it. */
+export const getDefaultScheduledAt = (now: Date, bounds: ScheduleTimeBounds) => {
+ const tomorrowMorning = getLocalDateAtHour(now, 1, SCHEDULE_PRESET_HOURS.morning);
+ if (!getScheduleTimeError(tomorrowMorning, bounds)) return tomorrowMorning;
+
+ const earliest = new Date(bounds.earliest);
+ earliest.setSeconds(0, 0);
+ earliest.setMinutes(earliest.getMinutes() + 1);
+ return earliest;
+};
+
+/** Formats the device's UTC offset like `GMT+2` or `GMT+5:30`. */
+export const formatTimeZoneOffset = (date: Date) => {
+ const offset = -date.getTimezoneOffset();
+ if (!offset) return 'GMT';
+
+ const sign = offset < 0 ? '-' : '+';
+ const absolute = Math.abs(offset);
+ const hours = Math.floor(absolute / 60);
+ const minutes = absolute % 60;
+
+ return minutes ? `GMT${sign}${hours}:${String(minutes).padStart(2, '0')}` : `GMT${sign}${hours}`;
+};
diff --git a/package/src/components/ScheduledMessages/utils/scheduledTimeLabels.ts b/package/src/components/ScheduledMessages/utils/scheduledTimeLabels.ts
new file mode 100644
index 0000000000..5f65b22846
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/scheduledTimeLabels.ts
@@ -0,0 +1,69 @@
+import { isSameLocalDay } from './scheduleTime';
+
+import type { TranslationContextValue } from '../../../contexts/translationContext/TranslationContext';
+import { getDateString } from '../../../i18n/utils';
+
+/** The translation functions the scheduled time labels are resolved with. */
+export type ScheduledTimeTranslators = Pick;
+
+const formatWithKey = ({
+ date,
+ t,
+ tDateTimeParser,
+ timestampTranslationKey,
+}: ScheduledTimeTranslators & { date: Date; timestampTranslationKey: string }) =>
+ String(
+ getDateString({ messageCreatedAt: date, t, tDateTimeParser, timestampTranslationKey }) ?? '',
+ );
+
+/**
+ * Formats the time of a scheduled message with the `timestamp.ScheduledMessageTime` translation,
+ * which defaults to the 24 hour `HH:mm` format of the design.
+ */
+export const formatScheduledTime = (date: Date, translators: ScheduledTimeTranslators) =>
+ formatWithKey({
+ ...translators,
+ date,
+ timestampTranslationKey: 'timestamp.ScheduledMessageTime',
+ });
+
+/** Formats the day of a scheduled message with the `timestamp.ScheduledMessageDate` translation. */
+export const formatScheduledDate = (date: Date, translators: ScheduledTimeTranslators) =>
+ formatWithKey({
+ ...translators,
+ date,
+ timestampTranslationKey: 'timestamp.ScheduledMessageDate',
+ });
+
+/** Formats a scheduled send time such as `Fri, Oct 23 at 09:00`. */
+export const formatScheduledDateTime = (date: Date, translators: ScheduledTimeTranslators) =>
+ translators.t('scheduledMessages.dateTime.label', '{{ day }} at {{ time }}', {
+ day: formatScheduledDate(date, translators),
+ time: formatScheduledTime(date, translators),
+ });
+
+/** Formats a quick schedule option such as `Tomorrow at 09:00` or `Monday at 09:00`. */
+export const formatSchedulePreset = (
+ date: Date,
+ now: Date,
+ translators: ScheduledTimeTranslators,
+) => {
+ const tomorrow = new Date(now);
+ tomorrow.setDate(now.getDate() + 1);
+ const time = formatScheduledTime(date, translators);
+
+ if (isSameLocalDay(date, tomorrow)) {
+ return translators.t('scheduledMessages.preset.tomorrow.label', 'Tomorrow at {{ time }}', {
+ time,
+ });
+ }
+
+ return translators.t('scheduledMessages.preset.weekday.label', '{{ day }} at {{ time }}', {
+ day: formatWithKey({
+ ...translators,
+ date,
+ timestampTranslationKey: 'timestamp.ScheduledMessageWeekday',
+ }),
+ time,
+ });
+};
diff --git a/package/src/components/ScheduledMessages/utils/status.ts b/package/src/components/ScheduledMessages/utils/status.ts
new file mode 100644
index 0000000000..d81f4f277c
--- /dev/null
+++ b/package/src/components/ScheduledMessages/utils/status.ts
@@ -0,0 +1,27 @@
+import { isPendingUpload, SCHEDULED_MESSAGE_STATUS } from 'stream-chat';
+import type { LocalScheduledMessage } from 'stream-chat';
+
+/** Whether a scheduled message shows as sending: it is still being scheduled, or being sent. */
+export const isScheduledMessageSending = ({
+ localMetadata,
+ status,
+}: Pick) =>
+ !!localMetadata?.pending || status === SCHEDULED_MESSAGE_STATUS.Sending;
+
+/** Whether a message still being scheduled waits for its attachments to upload. */
+export const isScheduledMessageUploading = ({
+ localMetadata,
+ message,
+}: Pick) =>
+ !!localMetadata?.pending && !!message.attachments?.some(isPendingUpload);
+
+/**
+ * Whether a scheduled message can't be acted on: the client's own request for it is in flight, or
+ * the server is sending it. One whose request waits in the offline queue can.
+ */
+export const isScheduledMessageLocked = ({
+ localMetadata,
+ status,
+}: Pick) =>
+ localMetadata?.requestState === 'inFlight' ||
+ (status === SCHEDULED_MESSAGE_STATUS.Sending && localMetadata?.requestState !== 'queued');
diff --git a/package/src/components/Thread/__tests__/__snapshots__/Thread.test.tsx.snap b/package/src/components/Thread/__tests__/__snapshots__/Thread.test.tsx.snap
index ac4eea8af2..cd0302a2fe 100644
--- a/package/src/components/Thread/__tests__/__snapshots__/Thread.test.tsx.snap
+++ b/package/src/components/Thread/__tests__/__snapshots__/Thread.test.tsx.snap
@@ -11,6 +11,7 @@ exports[`Thread should match thread snapshot 1`] = `
}
>
+
+
+
+
+
& {
/**
- * Determines the height of the `AttachmentPicker` and how far the `MessageList` shifts when it
- * opens. Set via the `bottomInset` prop on `Channel`.
+ * Space at the bottom of the `Channel` covered by something positioned over it, such as an
+ * absolutely positioned tab bar. The `AttachmentPicker` and the composer above it are lifted by
+ * this much. Set via the `bottomInset` prop on `Channel`.
*/
bottomInset: number;
bottomSheetRef: React.RefObject;
closePicker: () => void;
openPicker: () => void;
+ /**
+ * The distance from the top of the window to the top of the `Channel`, such as a header or a
+ * native modal above it. Set via the `topInset` prop on `Channel`.
+ */
topInset: number;
/**
diff --git a/package/src/contexts/componentsContext/defaultComponents.ts b/package/src/contexts/componentsContext/defaultComponents.ts
index 742cf49d0c..0ef5407d7c 100644
--- a/package/src/contexts/componentsContext/defaultComponents.ts
+++ b/package/src/contexts/componentsContext/defaultComponents.ts
@@ -171,6 +171,11 @@ import { PollOptionFullResultsContent } from '../../components/Poll/components/P
import { PollResultsContent } from '../../components/Poll/components/PollResults/PollResults';
import { PollHeader } from '../../components/Poll/Poll';
import { Reply } from '../../components/Reply/Reply';
+import { ScheduledMessageActionsSheet } from '../../components/ScheduledMessages/ScheduledMessageActionsSheet';
+import { ScheduledMessageListItem } from '../../components/ScheduledMessages/ScheduledMessageListItem';
+import { ScheduledMessagesBanner } from '../../components/ScheduledMessages/ScheduledMessagesBanner';
+import { ScheduleMessageSheet } from '../../components/ScheduledMessages/ScheduleMessageSheet';
+import { ScheduleTimeSheet } from '../../components/ScheduledMessages/ScheduleTimeSheet';
import {
DefaultThreadListComponent as ThreadListComponent,
DefaultThreadListEmptyPlaceholder,
@@ -190,6 +195,7 @@ import { ArrowUpRight } from '../../icons/arrow-up-right';
import { Sound } from '../../icons/audio';
import { Bell } from '../../icons/bell';
import { Lightning } from '../../icons/bolt';
+import { Calendar } from '../../icons/calendar';
import { Camera } from '../../icons/camera';
import { Check, Tick } from '../../icons/checkmark';
import { Checkmark } from '../../icons/checkmark-1';
@@ -204,6 +210,7 @@ import { Delete } from '../../icons/delete';
import { Edit } from '../../icons/edit';
import { Smile } from '../../icons/emoji';
import { MoreEmojis } from '../../icons/emoji-add-1';
+import { ExclamationCircleOutline } from '../../icons/exclamation-circle';
import { ExclamationCircle } from '../../icons/exclamation-circle-fill';
import { Exclamation } from '../../icons/exclamation-mark-fill';
import { Warning } from '../../icons/exclamation-triangle-fill';
@@ -288,6 +295,7 @@ export const defaultIcons = {
Bell,
BlockUser,
Bookmark,
+ Calendar,
Camera,
Check,
CheckAll,
@@ -309,6 +317,7 @@ export const defaultIcons = {
Edit,
Exclamation,
ExclamationCircle,
+ ExclamationCircleOutline,
EyeOpen,
File,
FilePickerIcon,
@@ -484,6 +493,11 @@ const components = {
ReactionListItemWrapper,
ReactionListTop,
Reply,
+ ScheduledMessageActionsSheet,
+ ScheduledMessageListItem,
+ ScheduledMessagesBanner,
+ ScheduleMessageSheet,
+ ScheduleTimeSheet,
ScrollToBottomButton,
SendButton,
SendMessageDisallowedIndicator,
diff --git a/package/src/contexts/messageComposerContext/MessageComposerAPIContext.tsx b/package/src/contexts/messageComposerContext/MessageComposerAPIContext.tsx
index 4435d4db1d..5cbced8552 100644
--- a/package/src/contexts/messageComposerContext/MessageComposerAPIContext.tsx
+++ b/package/src/contexts/messageComposerContext/MessageComposerAPIContext.tsx
@@ -1,6 +1,6 @@
import React, { useContext } from 'react';
-import { LocalMessage, type MessageComposer } from 'stream-chat';
+import { LocalMessage, type MessageComposer, type ScheduledMessageResponse } from 'stream-chat';
import { DEFAULT_BASE_CONTEXT_VALUE } from '../utils/defaultBaseContextValue';
import { isTestEnvironment } from '../utils/isTestEnvironment';
@@ -9,6 +9,12 @@ export type MessageComposerAPIContextValue = {
setQuotedMessage: MessageComposer['setQuotedMessage'];
setEditingState: (message?: LocalMessage) => void;
clearEditingState: () => void;
+ /**
+ * Opens a scheduled message for editing in a composer of its own, so the channel's composer and
+ * its draft are left as they are. The composer is put in use once it is filled in, which may wait
+ * for the quoted message and the mentioned users. Saving or cancelling ends the edit.
+ */
+ editScheduledMessage: (scheduledMessage: ScheduledMessageResponse) => Promise;
};
export const MessageComposerAPIContext = React.createContext(
diff --git a/package/src/contexts/messageComposerContext/MessageComposerContext.tsx b/package/src/contexts/messageComposerContext/MessageComposerContext.tsx
index 6ba9777d50..3c50b8bea2 100644
--- a/package/src/contexts/messageComposerContext/MessageComposerContext.tsx
+++ b/package/src/contexts/messageComposerContext/MessageComposerContext.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useMemo, useState } from 'react';
+import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { LocalMessage, MessageComposer, MessageComposerState } from 'stream-chat';
@@ -39,12 +39,21 @@ const editedMessageSelector = (state: MessageComposerState) => ({
editedMessage: state.editedMessage,
});
+const editedScheduledMessageSelector = (state: MessageComposerState) => ({
+ editedScheduledMessage: state.editedScheduledMessage,
+});
+
export const MessageComposerProvider = ({ children, value }: Props) => {
const { client } = useChatContext();
const { channel, thread } = value;
const [editComposer, setEditComposer] = useState(undefined);
+ const [scheduledEditComposer, setScheduledEditComposer] = useState(
+ undefined,
+ );
+ const latestScheduledEditComposer = useRef(undefined);
- const messageComposer = editComposer ?? thread?.messageComposer ?? channel.messageComposer;
+ const messageComposer =
+ editComposer ?? scheduledEditComposer ?? thread?.messageComposer ?? channel.messageComposer;
// Submitting or clearing the edit composer clears its edited message, which ends the edit.
const { editedMessage } = useStateStore(editComposer?.state, editedMessageSelector) ?? {};
@@ -54,6 +63,14 @@ export const MessageComposerProvider = ({ children, value }: Props) => {
}
}, [editComposer, editedMessage]);
+ const { editedScheduledMessage } =
+ useStateStore(scheduledEditComposer?.state, editedScheduledMessageSelector) ?? {};
+ useEffect(() => {
+ if (scheduledEditComposer && !editedScheduledMessage) {
+ setScheduledEditComposer(undefined);
+ }
+ }, [editedScheduledMessage, scheduledEditComposer]);
+
useEffect(() => messageComposer.registerSubscriptions(), [messageComposer]);
const setEditingState: MessageComposerAPIContextValue['setEditingState'] = useStableCallback(
@@ -85,6 +102,18 @@ export const MessageComposerProvider = ({ children, value }: Props) => {
() => setEditComposer(undefined),
);
+ const editScheduledMessage: MessageComposerAPIContextValue['editScheduledMessage'] =
+ useStableCallback(async (scheduledMessage) => {
+ // Not cached: it lives only as long as the edit.
+ const composer = new MessageComposer({ client, compositionContext: channel });
+ latestScheduledEditComposer.current = composer;
+ await composer.editScheduledMessage(scheduledMessage);
+ // When another message was opened while this one loaded, only the last one is shown.
+ if (latestScheduledEditComposer.current === composer) {
+ setScheduledEditComposer(composer);
+ }
+ });
+
const setQuotedMessage = useStableCallback((message: LocalMessage | null) =>
messageComposer.setQuotedMessage(message),
);
@@ -95,8 +124,8 @@ export const MessageComposerProvider = ({ children, value }: Props) => {
);
const messageComposerAPIContextValue = useMemo(
- () => ({ clearEditingState, setEditingState, setQuotedMessage }),
- [clearEditingState, setEditingState, setQuotedMessage],
+ () => ({ clearEditingState, editScheduledMessage, setEditingState, setQuotedMessage }),
+ [clearEditingState, editScheduledMessage, setEditingState, setQuotedMessage],
);
return (
diff --git a/package/src/contexts/messageInputContext/MessageInputContext.tsx b/package/src/contexts/messageInputContext/MessageInputContext.tsx
index 4669610a0d..96c4bb4ced 100644
--- a/package/src/contexts/messageInputContext/MessageInputContext.tsx
+++ b/package/src/contexts/messageInputContext/MessageInputContext.tsx
@@ -9,6 +9,7 @@ import React, {
} from 'react';
import { Alert, Linking, TextInputProps } from 'react-native';
+import { StateStore } from '@stream-io/state-store';
import { lookup as lookupMimeType } from 'mime-types';
import { useCreateMessageInputContext } from './hooks/useCreateMessageInputContext';
@@ -33,6 +34,8 @@ import { DEFAULT_BASE_CONTEXT_VALUE } from '../utils/defaultBaseContextValue';
import { isTestEnvironment } from '../utils/isTestEnvironment';
+export type ScheduleSheetState = { isOpen: boolean };
+
export type LocalMessageInputContext = {
closeAttachmentPicker: () => void;
inputBoxRef: React.RefObject;
@@ -53,6 +56,10 @@ export type LocalMessageInputContext = {
deleteVoiceRecording: () => Promise;
uploadVoiceRecording: (sendOnComplete: boolean) => Promise;
stopVoiceRecording: () => Promise;
+ closeScheduleSheet: () => void;
+ /** Opens the sheet that schedules the composer's message, as a long press on send does. */
+ openScheduleSheet: () => void;
+ scheduleSheetStore: StateStore;
};
export type InputBoxRef = TextInputRef & {
@@ -175,6 +182,18 @@ export const MessageInputProvider = ({
const defaultOpenPollCreationDialog = useCallback(() => setShowPollCreationDialog(true), []);
const closePollCreationDialog = useCallback(() => setShowPollCreationDialog(false), []);
+ const [scheduleSheetStore] = useState(
+ () => new StateStore({ isOpen: false }),
+ );
+ const openScheduleSheet = useCallback(
+ () => scheduleSheetStore.partialNext({ isOpen: true }),
+ [scheduleSheetStore],
+ );
+ const closeScheduleSheet = useCallback(
+ () => scheduleSheetStore.partialNext({ isOpen: false }),
+ [scheduleSheetStore],
+ );
+
const { openPollCreationDialog: openPollCreationDialogFromContext } = value;
const messageComposer = useMessageComposer();
@@ -311,7 +330,15 @@ export const MessageInputProvider = ({
try {
// Editing a bounced message (type 'error') sends it again as a new message.
- const { editedMessage } = messageComposer;
+ const { editedMessage, editedScheduledMessage } = messageComposer;
+ if (editedScheduledMessage && editedScheduledMessage.status !== 'failed') {
+ const { status } = await messageComposer.updateScheduledMessage();
+ if (status !== 'scheduled') {
+ inputBoxRef.current?.restoreState(text);
+ }
+ return;
+ }
+
const result =
editedMessage && editedMessage.type !== 'error'
? await messageComposer.update()
@@ -398,6 +425,9 @@ export const MessageInputProvider = ({
openPollCreationDialog,
sendMessage,
showPollCreationDialog,
+ closeScheduleSheet,
+ openScheduleSheet,
+ scheduleSheetStore,
audioRecorderManager,
startVoiceRecording,
deleteVoiceRecording,
diff --git a/package/src/contexts/messageInputContext/hooks/useCreateMessageInputContext.ts b/package/src/contexts/messageInputContext/hooks/useCreateMessageInputContext.ts
index 0d14848804..c8687a07ca 100644
--- a/package/src/contexts/messageInputContext/hooks/useCreateMessageInputContext.ts
+++ b/package/src/contexts/messageInputContext/hooks/useCreateMessageInputContext.ts
@@ -39,6 +39,9 @@ export const useCreateMessageInputContext = ({
deleteVoiceRecording,
uploadVoiceRecording,
stopVoiceRecording,
+ closeScheduleSheet,
+ openScheduleSheet,
+ scheduleSheetStore,
}: MessageInputContextValue) => {
const messageInputContext: MessageInputContextValue = useMemo(
() => ({
@@ -78,6 +81,9 @@ export const useCreateMessageInputContext = ({
deleteVoiceRecording,
uploadVoiceRecording,
stopVoiceRecording,
+ closeScheduleSheet,
+ openScheduleSheet,
+ scheduleSheetStore,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hasCommands, showPollCreationDialog],
diff --git a/package/src/contexts/messagesContext/MessagesContext.tsx b/package/src/contexts/messagesContext/MessagesContext.tsx
index e23ae16953..730f3c2dd4 100644
--- a/package/src/contexts/messagesContext/MessagesContext.tsx
+++ b/package/src/contexts/messagesContext/MessagesContext.tsx
@@ -2,7 +2,7 @@ import React, { PropsWithChildren, useContext } from 'react';
import { PressableProps, ViewProps } from 'react-native';
-import type { Attachment, Channel, LocalMessage } from 'stream-chat';
+import type { Attachment, Channel, LocalMessage, Thread } from 'stream-chat';
import type { MessagePressableHandlerPayload } from '../../components/Message/Message';
import type { MarkdownRules } from '../../components/Message/MessageItemView/utils/renderText';
@@ -177,6 +177,12 @@ export type MessagesContextValue = {
* and in a channel also the reply's thread.
*/
onAlsoSentToChannelHeaderPress?: (payload: AlsoSentToChannelHeaderPressPayload) => void;
+ /**
+ * Handles a press on the scheduled messages banner above the composer, to open the scheduled
+ * messages of the channel or, in a thread, of the thread. The banner shows its `View` link only
+ * when this is set.
+ */
+ onScheduledMessagesBannerPress?: (payload: { channel: Channel; thread?: Thread }) => void;
/** Where the reaction list renders in the message. Defaults to 'top'. */
reactionListPosition?: 'top' | 'bottom';
diff --git a/package/src/contexts/themeContext/utils/theme.ts b/package/src/contexts/themeContext/utils/theme.ts
index 341e27aa64..5f81339b8f 100644
--- a/package/src/contexts/themeContext/utils/theme.ts
+++ b/package/src/contexts/themeContext/utils/theme.ts
@@ -1162,6 +1162,70 @@ export type Theme = {
};
};
screenPadding: number;
+ scheduledMessages: {
+ actionsSheet: {
+ container: ViewStyle;
+ };
+ banner: {
+ banner: ViewStyle;
+ container: ViewStyle;
+ label: TextStyle;
+ link: TextStyle;
+ };
+ list: {
+ container: ViewStyle;
+ list: ViewStyle;
+ listContent: ViewStyle;
+ };
+ listItem: {
+ channelName: TextStyle;
+ container: ViewStyle;
+ content: ViewStyle;
+ contentContainer: ViewStyle;
+ messageGroup: ViewStyle;
+ preview: TextStyle;
+ row: ViewStyle;
+ status: ViewStyle;
+ statusIcon: ViewStyle;
+ statusText: TextStyle;
+ time: TextStyle;
+ };
+ notice: {
+ container: ViewStyle;
+ description: TextStyle;
+ title: TextStyle;
+ };
+ presetSheet: {
+ container: ViewStyle;
+ option: ViewStyle;
+ optionLabel: TextStyle;
+ options: ViewStyle;
+ };
+ sheetHeader: {
+ container: ViewStyle;
+ title: TextStyle;
+ };
+ timeSheet: {
+ container: ViewStyle;
+ content: ViewStyle;
+ row: ViewStyle;
+ rowLabel: TextStyle;
+ rows: ViewStyle;
+ rowValue: TextStyle;
+ };
+ };
+ scheduledMessageListSkeleton: {
+ animationTime: number;
+ avatar: ViewStyle;
+ body: ViewStyle;
+ container: ViewStyle;
+ content: ViewStyle;
+ list: ViewStyle;
+ message: ViewStyle;
+ textContainer: ViewStyle;
+ time: ViewStyle;
+ title: ViewStyle;
+ };
selectionCircle: {
circle: ViewStyle;
circleSelected: ViewStyle;
@@ -2262,6 +2326,70 @@ export const defaultTheme: Theme = {
},
},
screenPadding: 16,
+ scheduledMessages: {
+ actionsSheet: {
+ container: {},
+ },
+ banner: {
+ banner: {},
+ container: {},
+ label: {},
+ link: {},
+ },
+ list: {
+ container: {},
+ list: {},
+ listContent: {},
+ },
+ listItem: {
+ channelName: {},
+ container: {},
+ content: {},
+ contentContainer: {},
+ messageGroup: {},
+ preview: {},
+ row: {},
+ status: {},
+ statusIcon: {},
+ statusText: {},
+ time: {},
+ },
+ notice: {
+ container: {},
+ description: {},
+ title: {},
+ },
+ presetSheet: {
+ container: {},
+ option: {},
+ optionLabel: {},
+ options: {},
+ },
+ sheetHeader: {
+ container: {},
+ title: {},
+ },
+ timeSheet: {
+ container: {},
+ content: {},
+ row: {},
+ rowLabel: {},
+ rows: {},
+ rowValue: {},
+ },
+ },
+ scheduledMessageListSkeleton: {
+ animationTime: 1000, // in milliseconds
+ avatar: {},
+ body: {},
+ container: {},
+ content: {},
+ list: {},
+ message: {},
+ textContainer: {},
+ time: {},
+ title: {},
+ },
selectionCircle: {
circle: {},
circleSelected: {},
diff --git a/package/src/hooks/__tests__/useCanScheduleMessages.test.tsx b/package/src/hooks/__tests__/useCanScheduleMessages.test.tsx
new file mode 100644
index 0000000000..137576fefa
--- /dev/null
+++ b/package/src/hooks/__tests__/useCanScheduleMessages.test.tsx
@@ -0,0 +1,57 @@
+import { act, cleanup, renderHook } from '@testing-library/react-native';
+import type { Channel } from 'stream-chat';
+
+import { initiateClientWithChannels } from '../../mock-builders/api/initiateClientWithChannels';
+import { useCanScheduleMessages } from '../useCanScheduleMessages';
+
+describe('useCanScheduleMessages', () => {
+ let channel: Channel;
+
+ const setScheduledMessagesEnabled = (enabled: boolean) =>
+ channel.configState.partialNext({
+ scheduledMessages: { ...channel.config.scheduledMessages, enabled },
+ });
+
+ const setOwnCapabilities = (ownCapabilities: string[]) => {
+ channel.data = { ...channel.data, own_capabilities: ownCapabilities };
+ channel.state.partialNext({ ownCapabilities });
+ };
+
+ beforeEach(async () => {
+ const { channels } = await initiateClientWithChannels();
+ channel = channels[0];
+ setScheduledMessagesEnabled(true);
+ setOwnCapabilities(['schedule-message']);
+ });
+
+ afterEach(cleanup);
+
+ it('is true when the config allows scheduling and the user has the capability', () => {
+ const { result } = renderHook(() => useCanScheduleMessages(channel));
+
+ expect(result.current).toBe(true);
+ });
+
+ it('follows the schedule-message capability as it changes', () => {
+ const { result } = renderHook(() => useCanScheduleMessages(channel));
+
+ act(() => setOwnCapabilities([]));
+ expect(result.current).toBe(false);
+
+ act(() => setOwnCapabilities(['schedule-message']));
+ expect(result.current).toBe(true);
+ });
+
+ it('follows the scheduled messages config as it changes', () => {
+ const { result } = renderHook(() => useCanScheduleMessages(channel));
+
+ act(() => setScheduledMessagesEnabled(false));
+ expect(result.current).toBe(false);
+ });
+
+ it('is false when there is no channel', () => {
+ const { result } = renderHook(() => useCanScheduleMessages());
+
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/package/src/hooks/index.ts b/package/src/hooks/index.ts
index 375a0d4bf8..1146d4163c 100644
--- a/package/src/hooks/index.ts
+++ b/package/src/hooks/index.ts
@@ -10,6 +10,7 @@ export * from './useChannelMembershipState';
export * from './useChannelOwnCapabilities';
export * from './useCanEditChannel';
export * from './useCanAddMembersToChannel';
+export * from './useCanScheduleMessages';
export * from './useChannelMuteActive';
export * from './useIsDirectChat';
export * from './useIsChannelMember';
diff --git a/package/src/hooks/useCanScheduleMessages.ts b/package/src/hooks/useCanScheduleMessages.ts
new file mode 100644
index 0000000000..4bafca3b7f
--- /dev/null
+++ b/package/src/hooks/useCanScheduleMessages.ts
@@ -0,0 +1,21 @@
+import type { Channel, ChannelConfig } from 'stream-chat';
+
+import { useChannelOwnCapabilities } from './useChannelOwnCapabilities';
+import { useStateStore } from './useStateStore';
+
+const enabledByConfigSelector = ({ scheduledMessages }: ChannelConfig) => ({
+ isEnabledByConfig: scheduledMessages.enabled,
+});
+
+/**
+ * Whether the current user can schedule messages in the channel, i.e. `channel.scheduledMessagesEnabled`.
+ * Subscribing to the user's capabilities and the scheduled messages config re-renders when either changes.
+ *
+ * @param channel The channel to check.
+ * @returns True when the config allows scheduling and the user has the `schedule-message` capability.
+ */
+export const useCanScheduleMessages = (channel?: Channel) => {
+ useChannelOwnCapabilities(channel);
+ useStateStore(channel?.configState, enabledByConfigSelector);
+ return channel?.scheduledMessagesEnabled ?? false;
+};
diff --git a/package/src/hooks/useFocusMessageInput.ts b/package/src/hooks/useFocusMessageInput.ts
new file mode 100644
index 0000000000..236ffd8bf5
--- /dev/null
+++ b/package/src/hooks/useFocusMessageInput.ts
@@ -0,0 +1,35 @@
+import { useEffect } from 'react';
+import { AppState, type EventSubscription, Keyboard, Platform } from 'react-native';
+
+import { useMessageInputContext } from '../contexts/messageInputContext/MessageInputContext';
+
+/**
+ * @internal
+ *
+ * Focuses the message input each time `focusFor` changes to a value, so the keyboard opens.
+ *
+ * On Android a sheet that is still closing can hold window focus, and the keyboard opens only for
+ * a focused window. So there it focuses again once the app window gets focus back.
+ * */
+export const useFocusMessageInput = (focusFor: string | undefined) => {
+ const { inputBoxRef } = useMessageInputContext();
+
+ useEffect(() => {
+ if (!focusFor) return;
+ inputBoxRef.current?.focus();
+ if (Platform.OS !== 'android') return;
+
+ const subscriptions: EventSubscription[] = [];
+ const stopWaiting = () => subscriptions.forEach((subscription) => subscription.remove());
+ subscriptions.push(
+ AppState.addEventListener('focus', () => {
+ stopWaiting();
+ // React Native skips `focus()` on the input it already considers focused.
+ inputBoxRef.current?.blur();
+ inputBoxRef.current?.focus();
+ }),
+ Keyboard.addListener('keyboardDidShow', stopWaiting),
+ );
+ return stopWaiting;
+ }, [focusFor, inputBoxRef]);
+};
diff --git a/package/src/i18n/__tests__/catalog.fixture.json b/package/src/i18n/__tests__/catalog.fixture.json
index 5348291385..50ef492e47 100644
--- a/package/src/i18n/__tests__/catalog.fixture.json
+++ b/package/src/i18n/__tests__/catalog.fixture.json
@@ -203,6 +203,7 @@
"channelDetails.navigation.files.label": "Files",
"channelDetails.navigation.photosAndVideos.label": "Photos & Videos",
"channelDetails.navigation.pinnedMessages.label": "Pinned Messages",
+ "channelDetails.navigation.scheduledMessages.label": "Scheduled Messages",
"channelDetails.pinnedMessageList.empty.description": "Long-press a message to pin it to the chat",
"channelDetails.pinnedMessageList.empty.title": "No pinned messages",
"channelDetails.pinnedMessageList.load.error": "Failed to load pinned messages",
@@ -409,10 +410,12 @@
"notifications.pollEndFailed.withReason.error": "Failed to end the poll due to {{reason}}",
"notifications.pollEnded.text": "Poll ended",
"notifications.recordingPlaybackFailed.error": "Error reproducing the recording",
+ "notifications.scheduledMessageBlocked.command.error": "Commands can't be scheduled",
"notifications.scheduledMessageBlocked.error": "This message cannot be scheduled",
+ "notifications.scheduledMessageCompositionEnded.deleted.error": "This scheduled message was deleted",
"notifications.scheduledMessageCompositionEnded.error": "The scheduled message can no longer be edited",
- "notifications.scheduledMessageCreateFailed.error": "Failed to schedule the message",
- "notifications.scheduledMessageUpdateFailed.error": "Failed to update the scheduled message",
+ "notifications.scheduledMessageCompositionEnded.failed.error": "This scheduled message failed to send",
+ "notifications.scheduledMessageCompositionEnded.sent.error": "This message was already sent",
"notifications.voteLimitReached.error": "Reached the vote limit. Remove an existing vote first.",
"poll.addComment.description": "Add a comment to the poll",
"poll.addComment.label": "Add a comment",
@@ -467,6 +470,79 @@
"reply.replyTo.title": "Reply to {{name}}",
"reply.replying.withUser.accessibilityLabel": "Replying to {{user}}",
"reply.replying.withUserAndText.accessibilityLabel": "Replying to {{user}}: {{text}}",
+ "scheduledMessages.alreadySent.error": "This message was already sent",
+ "scheduledMessages.alreadySent.text": "Already sent. It's in the channel now.",
+ "scheduledMessages.banner.count.text": "{{ count }} scheduled messages",
+ "scheduledMessages.banner.failed.text": "{{ count }} failed to send",
+ "scheduledMessages.banner.limit.text": "{{ count }} of {{ max }} scheduled messages",
+ "scheduledMessages.banner.single.text": "Scheduled for {{ time }}",
+ "scheduledMessages.channelLimit.error": "You've reached the limit of scheduled messages in this channel.",
+ "scheduledMessages.commandBlocked.error": "Commands can't be scheduled. Remove the / command to continue.",
+ "scheduledMessages.confirm.accessibilityLabel": "Schedule",
+ "scheduledMessages.copyText.label": "Copy text",
+ "scheduledMessages.customTime.label": "Custom time",
+ "scheduledMessages.date.label": "Date",
+ "scheduledMessages.dateTime.label": "{{ day }} at {{ time }}",
+ "scheduledMessages.delete.label": "Delete",
+ "scheduledMessages.deleteConfirm.text": "This message won't be sent. This can't be undone.",
+ "scheduledMessages.deleteConfirm.title": "Delete scheduled message?",
+ "scheduledMessages.deleteConfirm.withName.text": "This message to {{ name }} won't be sent. This can't be undone.",
+ "scheduledMessages.deleteFailed.error": "Couldn't delete the scheduled message. Try again",
+ "scheduledMessages.disabled.error": "Scheduled messages are turned off",
+ "scheduledMessages.editMessage.label": "Edit message",
+ "scheduledMessages.editScheduledMessage.label": "Edit scheduled message",
+ "scheduledMessages.empty.description": "Long press the send button in a channel to schedule a message.",
+ "scheduledMessages.empty.title": "No scheduled messages",
+ "scheduledMessages.failure.banned.text": "You can't send messages in this channel.",
+ "scheduledMessages.failure.channelDeleted.text": "This channel was deleted",
+ "scheduledMessages.failure.channelFrozen.text": "This channel is frozen.",
+ "scheduledMessages.failure.default.text": "Couldn't send. Try again",
+ "scheduledMessages.failure.expired.text": "Not sent: the service was delayed.",
+ "scheduledMessages.failure.hookRejected.text": "Rejected by the app.",
+ "scheduledMessages.failure.internalError.text": "Something went wrong. Try again",
+ "scheduledMessages.failure.invalidMessage.text": "The message no longer meets the app's limits. Edit it.",
+ "scheduledMessages.failure.moderationBlocked.text": "Blocked by moderation.",
+ "scheduledMessages.failure.noPermission.text": "You're no longer allowed to post here.",
+ "scheduledMessages.failure.pendingNotSupported.text": "This channel now needs approval. Schedule it again.",
+ "scheduledMessages.forbidden.error": "You can't schedule messages here",
+ "scheduledMessages.limitReached.title": "Limit reached ({{ count }} max)",
+ "scheduledMessages.loadFailed.error": "Couldn't load scheduled messages",
+ "scheduledMessages.message.title": "Scheduled message",
+ "scheduledMessages.messageTo.title": "Message to {{ name }}",
+ "scheduledMessages.pickerConfirm.label": "Confirm",
+ "scheduledMessages.preset.tomorrow.label": "Tomorrow at {{ time }}",
+ "scheduledMessages.preset.weekday.label": "{{ day }} at {{ time }}",
+ "scheduledMessages.quoteDeleted.text": "The quoted message was deleted. Edit it to remove the quote.",
+ "scheduledMessages.quoteDeleted.title": "The quoted message was deleted",
+ "scheduledMessages.removeQuote.label": "Remove quote",
+ "scheduledMessages.reply.prefix": "Reply:",
+ "scheduledMessages.replyTo.prefix": "Reply to {{ name }}:",
+ "scheduledMessages.reschedule.label": "Reschedule",
+ "scheduledMessages.rescheduleFailed.error": "Couldn't reschedule the message. Try again",
+ "scheduledMessages.rescheduleMessage.title": "Reschedule message",
+ "scheduledMessages.rescheduleTooSoon.error": "Pick a later time. Editing can't send a message right away.",
+ "scheduledMessages.scheduleFailed.error": "Couldn't schedule message. Try again",
+ "scheduledMessages.scheduleMessage.title": "Schedule message",
+ "scheduledMessages.search.accessibilityLabel": "Search scheduled messages",
+ "scheduledMessages.sendNow.label": "Send now",
+ "scheduledMessages.sendNowFailed.error": "Couldn't send the message. Try again",
+ "scheduledMessages.sendTime.label": "Send {{ time }}",
+ "scheduledMessages.sending.label": "Sending…",
+ "scheduledMessages.sentNow.text": "Scheduled message sent",
+ "scheduledMessages.stillSending.text": "Still sending. Try again in a moment.",
+ "scheduledMessages.threadReply.prefix": "Thread reply:",
+ "scheduledMessages.time.label": "Time",
+ "scheduledMessages.timeZone.text": "Sent in your time zone ({{ timeZone }})",
+ "scheduledMessages.tooFar.error": "That's further ahead than your app allows",
+ "scheduledMessages.tooSoon.error": "Pick a time at least 1 minute from now",
+ "scheduledMessages.tryAgain.label": "Try again",
+ "scheduledMessages.updateFailed.error": "Couldn't update the scheduled message. Try again",
+ "scheduledMessages.uploading.label": "Uploading…",
+ "scheduledMessages.usage.text": "{{ count }} of {{ max }} scheduled in this channel",
+ "scheduledMessages.userLimit.error": "You've reached your limit of scheduled messages.",
+ "scheduledMessages.userLimitCount.error": "You've reached your limit of {{ count }} scheduled messages.",
+ "scheduledMessages.view.label": "View",
+ "scheduledMessages.viewAll.label": "View all",
"threadList.unreadBanner.loadFailed.error": "Couldn't load new threads. Tap to retry",
"threadList.unreadBanner.newThreads.label_one": "{{count}} new thread",
"threadList.unreadBanner.newThreads.label_other": "{{count}} new threads",
@@ -477,6 +553,9 @@
"timestamp.MessageSystem": "{{ timestamp | timestampFormatter(calendar: true) }}",
"timestamp.MessageTimestamp": "{{ timestamp | timestampFormatter(format: LT) }}",
"timestamp.PollVote": "{{ timestamp | timestampFormatter(relativeCompact: true) }}",
+ "timestamp.ScheduledMessageDate": "{{ timestamp | timestampFormatter(format: ddd, MMM D) }}",
+ "timestamp.ScheduledMessageTime": "{{ timestamp | timestampFormatter(format: HH:mm) }}",
+ "timestamp.ScheduledMessageWeekday": "{{ timestamp | timestampFormatter(format: dddd) }}",
"timestamp.StickyHeader": "{{ timestamp | timestampFormatter(calendar: true) }}",
"timestamp.ThreadListItem": "{{ timestamp | timestampFormatter(calendar: true; calendarFormats: {\"lastDay\":\"[Yesterday]\", \"lastWeek\":\"dddd\", \"nextDay\":\"[Tomorrow]\", \"nextWeek\":\"dddd [at] LT\", \"sameDay\":\"LT\", \"sameElse\":\"L\"}) }}",
"timestamp.UserActivityStatus": "Last seen {{ timestamp | fromNowFormatter }}",
diff --git a/package/src/i18n/keys.ts b/package/src/i18n/keys.ts
index 90db0072c9..e72eca9ed3 100644
--- a/package/src/i18n/keys.ts
+++ b/package/src/i18n/keys.ts
@@ -214,6 +214,7 @@ export type TranslationCatalog = {
'channelDetails.navigation.files.label': 'Files';
'channelDetails.navigation.photosAndVideos.label': 'Photos & Videos';
'channelDetails.navigation.pinnedMessages.label': 'Pinned Messages';
+ 'channelDetails.navigation.scheduledMessages.label': 'Scheduled Messages';
'channelDetails.pinnedMessageList.empty.description': 'Long-press a message to pin it to the chat';
'channelDetails.pinnedMessageList.empty.title': 'No pinned messages';
'channelDetails.pinnedMessageList.load.error': 'Failed to load pinned messages';
@@ -420,10 +421,12 @@ export type TranslationCatalog = {
'notifications.pollEndFailed.withReason.error': 'Failed to end the poll due to {{reason}}';
'notifications.pollEnded.text': 'Poll ended';
'notifications.recordingPlaybackFailed.error': 'Error reproducing the recording';
+ 'notifications.scheduledMessageBlocked.command.error': "Commands can't be scheduled";
'notifications.scheduledMessageBlocked.error': 'This message cannot be scheduled';
+ 'notifications.scheduledMessageCompositionEnded.deleted.error': 'This scheduled message was deleted';
'notifications.scheduledMessageCompositionEnded.error': 'The scheduled message can no longer be edited';
- 'notifications.scheduledMessageCreateFailed.error': 'Failed to schedule the message';
- 'notifications.scheduledMessageUpdateFailed.error': 'Failed to update the scheduled message';
+ 'notifications.scheduledMessageCompositionEnded.failed.error': 'This scheduled message failed to send';
+ 'notifications.scheduledMessageCompositionEnded.sent.error': 'This message was already sent';
'notifications.voteLimitReached.error': 'Reached the vote limit. Remove an existing vote first.';
'poll.addComment.description': 'Add a comment to the poll';
'poll.addComment.label': 'Add a comment';
@@ -478,6 +481,79 @@ export type TranslationCatalog = {
'reply.replyTo.title': 'Reply to {{name}}';
'reply.replying.withUser.accessibilityLabel': 'Replying to {{user}}';
'reply.replying.withUserAndText.accessibilityLabel': 'Replying to {{user}}: {{text}}';
+ 'scheduledMessages.alreadySent.error': 'This message was already sent';
+ 'scheduledMessages.alreadySent.text': "Already sent. It's in the channel now.";
+ 'scheduledMessages.banner.count.text': '{{ count }} scheduled messages';
+ 'scheduledMessages.banner.failed.text': '{{ count }} failed to send';
+ 'scheduledMessages.banner.limit.text': '{{ count }} of {{ max }} scheduled messages';
+ 'scheduledMessages.banner.single.text': 'Scheduled for {{ time }}';
+ 'scheduledMessages.channelLimit.error': "You've reached the limit of scheduled messages in this channel.";
+ 'scheduledMessages.commandBlocked.error': "Commands can't be scheduled. Remove the / command to continue.";
+ 'scheduledMessages.confirm.accessibilityLabel': 'Schedule';
+ 'scheduledMessages.copyText.label': 'Copy text';
+ 'scheduledMessages.customTime.label': 'Custom time';
+ 'scheduledMessages.date.label': 'Date';
+ 'scheduledMessages.dateTime.label': '{{ day }} at {{ time }}';
+ 'scheduledMessages.delete.label': 'Delete';
+ 'scheduledMessages.deleteConfirm.text': "This message won't be sent. This can't be undone.";
+ 'scheduledMessages.deleteConfirm.title': 'Delete scheduled message?';
+ 'scheduledMessages.deleteConfirm.withName.text': "This message to {{ name }} won't be sent. This can't be undone.";
+ 'scheduledMessages.deleteFailed.error': "Couldn't delete the scheduled message. Try again";
+ 'scheduledMessages.disabled.error': 'Scheduled messages are turned off';
+ 'scheduledMessages.editMessage.label': 'Edit message';
+ 'scheduledMessages.editScheduledMessage.label': 'Edit scheduled message';
+ 'scheduledMessages.empty.description': 'Long press the send button in a channel to schedule a message.';
+ 'scheduledMessages.empty.title': 'No scheduled messages';
+ 'scheduledMessages.failure.banned.text': "You can't send messages in this channel.";
+ 'scheduledMessages.failure.channelDeleted.text': 'This channel was deleted';
+ 'scheduledMessages.failure.channelFrozen.text': 'This channel is frozen.';
+ 'scheduledMessages.failure.default.text': "Couldn't send. Try again";
+ 'scheduledMessages.failure.expired.text': 'Not sent: the service was delayed.';
+ 'scheduledMessages.failure.hookRejected.text': 'Rejected by the app.';
+ 'scheduledMessages.failure.internalError.text': 'Something went wrong. Try again';
+ 'scheduledMessages.failure.invalidMessage.text': "The message no longer meets the app's limits. Edit it.";
+ 'scheduledMessages.failure.moderationBlocked.text': 'Blocked by moderation.';
+ 'scheduledMessages.failure.noPermission.text': "You're no longer allowed to post here.";
+ 'scheduledMessages.failure.pendingNotSupported.text': 'This channel now needs approval. Schedule it again.';
+ 'scheduledMessages.forbidden.error': "You can't schedule messages here";
+ 'scheduledMessages.limitReached.title': 'Limit reached ({{ count }} max)';
+ 'scheduledMessages.loadFailed.error': "Couldn't load scheduled messages";
+ 'scheduledMessages.message.title': 'Scheduled message';
+ 'scheduledMessages.messageTo.title': 'Message to {{ name }}';
+ 'scheduledMessages.pickerConfirm.label': 'Confirm';
+ 'scheduledMessages.preset.tomorrow.label': 'Tomorrow at {{ time }}';
+ 'scheduledMessages.preset.weekday.label': '{{ day }} at {{ time }}';
+ 'scheduledMessages.quoteDeleted.text': 'The quoted message was deleted. Edit it to remove the quote.';
+ 'scheduledMessages.quoteDeleted.title': 'The quoted message was deleted';
+ 'scheduledMessages.removeQuote.label': 'Remove quote';
+ 'scheduledMessages.reply.prefix': 'Reply:';
+ 'scheduledMessages.replyTo.prefix': 'Reply to {{ name }}:';
+ 'scheduledMessages.reschedule.label': 'Reschedule';
+ 'scheduledMessages.rescheduleFailed.error': "Couldn't reschedule the message. Try again";
+ 'scheduledMessages.rescheduleMessage.title': 'Reschedule message';
+ 'scheduledMessages.rescheduleTooSoon.error': "Pick a later time. Editing can't send a message right away.";
+ 'scheduledMessages.scheduleFailed.error': "Couldn't schedule message. Try again";
+ 'scheduledMessages.scheduleMessage.title': 'Schedule message';
+ 'scheduledMessages.search.accessibilityLabel': 'Search scheduled messages';
+ 'scheduledMessages.sendNow.label': 'Send now';
+ 'scheduledMessages.sendNowFailed.error': "Couldn't send the message. Try again";
+ 'scheduledMessages.sendTime.label': 'Send {{ time }}';
+ 'scheduledMessages.sending.label': 'Sending…';
+ 'scheduledMessages.sentNow.text': 'Scheduled message sent';
+ 'scheduledMessages.stillSending.text': 'Still sending. Try again in a moment.';
+ 'scheduledMessages.threadReply.prefix': 'Thread reply:';
+ 'scheduledMessages.time.label': 'Time';
+ 'scheduledMessages.timeZone.text': 'Sent in your time zone ({{ timeZone }})';
+ 'scheduledMessages.tooFar.error': "That's further ahead than your app allows";
+ 'scheduledMessages.tooSoon.error': 'Pick a time at least 1 minute from now';
+ 'scheduledMessages.tryAgain.label': 'Try again';
+ 'scheduledMessages.updateFailed.error': "Couldn't update the scheduled message. Try again";
+ 'scheduledMessages.uploading.label': 'Uploading…';
+ 'scheduledMessages.usage.text': '{{ count }} of {{ max }} scheduled in this channel';
+ 'scheduledMessages.userLimit.error': "You've reached your limit of scheduled messages.";
+ 'scheduledMessages.userLimitCount.error': "You've reached your limit of {{ count }} scheduled messages.";
+ 'scheduledMessages.view.label': 'View';
+ 'scheduledMessages.viewAll.label': 'View all';
'threadList.unreadBanner.loadFailed.error': "Couldn't load new threads. Tap to retry";
'threadList.unreadBanner.newThreads.label_one': '{{count}} new thread';
'threadList.unreadBanner.newThreads.label_other': '{{count}} new threads';
@@ -488,6 +564,9 @@ export type TranslationCatalog = {
'timestamp.MessageSystem': '{{ timestamp | timestampFormatter(calendar: true) }}';
'timestamp.MessageTimestamp': '{{ timestamp | timestampFormatter(format: LT) }}';
'timestamp.PollVote': '{{ timestamp | timestampFormatter(relativeCompact: true) }}';
+ 'timestamp.ScheduledMessageDate': '{{ timestamp | timestampFormatter(format: ddd, MMM D) }}';
+ 'timestamp.ScheduledMessageTime': '{{ timestamp | timestampFormatter(format: HH:mm) }}';
+ 'timestamp.ScheduledMessageWeekday': '{{ timestamp | timestampFormatter(format: dddd) }}';
'timestamp.StickyHeader': '{{ timestamp | timestampFormatter(calendar: true) }}';
'timestamp.ThreadListItem': '{{ timestamp | timestampFormatter(calendar: true; calendarFormats: {"lastDay":"[Yesterday]", "lastWeek":"dddd", "nextDay":"[Tomorrow]", "nextWeek":"dddd [at] LT", "sameDay":"LT", "sameElse":"L"}) }}';
'timestamp.UserActivityStatus': 'Last seen {{ timestamp | fromNowFormatter }}';
@@ -531,6 +610,7 @@ export type BundledTranslationKey =
| 'channelDetails.navigation.files.label'
| 'channelDetails.navigation.photosAndVideos.label'
| 'channelDetails.navigation.pinnedMessages.label'
+ | 'channelDetails.navigation.scheduledMessages.label'
| 'channelPreview.deliveryStatus.delivered.accessibilityLabel'
| 'channelPreview.deliveryStatus.read.accessibilityLabel'
| 'channelPreview.deliveryStatus.sent.accessibilityLabel'
@@ -581,6 +661,7 @@ export type BundledTranslationKey =
| 'poll.modalHeader.close.accessibilityLabel'
| 'reply.removeEdit.accessibilityLabel'
| 'reply.removeReply.accessibilityLabel'
+ | 'scheduledMessages.confirm.accessibilityLabel'
| 'timestamp.ChannelPreviewStatus'
| 'timestamp.FileAttachmentListSection'
| 'timestamp.ImageGalleryHeader'
@@ -588,6 +669,9 @@ export type BundledTranslationKey =
| 'timestamp.MessageSystem'
| 'timestamp.MessageTimestamp'
| 'timestamp.PollVote'
+ | 'timestamp.ScheduledMessageDate'
+ | 'timestamp.ScheduledMessageTime'
+ | 'timestamp.ScheduledMessageWeekday'
| 'timestamp.StickyHeader'
| 'timestamp.ThreadListItem'
| 'timestamp.UserActivityStatus'
diff --git a/package/src/i18n/runtimeDefaults.ts b/package/src/i18n/runtimeDefaults.ts
index ccf1b7cb69..088f69885c 100644
--- a/package/src/i18n/runtimeDefaults.ts
+++ b/package/src/i18n/runtimeDefaults.ts
@@ -39,6 +39,9 @@ export const runtimeDefaults = {
'timestamp.MessageSystem': '{{ timestamp | timestampFormatter(calendar: true) }}',
'timestamp.MessageTimestamp': '{{ timestamp | timestampFormatter(format: LT) }}',
'timestamp.PollVote': '{{ timestamp | timestampFormatter(relativeCompact: true) }}',
+ 'timestamp.ScheduledMessageDate': '{{ timestamp | timestampFormatter(format: ddd, MMM D) }}',
+ 'timestamp.ScheduledMessageTime': '{{ timestamp | timestampFormatter(format: HH:mm) }}',
+ 'timestamp.ScheduledMessageWeekday': '{{ timestamp | timestampFormatter(format: dddd) }}',
'timestamp.StickyHeader': '{{ timestamp | timestampFormatter(calendar: true) }}',
'timestamp.ThreadListItem':
'{{ timestamp | timestampFormatter(calendar: true; calendarFormats: {"lastDay":"[Yesterday]", "lastWeek":"dddd", "nextDay":"[Tomorrow]", "nextWeek":"dddd [at] LT", "sameDay":"LT", "sameElse":"L"}) }}',
@@ -79,6 +82,7 @@ export const runtimeDefaults = {
'channelDetails.navigation.files.label': 'Files',
'channelDetails.navigation.photosAndVideos.label': 'Photos & Videos',
'channelDetails.navigation.pinnedMessages.label': 'Pinned Messages',
+ 'channelDetails.navigation.scheduledMessages.label': 'Scheduled Messages',
'channelPreview.deliveryStatus.delivered.accessibilityLabel': 'Delivered, sent by you',
'channelPreview.deliveryStatus.read.accessibilityLabel': 'Read, sent by you',
'channelPreview.deliveryStatus.sent.accessibilityLabel': 'Sent by you',
@@ -143,6 +147,7 @@ export const runtimeDefaults = {
'poll.modalHeader.close.accessibilityLabel': 'Close poll',
'reply.removeEdit.accessibilityLabel': 'Remove edit',
'reply.removeReply.accessibilityLabel': 'Remove reply',
+ 'scheduledMessages.confirm.accessibilityLabel': 'Schedule',
'uiComponents.bottomSheetModal.opened.accessibilityLabel':
'Bottom sheet opened. Activate the close action or use the escape gesture to dismiss.',
};
diff --git a/package/src/icons/calendar.tsx b/package/src/icons/calendar.tsx
new file mode 100644
index 0000000000..619775e737
--- /dev/null
+++ b/package/src/icons/calendar.tsx
@@ -0,0 +1,22 @@
+import React from 'react';
+
+import Svg, { Path } from 'react-native-svg';
+
+import { IconProps } from './utils/base';
+
+export const Calendar = ({ fill, height, pathFill, size, stroke, width, ...rest }: IconProps) => {
+ const color = stroke ?? pathFill ?? fill ?? 'black';
+
+ return (
+
+ );
+};
diff --git a/package/src/icons/exclamation-circle.tsx b/package/src/icons/exclamation-circle.tsx
new file mode 100644
index 0000000000..3ac9b41218
--- /dev/null
+++ b/package/src/icons/exclamation-circle.tsx
@@ -0,0 +1,34 @@
+import React from 'react';
+
+import { Path, Svg } from 'react-native-svg';
+
+import { IconProps } from './utils/base';
+
+export const ExclamationCircleOutline = ({
+ fill,
+ height,
+ pathFill,
+ size,
+ stroke,
+ width,
+ ...rest
+}: IconProps) => {
+ const color = fill ?? stroke ?? pathFill ?? 'black';
+
+ return (
+
+ );
+};
diff --git a/package/src/icons/index.ts b/package/src/icons/index.ts
index f44e8512e6..660c706852 100644
--- a/package/src/icons/index.ts
+++ b/package/src/icons/index.ts
@@ -3,6 +3,7 @@ export * from './utils/base';
export * from './filetype-audio-xl';
export * from './archive';
export * from './no-sign';
+export * from './calendar';
export * from './camera';
export { Check } from './checkmark';
export * from './checks';
diff --git a/package/src/index.ts b/package/src/index.ts
index 427b5b9788..6512c56e88 100644
--- a/package/src/index.ts
+++ b/package/src/index.ts
@@ -5,6 +5,8 @@ import './polyfills';
export * from './components';
export * from './hooks';
export {
+ PickDateTime,
+ PickDateTimeOptions,
PickImageOptions,
PlaybackStatus,
RecordingStatus,
diff --git a/package/src/native.ts b/package/src/native.ts
index 1398f95240..8fd0228d40 100644
--- a/package/src/native.ts
+++ b/package/src/native.ts
@@ -343,6 +343,25 @@ export type NativePerfTextProps = ViewProps & {
lineHeight?: number;
};
+export type PickDateTimeOptions = {
+ mode: 'date' | 'time';
+ /** The initial value. Selecting a date preserves its time of day, and the reverse. */
+ value: Date;
+ minimumDate?: Date;
+ maximumDate?: Date;
+ /** Translated labels for the dialog buttons, used on iOS. The Android dialogs provide their own. */
+ confirmLabel: string;
+ cancelLabel: string;
+ /** Aborting the signal closes the picker and resolves the call with `null`. */
+ signal?: AbortSignal;
+};
+
+/**
+ * Opens the system date or time picker, a Material dialog on Android and a `UIDatePicker` dialog on
+ * iOS. Resolves with the selected moment, or `null` when the picker is cancelled.
+ */
+export type PickDateTime = (options: PickDateTimeOptions) => Promise;
+
type Handlers = {
Audio?: AudioType;
compressImage?: CompressImage;
@@ -356,6 +375,7 @@ type Handlers = {
overrideAudioRecordingConfiguration?: (
audioRecordingConfiguration: AudioRecordingConfiguration,
) => AudioRecordingConfiguration;
+ pickDateTime?: PickDateTime;
pickDocument?: PickDocument;
pickImage?: PickImage;
saveFile?: SaveFile;
@@ -372,7 +392,7 @@ type Handlers = {
export const NativeHandlers: Pick<
Handlers,
- 'Audio' | 'FlatList' | 'NativeShimmerView' | 'PerfText' | 'Video' | 'Sound'
+ 'Audio' | 'FlatList' | 'NativeShimmerView' | 'PerfText' | 'pickDateTime' | 'Video' | 'Sound'
> &
Required<
Pick<
@@ -403,6 +423,7 @@ export const NativeHandlers: Pick<
iOS14RefreshGallerySelection: fail,
multipartUpload: fail,
oniOS14GalleryLibrarySelectionChange: fail,
+ pickDateTime: undefined,
pickDocument: fail,
pickImage: fail,
saveFile: fail,
@@ -461,6 +482,10 @@ export const registerNativeHandlers = (handlers: Handlers) => {
handlers.oniOS14GalleryLibrarySelectionChange;
}
+ if (handlers.pickDateTime !== undefined) {
+ NativeHandlers.pickDateTime = handlers.pickDateTime;
+ }
+
if (handlers.pickDocument !== undefined) {
NativeHandlers.pickDocument = handlers.pickDocument;
}
diff --git a/package/src/state-store/message-input-height-store.ts b/package/src/state-store/message-input-height-store.ts
index 55470d2261..fd9ce16bbd 100644
--- a/package/src/state-store/message-input-height-store.ts
+++ b/package/src/state-store/message-input-height-store.ts
@@ -2,9 +2,12 @@ import { StateStore } from '@stream-io/state-store';
export type MessageInputHeightState = {
height: number;
+ /** Height of the banner floating above the composer, including its gap, or 0 when hidden. */
+ bannerHeight: number;
};
const INITIAL_STATE: MessageInputHeightState = {
+ bannerHeight: 0,
height: 0,
};
@@ -12,10 +15,14 @@ export class MessageInputHeightStore {
public store = new StateStore(INITIAL_STATE);
constructor() {
- this.store.next({ height: 0 });
+ this.store.next(INITIAL_STATE);
}
setHeight(height: number) {
- this.store.next({ height });
+ this.store.partialNext({ height });
+ }
+
+ setBannerHeight(bannerHeight: number) {
+ this.store.partialNext({ bannerHeight });
}
}
diff --git a/package/src/store/OfflineDB.ts b/package/src/store/OfflineDB.ts
index fddfb93e9f..9e3784ba68 100644
--- a/package/src/store/OfflineDB.ts
+++ b/package/src/store/OfflineDB.ts
@@ -78,6 +78,12 @@ export class OfflineDB extends AbstractOfflineDB {
getReactions = api.getReactionsForFilterSort;
+ upsertScheduledMessages = api.upsertScheduledMessages;
+
+ getScheduledMessages = api.getScheduledMessages;
+
+ deleteScheduledMessages = api.deleteScheduledMessages;
+
getMessageMarks = api.getMessageMarks;
addPendingTask = api.addPendingTask;
diff --git a/package/src/store/SqliteClient.ts b/package/src/store/SqliteClient.ts
index db55054da8..d7c93d87c2 100644
--- a/package/src/store/SqliteClient.ts
+++ b/package/src/store/SqliteClient.ts
@@ -44,7 +44,7 @@ export class SqliteClientError extends Error {
/** Wraps all direct use of `@op-engineering/op-sqlite`. */
export class SqliteClient {
- static dbVersion = 20;
+ static dbVersion = 21;
static dbName = DB_NAME;
static dbLocation = DB_LOCATION;
diff --git a/package/src/store/__tests__/scheduledMessages.test.ts b/package/src/store/__tests__/scheduledMessages.test.ts
new file mode 100644
index 0000000000..86b38336c6
--- /dev/null
+++ b/package/src/store/__tests__/scheduledMessages.test.ts
@@ -0,0 +1,195 @@
+import type { ScheduledMessageResponse, TimestampNS } from 'stream-chat';
+
+import { generateChannelResponse } from '../../mock-builders/generator/channel';
+import { generateMessage } from '../../mock-builders/generator/message';
+import { generateUser } from '../../mock-builders/generator/user';
+import { BetterSqlite } from '../../test-utils/BetterSqlite';
+import { deleteMessagesForChannel } from '../apis/deleteMessagesForChannel';
+import { deleteScheduledMessages } from '../apis/deleteScheduledMessages';
+import { getChannelMessages } from '../apis/getChannelMessages';
+import { getChannels } from '../apis/getChannels';
+import { getScheduledMessages } from '../apis/getScheduledMessages';
+import { selectMessageForId } from '../apis/queries/selectMessageById';
+import { upsertChannels } from '../apis/upsertChannels';
+import { upsertMessages } from '../apis/upsertMessages';
+import { upsertScheduledMessages } from '../apis/upsertScheduledMessages';
+import { SqliteClient } from '../SqliteClient';
+
+/** Runs against real SQLite: a scheduled message hangs off its message, which hangs off its channel. */
+describe('scheduled messages', () => {
+ const cid = 'messaging:scheduled';
+ const otherCid = 'messaging:other';
+ const ava = generateUser({ id: 'ava', name: 'Ava' });
+
+ const scheduledMessage = (
+ data: Partial = {},
+ ): ScheduledMessageResponse => ({
+ cid,
+ created_at: 100 as TimestampNS,
+ id: 'sm-1',
+ message: { custom: {}, text: 'see you tomorrow' },
+ scheduled_at: 5000 as TimestampNS,
+ status: 'scheduled',
+ updated_at: 200 as TimestampNS,
+ user: ava,
+ ...data,
+ });
+
+ const storeChannels = async (...cids: string[]) => {
+ const channels = cids.map((channelCid) => {
+ const channelResponse = generateChannelResponse({ members: [], messages: [] });
+ channelResponse.channel.cid = channelCid;
+ return channelResponse;
+ });
+ await upsertChannels({
+ channels: channels as unknown as Parameters[0]['channels'],
+ });
+ };
+
+ beforeEach(async () => {
+ await SqliteClient.initializeDatabase();
+ await BetterSqlite.openDB();
+ await storeChannels(cid);
+ });
+
+ afterEach(() => {
+ BetterSqlite.dropAllTables();
+ BetterSqlite.closeDB();
+ });
+
+ it('reads back a scheduled message as it was stored', async () => {
+ const stored = scheduledMessage({
+ channel: { cid, id: 'scheduled', name: 'Planning', type: 'messaging' },
+ failure_reason: 'channel_frozen',
+ message: {
+ attachments: [{ image_url: 'https://example.com/a.png', type: 'image' }],
+ custom: { mood: 'sunny' },
+ mentioned_users: ['ben'],
+ parent_id: 'parent-1',
+ quoted_message_id: 'quoted-1',
+ shared_location: {
+ created_by_device_id: 'device-1',
+ end_at: 9000 as TimestampNS,
+ latitude: 1.5,
+ longitude: 2.5,
+ },
+ text: 'see you tomorrow',
+ type: 'reply',
+ },
+ status: 'failed',
+ });
+
+ await upsertScheduledMessages({ scheduledMessages: [stored] });
+
+ expect(await getScheduledMessages({})).toEqual([
+ { ...stored, user: expect.objectContaining({ id: 'ava', name: 'Ava' }) },
+ ]);
+ });
+
+ it('reads earliest first, by channel and status, up to the limit', async () => {
+ await storeChannels(otherCid);
+ await upsertScheduledMessages({
+ scheduledMessages: [
+ scheduledMessage({ id: 'late', scheduled_at: 3000 as TimestampNS }),
+ scheduledMessage({ id: 'early', scheduled_at: 1000 as TimestampNS }),
+ scheduledMessage({ id: 'failed', scheduled_at: 2000 as TimestampNS, status: 'failed' }),
+ scheduledMessage({ cid: otherCid, id: 'elsewhere', scheduled_at: 500 as TimestampNS }),
+ ],
+ });
+
+ const ids = (messages: ScheduledMessageResponse[]) => messages.map(({ id }) => id);
+
+ expect(ids(await getScheduledMessages({}))).toEqual(['elsewhere', 'early', 'failed', 'late']);
+ expect(ids(await getScheduledMessages({ cid }))).toEqual(['early', 'failed', 'late']);
+ expect(ids(await getScheduledMessages({ statuses: ['failed'] }))).toEqual(['failed']);
+ expect(ids(await getScheduledMessages({ cid, limit: 2 }))).toEqual(['early', 'failed']);
+ });
+
+ it('skips one whose channel is not stored, and stores the rest', async () => {
+ await upsertScheduledMessages({
+ scheduledMessages: [
+ scheduledMessage({ cid: otherCid, id: 'unknown-channel' }),
+ scheduledMessage({ id: 'known-channel' }),
+ ],
+ });
+
+ expect((await getScheduledMessages({})).map(({ id }) => id)).toEqual(['known-channel']);
+ });
+
+ it('updates the status and clears the failure reason', async () => {
+ await upsertScheduledMessages({
+ scheduledMessages: [scheduledMessage({ failure_reason: 'banned', status: 'failed' })],
+ });
+
+ await upsertScheduledMessages({
+ scheduledMessages: [scheduledMessage({ status: 'sending' })],
+ });
+
+ const [stored] = await getScheduledMessages({});
+ expect(stored.status).toBe('sending');
+ expect(stored).not.toHaveProperty('failure_reason');
+ });
+
+ it("returns each channel's scheduled messages with the channel", async () => {
+ await storeChannels(otherCid);
+ await upsertScheduledMessages({
+ scheduledMessages: [
+ scheduledMessage({ id: 'here' }),
+ scheduledMessage({ cid: otherCid, id: 'elsewhere' }),
+ ],
+ });
+
+ const channels = await getChannels({ channelIds: [cid, otherCid], userId: 'ava' });
+ const byCid = Object.fromEntries(
+ channels.map(({ channel, scheduled_messages }) => [
+ channel?.cid,
+ scheduled_messages?.map(({ id }) => id),
+ ]),
+ );
+
+ expect(byCid).toEqual({ [cid]: ['here'], [otherCid]: ['elsewhere'] });
+ });
+
+ it("leaves scheduled messages out of the channel's messages", async () => {
+ await upsertMessages({ messages: [generateMessage({ cid, id: 'sent', user: ava })] });
+ await upsertScheduledMessages({ scheduledMessages: [scheduledMessage()] });
+
+ const { [cid]: messages } = await getChannelMessages({ channelIds: [cid], userId: 'ava' });
+
+ expect(messages.map(({ id }) => id)).toEqual(['sent']);
+ expect(messages[0]).not.toHaveProperty('scheduledAt');
+ expect(await selectMessageForId('sm-1')).toBeUndefined();
+ });
+
+ it('keeps scheduled messages when the channel is truncated', async () => {
+ await upsertMessages({
+ messages: [generateMessage({ cid, id: 'sent', timestamp: new Date(1000) })],
+ });
+ await upsertScheduledMessages({ scheduledMessages: [scheduledMessage()] });
+
+ await deleteMessagesForChannel({ cid });
+
+ expect((await getScheduledMessages({})).map(({ id }) => id)).toEqual(['sm-1']);
+ const { [cid]: messages = [] } = await getChannelMessages({
+ channelIds: [cid],
+ userId: 'ava',
+ });
+ expect(messages).toEqual([]);
+ });
+
+ it('deletes scheduled messages with their messages, and never a sent message', async () => {
+ await upsertMessages({ messages: [generateMessage({ cid, id: 'sent', user: ava })] });
+ await upsertScheduledMessages({
+ scheduledMessages: [scheduledMessage({ id: 'a' }), scheduledMessage({ id: 'b' })],
+ });
+
+ await deleteScheduledMessages({ ids: ['a', 'sent'] });
+
+ expect((await getScheduledMessages({})).map(({ id }) => id)).toEqual(['b']);
+ expect(
+ await BetterSqlite.selectFromTable('messages').then((rows) =>
+ rows.map(({ id }: { id: string }) => id).sort(),
+ ),
+ ).toEqual(['b', 'sent']);
+ });
+});
diff --git a/package/src/store/apis/deleteMessagesForChannel.ts b/package/src/store/apis/deleteMessagesForChannel.ts
index 7c4c3235f4..e167d0a5af 100644
--- a/package/src/store/apis/deleteMessagesForChannel.ts
+++ b/package/src/store/apis/deleteMessagesForChannel.ts
@@ -14,9 +14,10 @@ export const deleteMessagesForChannel = async ({
execute?: boolean;
}) => {
// `createdAt` holds unix nanoseconds, so the cutoff is one too and the comparison is numeric.
+ // Truncating a channel leaves its scheduled messages scheduled.
const timestamp = truncated_at ?? nowNs();
const query: [string, (string | number)[]] = [
- `DELETE FROM messages WHERE cid = ? AND createdAt <= ?`,
+ `DELETE FROM messages WHERE cid = ? AND createdAt <= ? AND scheduledAt IS NULL`,
[cid, timestamp],
];
diff --git a/package/src/store/apis/deleteScheduledMessages.ts b/package/src/store/apis/deleteScheduledMessages.ts
new file mode 100644
index 0000000000..e9514c2daa
--- /dev/null
+++ b/package/src/store/apis/deleteScheduledMessages.ts
@@ -0,0 +1,27 @@
+import type { DBDeleteScheduledMessagesType } from 'stream-chat';
+
+import { createDeleteQuery } from '../sqlite-utils/createDeleteQuery';
+import { SqliteClient } from '../SqliteClient';
+import type { PreparedQueries } from '../types';
+
+/** Deletes scheduled messages with their messages. A message no scheduled message owns stays. */
+export const deleteScheduledMessages = async ({
+ execute = true,
+ ids,
+}: DBDeleteScheduledMessagesType) => {
+ if (!ids.length) return [];
+
+ const questionMarks = Array(ids.length).fill('?').join(',');
+ const queries: PreparedQueries[] = [
+ createDeleteQuery('scheduledMessages', { id: ids }),
+ [`DELETE FROM messages WHERE id in (${questionMarks}) AND scheduledAt IS NOT NULL`, ids],
+ ];
+
+ SqliteClient.logger?.('info', 'deleteScheduledMessages', { execute, ids });
+
+ if (execute) {
+ await SqliteClient.executeSqlBatch(queries);
+ }
+
+ return queries;
+};
diff --git a/package/src/store/apis/getChannels.ts b/package/src/store/apis/getChannels.ts
index cb1b2c131c..e2c9c68fa1 100644
--- a/package/src/store/apis/getChannels.ts
+++ b/package/src/store/apis/getChannels.ts
@@ -5,14 +5,15 @@ import { getChannelMessages } from './getChannelMessages';
import { getDraftForChannels } from './getDraftsForChannels';
import { getMembers } from './getMembers';
import { getReads } from './getReads';
+import { getScheduledMessages } from './getScheduledMessages';
import { selectChannels } from './queries/selectChannels';
import { mapStorableToChannel } from '../mappers/mapStorableToChannel';
import { SqliteClient } from '../SqliteClient';
/**
- * Returns the channels with the given IDs, including their members, reads, messages, draft and
- * active live locations.
+ * Returns the channels with the given IDs, including their members, reads, messages, draft, active
+ * live locations and the current user's scheduled messages.
*
* @param params.channelIds The channel IDs to fetch.
* @param params.userId The ID of the current user.
@@ -30,19 +31,27 @@ export const getChannels = async ({
}): Promise[]> => {
SqliteClient.logger?.('info', 'getChannels', { channelIds, userId, messageLimit });
- const [channels, cidVsDraft, cidVsMembers, cidVsReads, cidVsMessages, cidVsActiveLocations] =
- await Promise.all([
- selectChannels({ channelIds }),
- getDraftForChannels({ channelIds, userId }),
- getMembers({ channelIds }),
- getReads({ channelIds }),
- getChannelMessages({
- channelIds,
- userId,
- messageLimit,
- }),
- getChannelActiveLocations({ channelIds }),
- ]);
+ const [
+ channels,
+ cidVsDraft,
+ cidVsMembers,
+ cidVsReads,
+ cidVsMessages,
+ cidVsActiveLocations,
+ scheduledMessages,
+ ] = await Promise.all([
+ selectChannels({ channelIds }),
+ getDraftForChannels({ channelIds, userId }),
+ getMembers({ channelIds }),
+ getReads({ channelIds }),
+ getChannelMessages({
+ channelIds,
+ userId,
+ messageLimit,
+ }),
+ getChannelActiveLocations({ channelIds }),
+ getScheduledMessages({}),
+ ]);
return channels.map((c) => ({
...mapStorableToChannel(c),
@@ -53,6 +62,7 @@ export const getChannels = async ({
messages: cidVsMessages[c.cid] || [],
pinned_messages: [],
read: cidVsReads[c.cid] || [],
+ scheduled_messages: scheduledMessages.filter(({ cid }) => cid === c.cid),
threads: [],
}));
};
diff --git a/package/src/store/apis/getScheduledMessages.ts b/package/src/store/apis/getScheduledMessages.ts
new file mode 100644
index 0000000000..2cf92422f2
--- /dev/null
+++ b/package/src/store/apis/getScheduledMessages.ts
@@ -0,0 +1,79 @@
+import type { DBGetScheduledMessagesType, ScheduledMessageResponse } from 'stream-chat';
+
+import { mapStorableToScheduledMessage } from '../mappers/mapStorableToScheduledMessage';
+import { tables } from '../schema';
+import { SqliteClient } from '../SqliteClient';
+import type { Scalar, TableRow, TableRowJoinedUser } from '../types';
+
+/**
+ * Fetches the stored scheduled messages with their messages, earliest `scheduled_at` first, as the
+ * server and `ScheduledMessagePaginator` order them.
+ *
+ * @param params.cid Only this channel's, when given.
+ * @param params.statuses Only these statuses, when given.
+ * @param params.limit Maximum number of scheduled messages to return.
+ * @returns The scheduled messages.
+ */
+export const getScheduledMessages = async ({
+ cid,
+ limit,
+ statuses,
+}: DBGetScheduledMessagesType): Promise => {
+ const userColumnNames = Object.keys(tables.users.columns)
+ .map((name) => `'${name}', b.${name}`)
+ .join(', ');
+ const messageColumnNames = Object.keys(tables.messages.columns)
+ .map((name) => `'${name}', a.${name}`)
+ .join(', ');
+ const scheduledMessageColumnNames = Object.keys(tables.scheduledMessages.columns)
+ .map((name) => `'${name}', s.${name}`)
+ .join(', ');
+
+ const conditions: string[] = [];
+ const params: Scalar[] = [];
+ if (cid) {
+ conditions.push('s.cid = ?');
+ params.push(cid);
+ }
+ if (statuses?.length) {
+ conditions.push(`s.status in (${Array(statuses.length).fill('?').join(',')})`);
+ params.push(...statuses);
+ }
+ if (limit) params.push(limit);
+
+ SqliteClient.logger?.('info', 'getScheduledMessages', { cid, limit, statuses });
+
+ const result = await SqliteClient.executeSql(
+ `SELECT
+ json_object(
+ 'messageRow', json_object(
+ 'user', json_object(
+ ${userColumnNames}
+ ),
+ ${messageColumnNames}
+ ),
+ 'scheduledMessageRow', json_object(
+ ${scheduledMessageColumnNames}
+ )
+ ) as value
+ FROM scheduledMessages s
+ JOIN messages a
+ ON a.id = s.id
+ LEFT JOIN
+ users b
+ ON b.id = a.userId
+ ${conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''}
+ ORDER BY a.scheduledAt ASC, s.createdAt ASC, s.id ASC
+ ${limit ? 'LIMIT ?' : ''}`,
+ params,
+ );
+
+ return result.map((row) =>
+ mapStorableToScheduledMessage(
+ JSON.parse(row.value) as {
+ messageRow: TableRowJoinedUser<'messages'>;
+ scheduledMessageRow: TableRow<'scheduledMessages'>;
+ },
+ ),
+ );
+};
diff --git a/package/src/store/apis/index.ts b/package/src/store/apis/index.ts
index 149be19817..08de16ac9b 100644
--- a/package/src/store/apis/index.ts
+++ b/package/src/store/apis/index.ts
@@ -36,3 +36,6 @@ export * from './dropPendingTasks';
export * from './getDraft';
export * from './upsertDraft';
export * from './deleteDraft';
+export * from './deleteScheduledMessages';
+export * from './getScheduledMessages';
+export * from './upsertScheduledMessages';
diff --git a/package/src/store/apis/queries/selectMessageById.ts b/package/src/store/apis/queries/selectMessageById.ts
index a8c28db840..cdeab213cb 100644
--- a/package/src/store/apis/queries/selectMessageById.ts
+++ b/package/src/store/apis/queries/selectMessageById.ts
@@ -32,7 +32,7 @@ export const selectMessageForId = async (
SELECT
*
FROM messages
- WHERE id = ?
+ WHERE id = ? AND scheduledAt IS NULL
) a
LEFT JOIN
users b
diff --git a/package/src/store/apis/queries/selectMessagesForChannels.ts b/package/src/store/apis/queries/selectMessagesForChannels.ts
index c6257bf039..c27b35598c 100644
--- a/package/src/store/apis/queries/selectMessagesForChannels.ts
+++ b/package/src/store/apis/queries/selectMessagesForChannels.ts
@@ -38,7 +38,7 @@ export const selectMessagesForChannels = async (
ORDER BY createdAt DESC
) RowNum
FROM messages
- WHERE cid in (${questionMarks})
+ WHERE cid in (${questionMarks}) AND scheduledAt IS NULL
) a
LEFT JOIN
users b
diff --git a/package/src/store/apis/upsertScheduledMessages.ts b/package/src/store/apis/upsertScheduledMessages.ts
new file mode 100644
index 0000000000..29f9e45f9c
--- /dev/null
+++ b/package/src/store/apis/upsertScheduledMessages.ts
@@ -0,0 +1,50 @@
+import type { DBUpsertScheduledMessagesType } from 'stream-chat';
+
+import { mapScheduledMessageToStorable } from '../mappers/mapScheduledMessageToStorable';
+import { mapUserToStorable } from '../mappers/mapUserToStorable';
+import { createUpsertQuery } from '../sqlite-utils/createUpsertQuery';
+import { createUpsertQueryIfParentExists } from '../sqlite-utils/createUpsertQueryIfParentExists';
+import { SqliteClient } from '../SqliteClient';
+import type { PreparedQueries } from '../types';
+
+/**
+ * Stores scheduled messages: each one's message in the messages table, marked by `scheduledAt`, and
+ * its scheduling in the scheduled messages table. One whose channel is not stored is skipped, as
+ * its message would violate the channel foreign key and abort the whole batch.
+ */
+export const upsertScheduledMessages = async ({
+ execute = true,
+ scheduledMessages,
+}: DBUpsertScheduledMessagesType) => {
+ const queries: PreparedQueries[] = [];
+
+ for (const scheduledMessage of scheduledMessages) {
+ const storable = mapScheduledMessageToStorable(scheduledMessage);
+ queries.push(createUpsertQuery('users', mapUserToStorable(scheduledMessage.user)));
+ queries.push(
+ createUpsertQueryIfParentExists('messages', storable.message, {
+ column: 'cid',
+ table: 'channels',
+ value: scheduledMessage.cid,
+ }),
+ );
+ queries.push(
+ createUpsertQueryIfParentExists('scheduledMessages', storable.scheduledMessage, {
+ column: 'id',
+ table: 'messages',
+ value: scheduledMessage.id,
+ }),
+ );
+ }
+
+ SqliteClient.logger?.('info', 'upsertScheduledMessages', {
+ execute,
+ ids: scheduledMessages.map(({ id }) => id),
+ });
+
+ if (execute && queries.length) {
+ await SqliteClient.executeSqlBatch(queries);
+ }
+
+ return queries;
+};
diff --git a/package/src/store/mappers/mapScheduledMessageToStorable.ts b/package/src/store/mappers/mapScheduledMessageToStorable.ts
new file mode 100644
index 0000000000..e96e1a7473
--- /dev/null
+++ b/package/src/store/mappers/mapScheduledMessageToStorable.ts
@@ -0,0 +1,53 @@
+import type { MessageLabel, ScheduledMessageResponse } from 'stream-chat';
+
+import { mapTimestampToStorable } from './mapTimestampToStorable';
+
+import type { TableRow } from '../types';
+
+/**
+ * Splits a scheduled message into its message, stored in the messages table and marked by
+ * `scheduledAt` so no message list reads it, and its scheduling, in the scheduled messages table.
+ */
+export const mapScheduledMessageToStorable = ({
+ channel,
+ cid,
+ created_at,
+ failure_reason,
+ id,
+ message,
+ scheduled_at,
+ status,
+ updated_at,
+ user,
+}: ScheduledMessageResponse): {
+ message: Partial>;
+ scheduledMessage: TableRow<'scheduledMessages'>;
+} => {
+ const { attachments, poll_id, text, type, ...extraData } = message;
+
+ return {
+ message: {
+ attachments: JSON.stringify(attachments ?? []),
+ cid,
+ createdAt: mapTimestampToStorable(created_at),
+ extraData: JSON.stringify(extraData),
+ id,
+ poll_id: poll_id ?? '',
+ scheduledAt: mapTimestampToStorable(scheduled_at),
+ text,
+ type: (type ?? 'regular') as MessageLabel,
+ updatedAt: mapTimestampToStorable(updated_at),
+ userId: user.id,
+ },
+ scheduledMessage: {
+ channel: channel ? JSON.stringify(channel) : undefined,
+ cid,
+ createdAt: mapTimestampToStorable(created_at),
+ failureReason: failure_reason ?? null,
+ id,
+ status,
+ updatedAt: mapTimestampToStorable(updated_at),
+ userId: user.id,
+ },
+ };
+};
diff --git a/package/src/store/mappers/mapStorableToMessage.ts b/package/src/store/mappers/mapStorableToMessage.ts
index e4f382e2fc..2cf3a70cfa 100644
--- a/package/src/store/mappers/mapStorableToMessage.ts
+++ b/package/src/store/mappers/mapStorableToMessage.ts
@@ -32,6 +32,8 @@ export const mapStorableToMessage = ({
ownMarks,
poll_id,
reactionGroups,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ scheduledAt,
shared_location,
updatedAt,
user,
diff --git a/package/src/store/mappers/mapStorableToScheduledMessage.ts b/package/src/store/mappers/mapStorableToScheduledMessage.ts
new file mode 100644
index 0000000000..115497ae02
--- /dev/null
+++ b/package/src/store/mappers/mapStorableToScheduledMessage.ts
@@ -0,0 +1,37 @@
+import type { ScheduledMessageResponse } from 'stream-chat';
+
+import { mapStorableToRequiredTimestamp } from './mapStorableToTimestamp';
+import { mapStorableToUser } from './mapStorableToUser';
+
+import type { TableRow, TableRowJoinedUser } from '../types';
+
+/** Joins a scheduled message's two rows back into the scheduled message. */
+export const mapStorableToScheduledMessage = ({
+ messageRow,
+ scheduledMessageRow,
+}: {
+ messageRow: TableRowJoinedUser<'messages'>;
+ scheduledMessageRow: TableRow<'scheduledMessages'>;
+}): ScheduledMessageResponse => {
+ const { attachments, extraData, poll_id, scheduledAt, text, type, user, userId } = messageRow;
+ const { channel, cid, createdAt, failureReason, id, status, updatedAt } = scheduledMessageRow;
+
+ return {
+ cid,
+ created_at: mapStorableToRequiredTimestamp(createdAt),
+ id,
+ message: {
+ ...(extraData ? JSON.parse(extraData) : {}),
+ attachments: attachments ? JSON.parse(attachments) : [],
+ ...(poll_id ? { poll_id } : {}),
+ text: text ?? '',
+ type,
+ },
+ scheduled_at: mapStorableToRequiredTimestamp(scheduledAt),
+ status,
+ updated_at: mapStorableToRequiredTimestamp(updatedAt),
+ user: mapStorableToUser(user?.id ? user : { id: userId ?? '' }),
+ ...(channel ? { channel: JSON.parse(channel) } : {}),
+ ...(failureReason ? { failure_reason: failureReason } : {}),
+ };
+};
diff --git a/package/src/store/schema.ts b/package/src/store/schema.ts
index 906f64e2ee..a51b88c483 100644
--- a/package/src/store/schema.ts
+++ b/package/src/store/schema.ts
@@ -1,4 +1,9 @@
-import type { MessageLabel, PendingTaskTypes } from 'stream-chat';
+import type {
+ MessageLabel,
+ PendingTaskTypes,
+ ScheduledMessageFailureReason,
+ ScheduledMessageStatus,
+} from 'stream-chat';
import type { ValueOf } from '../types/types';
@@ -200,6 +205,7 @@ export const tables: Tables = {
ownMarks: 'TEXT',
poll_id: 'TEXT',
reactionGroups: 'TEXT',
+ scheduledAt: 'INTEGER',
shared_location: 'TEXT',
text: "TEXT DEFAULT ''",
type: 'TEXT',
@@ -334,6 +340,34 @@ export const tables: Tables = {
],
primaryKey: ['messageId'],
},
+ scheduledMessages: {
+ columns: {
+ channel: 'TEXT',
+ cid: 'TEXT NOT NULL',
+ createdAt: 'INTEGER',
+ failureReason: 'TEXT',
+ id: 'TEXT NOT NULL',
+ status: 'TEXT NOT NULL',
+ updatedAt: 'INTEGER',
+ userId: 'TEXT',
+ },
+ foreignKeys: [
+ {
+ column: 'id',
+ onDeleteAction: 'CASCADE',
+ referenceTable: 'messages',
+ referenceTableColumn: 'id',
+ },
+ ],
+ indexes: [
+ {
+ columns: ['cid', 'status'],
+ name: 'index_scheduled_messages',
+ unique: false,
+ },
+ ],
+ primaryKey: ['id'],
+ },
users: {
columns: {
banned: 'BOOLEAN DEFAULT FALSE',
@@ -460,6 +494,8 @@ export type Schema = {
shared_location: string;
type: MessageLabel;
updatedAt: number | null;
+ /** Set only on the message of a scheduled message, which no message list shows. */
+ scheduledAt?: number | null;
text?: string;
userId?: string;
};
@@ -534,6 +570,17 @@ export type Schema = {
updatedAt: number | null;
userId: string;
};
+ scheduledMessages: {
+ cid: string;
+ createdAt: number | null;
+ id: string;
+ status: ScheduledMessageStatus;
+ updatedAt: number | null;
+ /** The channel as the scheduled message describes it, for a list across channels. */
+ channel?: string;
+ failureReason?: ScheduledMessageFailureReason | null;
+ userId?: string;
+ };
users: {
id: string;
banned?: boolean;
diff --git a/yarn.lock b/yarn.lock
index 2760258c9f..72f2ce0c2e 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5839,6 +5839,29 @@ __metadata:
languageName: node
linkType: hard
+"@react-native/community-cli-plugin@npm:0.88.1":
+ version: 0.88.1
+ resolution: "@react-native/community-cli-plugin@npm:0.88.1"
+ dependencies:
+ "@react-native/asset-utils": "npm:0.88.1"
+ "@react-native/dev-middleware": "npm:0.88.1"
+ commander: "npm:^12.0.0"
+ debug: "npm:^4.4.0"
+ invariant: "npm:^2.2.4"
+ metro: "npm:^0.87.1"
+ semver: "npm:^7.1.3"
+ peerDependencies:
+ "@react-native-community/cli": "*"
+ "@react-native/metro-config": 0.88.1
+ peerDependenciesMeta:
+ "@react-native-community/cli":
+ optional: true
+ "@react-native/metro-config":
+ optional: true
+ checksum: 10c0/aeee1cd978bdf4f60994888465ca6af8b94d6cb706a06b1fa2dad1b5e11f62e70c8042afe1beb246c7fb5bff684aa951606ad45809faf7a18a0e3e6a81a005b8
+ languageName: node
+ linkType: hard
+
"@react-native/debugger-frontend@npm:0.88.0":
version: 0.88.0
resolution: "@react-native/debugger-frontend@npm:0.88.0"
@@ -5954,6 +5977,13 @@ __metadata:
languageName: node
linkType: hard
+"@react-native/gradle-plugin@npm:0.88.1":
+ version: 0.88.1
+ resolution: "@react-native/gradle-plugin@npm:0.88.1"
+ checksum: 10c0/b78162926d85c4261338c1f00f0f423d949b619f61eaada6be20d07297e675c7923edeb1234df23be8b0cb3d334fd08e24af4a10f122df64e9d6ad2e5c4ed8fa
+ languageName: node
+ linkType: hard
+
"@react-native/jest-preset@npm:0.88.0":
version: 0.88.0
resolution: "@react-native/jest-preset@npm:0.88.0"
@@ -6068,6 +6098,23 @@ __metadata:
languageName: node
linkType: hard
+"@react-native/virtualized-lists@npm:0.88.1":
+ version: 0.88.1
+ resolution: "@react-native/virtualized-lists@npm:0.88.1"
+ dependencies:
+ invariant: "npm:^2.2.4"
+ nullthrows: "npm:^1.1.1"
+ peerDependencies:
+ "@types/react": ^19.2.0
+ react: "*"
+ react-native: 0.88.1
+ peerDependenciesMeta:
+ "@types/react":
+ optional: true
+ checksum: 10c0/663f3798bb619677549e047703d102e28244b569fedbcf493fbf4f056f5a06093cbf12470873593f7c436357c11660d41eed55638fbac404e2438b4b2e06fa13
+ languageName: node
+ linkType: hard
+
"@react-navigation/bottom-tabs@npm:^7.20.0":
version: 7.20.0
resolution: "@react-navigation/bottom-tabs@npm:7.20.0"
@@ -7534,7 +7581,7 @@ __metadata:
expo-video: "npm:~58.0.10"
react: "npm:19.3.0"
react-dom: "npm:19.3.0"
- react-native: "npm:0.88.0"
+ react-native: "npm:0.88.1"
react-native-gesture-handler: "npm:~3.4.0"
react-native-keyboard-controller: "npm:1.22.7"
react-native-maps: "npm:1.29.11"
@@ -12883,6 +12930,13 @@ __metadata:
languageName: node
linkType: hard
+"hermes-compiler@npm:260318099.0.5":
+ version: 260318099.0.5
+ resolution: "hermes-compiler@npm:260318099.0.5"
+ checksum: 10c0/0194e815661498cd384aa4de24dfb3754e856fe473782fa6861d9191c84fde926ca3f3a6921231418e810655ee9e231e6e701d3f3dca10aa1079162dd0623ab9
+ languageName: node
+ linkType: hard
+
"hermes-estree@npm:0.23.1":
version: 0.23.1
resolution: "hermes-estree@npm:0.23.1"
@@ -18995,6 +19049,51 @@ __metadata:
languageName: node
linkType: hard
+"react-native@npm:0.88.1":
+ version: 0.88.1
+ resolution: "react-native@npm:0.88.1"
+ dependencies:
+ "@react-native/asset-utils": "npm:0.88.1"
+ "@react-native/codegen": "npm:0.88.1"
+ "@react-native/community-cli-plugin": "npm:0.88.1"
+ "@react-native/gradle-plugin": "npm:0.88.1"
+ "@react-native/normalize-colors": "npm:0.88.1"
+ "@react-native/virtualized-lists": "npm:0.88.1"
+ anser: "npm:^1.4.9"
+ ansi-regex: "npm:^5.0.0"
+ base64-js: "npm:^1.5.1"
+ flow-enums-runtime: "npm:^0.0.6"
+ flow-parser: "npm:0.327.0"
+ hermes-compiler: "npm:260318099.0.5"
+ invariant: "npm:^2.2.4"
+ memoize-one: "npm:^5.0.0"
+ metro-runtime: "npm:^0.87.1"
+ metro-source-map: "npm:^0.87.1"
+ nullthrows: "npm:^1.1.1"
+ pretty-format: "npm:^29.7.0"
+ promise: "npm:^8.3.0"
+ react-devtools-core: "npm:^6.1.5"
+ react-refresh: "npm:^0.14.0"
+ regenerator-runtime: "npm:^0.13.2"
+ scheduler: "npm:0.28.0"
+ semver: "npm:^7.1.3"
+ stacktrace-parser: "npm:^0.1.10"
+ tinyglobby: "npm:^0.2.15"
+ whatwg-fetch: "npm:^3.0.0"
+ ws: "npm:^7.5.10"
+ yargs: "npm:^17.6.2"
+ peerDependencies:
+ "@types/react": ^19.1.1
+ react: ^19.3.0
+ peerDependenciesMeta:
+ "@types/react":
+ optional: true
+ bin:
+ react-native: cli.js
+ checksum: 10c0/c000040ac4b1b2dc736f40811ef4d11c88986296147e7722ed0f817540c0cb950a322e8766f9bc997470ef01e6bc46e90ff58ed67255fe08e1d8dee7da9ecfb3
+ languageName: node
+ linkType: hard
+
"react-reconciler@npm:0.31.0":
version: 0.31.0
resolution: "react-reconciler@npm:0.31.0"