From 92685e692e46225b55603174aadbbb5520fa6e68 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj Date: Thu, 26 Nov 2026 14:58:10 +0100 Subject: [PATCH 01/24] fix(MessageComposer): lift the composer above bottomInset while the attachment picker is open The attachment picker sheet is lifted by `bottomInset`, but the composer rose by `attachmentPickerBottomSheetHeight - bottomInset`, so any non-zero inset made the picker cover the composer. It now rises by the picker height plus the inset. --- .../MessageInput/MessageComposer.tsx | 8 ++++---- .../__tests__/MessageComposer.test.tsx | 18 +++++++++++++++++- .../AttachmentPickerContext.tsx | 9 +++++++-- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/package/src/components/MessageInput/MessageComposer.tsx b/package/src/components/MessageInput/MessageComposer.tsx index 2bb0ad7eac..2ddeef2458 100644 --- a/package/src/components/MessageInput/MessageComposer.tsx +++ b/package/src/components/MessageInput/MessageComposer.tsx @@ -343,7 +343,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { style={{ paddingBottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + ? attachmentPickerBottomSheetHeight + bottomInset : 0, }} /> @@ -356,7 +356,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { { bottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + BOTTOM_OFFSET + ? attachmentPickerBottomSheetHeight + bottomInset + BOTTOM_OFFSET : BOTTOM_OFFSET, }, floatingWrapper, @@ -375,7 +375,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { messageInputHeightStore.setHeight( newHeight - (selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + ? attachmentPickerBottomSheetHeight + bottomInset : 0), ); }} @@ -390,7 +390,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { borderTopColor: semantics.borderCoreSubtle, paddingBottom: selectedPicker && !isKeyboardVisible - ? attachmentPickerBottomSheetHeight - bottomInset + BOTTOM_OFFSET + ? attachmentPickerBottomSheetHeight + bottomInset + BOTTOM_OFFSET : BOTTOM_OFFSET, }, wrapper, diff --git a/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx b/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx index f74062e077..00f6da0953 100644 --- a/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx +++ b/package/src/components/MessageInput/__tests__/MessageComposer.test.tsx @@ -1,6 +1,6 @@ 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'; @@ -22,6 +22,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 +34,7 @@ jest.spyOn(AttachmentPickerUtils, 'useAttachmentPickerContext').mockImplementati setBottomInset: jest.fn(), setTopInset: jest.fn(), attachmentPickerStore, + ...attachmentPickerContextOverrides, } as unknown as ReturnType; }); @@ -69,11 +71,25 @@ 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); + }); + // 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/contexts/attachmentPickerContext/AttachmentPickerContext.tsx b/package/src/contexts/attachmentPickerContext/AttachmentPickerContext.tsx index 45082d028b..dab7ef1958 100644 --- a/package/src/contexts/attachmentPickerContext/AttachmentPickerContext.tsx +++ b/package/src/contexts/attachmentPickerContext/AttachmentPickerContext.tsx @@ -21,13 +21,18 @@ export type AttachmentPickerContextValue = Pick< 'attachmentSelectionBarHeight' | 'attachmentPickerBottomSheetHeight' > & { /** - * 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; /** From ebfab9fcf665492c9163873410b5d1a7f51eba62 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj Date: Thu, 26 Nov 2026 16:55:17 +0100 Subject: [PATCH 02/24] feat: scheduled messages foundation Utilities, hooks and wiring the scheduled messages UI builds on, with no UI yet: - schedule time presets, bounds and defaults, failure and error copy, deleted quote checks - hooks over the LLC's scheduled message views (`useScheduledMessages`, `useChannelScheduledMessages`, `useChannelWideScheduledMessagesView`), the per-channel limit and the edited scheduled message - `Chat` registers `client.scheduledMessagePaginators` - translations for the LLC's scheduled message notifications - the scheduled messages theme keys --- package/src/components/Chat/Chat.tsx | 2 + .../notificationTranslations.test.ts | 42 ++++- .../Notifications/notificationTranslations.ts | 82 +++++++-- .../__tests__/scheduleTime.test.ts | 145 ++++++++++++++++ .../useChannelScheduledMessages.test.tsx | 50 ++++++ .../hooks/useChannelScheduledMessageLimit.ts | 24 +++ .../hooks/useChannelScheduledMessages.ts | 42 +++++ .../useChannelWideScheduledMessagesView.ts | 14 ++ .../hooks/useEditedScheduledMessage.ts | 23 +++ .../hooks/useScheduledMessages.ts | 29 ++++ .../hooks/useScheduledTimeFormatter.ts | 59 +++++++ .../src/components/ScheduledMessages/index.ts | 11 ++ .../ScheduledMessages/utils/actions.ts | 5 + .../ScheduledMessages/utils/failureReason.ts | 46 +++++ .../ScheduledMessages/utils/quote.ts | 13 ++ .../ScheduledMessages/utils/scheduleErrors.ts | 71 ++++++++ .../ScheduledMessages/utils/scheduleTime.ts | 90 ++++++++++ package/src/components/index.ts | 2 + .../src/contexts/themeContext/utils/theme.ts | 160 ++++++++++++++++++ .../src/i18n/__tests__/catalog.fixture.json | 32 +++- package/src/i18n/keys.ts | 32 +++- 21 files changed, 958 insertions(+), 16 deletions(-) create mode 100644 package/src/components/ScheduledMessages/__tests__/scheduleTime.test.ts create mode 100644 package/src/components/ScheduledMessages/__tests__/useChannelScheduledMessages.test.tsx create mode 100644 package/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts create mode 100644 package/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts create mode 100644 package/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts create mode 100644 package/src/components/ScheduledMessages/hooks/useEditedScheduledMessage.ts create mode 100644 package/src/components/ScheduledMessages/hooks/useScheduledMessages.ts create mode 100644 package/src/components/ScheduledMessages/hooks/useScheduledTimeFormatter.ts create mode 100644 package/src/components/ScheduledMessages/index.ts create mode 100644 package/src/components/ScheduledMessages/utils/actions.ts create mode 100644 package/src/components/ScheduledMessages/utils/failureReason.ts create mode 100644 package/src/components/ScheduledMessages/utils/quote.ts create mode 100644 package/src/components/ScheduledMessages/utils/scheduleErrors.ts create mode 100644 package/src/components/ScheduledMessages/utils/scheduleTime.ts 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/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..b7f81d6eac 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,48 @@ 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", + ); + case ScheduledMessageBlockReason.SharedLocation: + return t( + 'notifications.scheduledMessageBlocked.sharedLocation.error', + "Locations 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 +217,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/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__/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/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/hooks/useScheduledTimeFormatter.ts b/package/src/components/ScheduledMessages/hooks/useScheduledTimeFormatter.ts new file mode 100644 index 0000000000..80827dce94 --- /dev/null +++ b/package/src/components/ScheduledMessages/hooks/useScheduledTimeFormatter.ts @@ -0,0 +1,59 @@ +import { useCallback } from 'react'; + +import { useTranslationContext } from '../../../contexts/translationContext/TranslationContext'; +import type { TDateTimeParser } from '../../../contexts/translationContext/types'; +import { isDayOrMoment } from '../../../i18n/utils'; +import { isSameLocalDay } from '../utils/scheduleTime'; + +/** Formats `date` with a Day.js/Moment template through the app's date parser. */ +export const formatWithParser = ( + tDateTimeParser: TDateTimeParser, + date: Date, + template: string, +) => { + const parsed = tDateTimeParser(date); + return isDayOrMoment(parsed) ? parsed.format(template) : date.toLocaleString(); +}; + +/** + * Formatters for the times shown around scheduled messages, such as `Fri, Oct 23 at 09:00` and + * `Tomorrow at 09:00`. + */ +export const useScheduledTimeFormatter = () => { + const { t, tDateTimeParser } = useTranslationContext(); + + const formatTime = useCallback( + (date: Date) => formatWithParser(tDateTimeParser, date, 'LT'), + [tDateTimeParser], + ); + + const formatDateTime = useCallback( + (date: Date) => + t('scheduledMessages.dateTime.label', '{{ day }} at {{ time }}', { + day: formatWithParser(tDateTimeParser, date, 'ddd, MMM D'), + time: formatTime(date), + }), + [formatTime, t, tDateTimeParser], + ); + + const formatPreset = useCallback( + (date: Date, now: Date) => { + const tomorrow = new Date(now); + tomorrow.setDate(now.getDate() + 1); + + if (isSameLocalDay(date, tomorrow)) { + return t('scheduledMessages.preset.tomorrow.label', 'Tomorrow at {{ time }}', { + time: formatTime(date), + }); + } + + return t('scheduledMessages.preset.weekday.label', '{{ day }} at {{ time }}', { + day: formatWithParser(tDateTimeParser, date, 'dddd'), + time: formatTime(date), + }); + }, + [formatTime, t, tDateTimeParser], + ); + + return { formatDateTime, formatPreset, formatTime }; +}; diff --git a/package/src/components/ScheduledMessages/index.ts b/package/src/components/ScheduledMessages/index.ts new file mode 100644 index 0000000000..d8a98a25e5 --- /dev/null +++ b/package/src/components/ScheduledMessages/index.ts @@ -0,0 +1,11 @@ +export * from './hooks/useChannelScheduledMessageLimit'; +export * from './hooks/useChannelScheduledMessages'; +export * from './hooks/useChannelWideScheduledMessagesView'; +export * from './hooks/useEditedScheduledMessage'; +export * from './hooks/useScheduledMessages'; +export * from './hooks/useScheduledTimeFormatter'; +export * from './utils/actions'; +export * from './utils/failureReason'; +export * from './utils/scheduleErrors'; +export * from './utils/scheduleTime'; +export * from './utils/quote'; 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/index.ts b/package/src/components/index.ts index fa4f16c8f9..d18d5cda7c 100644 --- a/package/src/components/index.ts +++ b/package/src/components/index.ts @@ -201,6 +201,8 @@ export * from './UIComponents/EmptySearchResult'; export * from './UIComponents/SearchInput'; export * from './UIComponents/SelectionCircle'; +export * from './ScheduledMessages'; + export * from './Thread/Thread'; export * from './Thread/components/ThreadFooterComponent'; export * from './ThreadList/ThreadList'; diff --git a/package/src/contexts/themeContext/utils/theme.ts b/package/src/contexts/themeContext/utils/theme.ts index 341e27aa64..aac675a506 100644 --- a/package/src/contexts/themeContext/utils/theme.ts +++ b/package/src/contexts/themeContext/utils/theme.ts @@ -1162,6 +1162,86 @@ export type Theme = { }; }; screenPadding: number; + scheduledMessages: { + actionsSheet: { + container: ViewStyle; + }; + banner: { + banner: ViewStyle; + container: ViewStyle; + label: TextStyle; + link: TextStyle; + }; + calendar: { + container: ViewStyle; + day: ViewStyle; + dayText: TextStyle; + header: ViewStyle; + monthTitle: TextStyle; + selectedDay: ViewStyle; + weekday: TextStyle; + }; + list: { + container: ViewStyle; + list: ViewStyle; + listContent: ViewStyle; + }; + listItem: { + channelName: TextStyle; + container: ViewStyle; + content: ViewStyle; + preview: TextStyle; + row: ViewStyle; + status: 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; + }; + sheetPreview: { + bar: ViewStyle; + container: ViewStyle; + text: TextStyle; + thumbnail: ImageStyle; + title: TextStyle; + }; + timePicker: { + columns: ViewStyle; + container: ViewStyle; + item: ViewStyle; + itemText: TextStyle; + label: TextStyle; + pill: ViewStyle; + pillText: TextStyle; + row: ViewStyle; + }; + timeSheet: { + container: ViewStyle; + content: ViewStyle; + }; + }; + scheduledMessageListSkeleton: { + animationTime: number; + avatar: ViewStyle; + container: ViewStyle; + content: ViewStyle; + subtitle: ViewStyle; + textContainer: ViewStyle; + title: ViewStyle; + }; selectionCircle: { circle: ViewStyle; circleSelected: ViewStyle; @@ -2262,6 +2342,86 @@ export const defaultTheme: Theme = { }, }, screenPadding: 16, + scheduledMessages: { + actionsSheet: { + container: {}, + }, + banner: { + banner: {}, + container: {}, + label: {}, + link: {}, + }, + calendar: { + container: {}, + day: {}, + dayText: {}, + header: {}, + monthTitle: {}, + selectedDay: {}, + weekday: {}, + }, + list: { + container: {}, + list: {}, + listContent: {}, + }, + listItem: { + channelName: {}, + container: {}, + content: {}, + preview: {}, + row: {}, + status: {}, + statusText: {}, + time: {}, + }, + notice: { + container: {}, + description: {}, + title: {}, + }, + presetSheet: { + container: {}, + option: {}, + optionLabel: {}, + options: {}, + }, + sheetHeader: { + container: {}, + title: {}, + }, + sheetPreview: { + bar: {}, + container: {}, + text: {}, + thumbnail: {}, + title: {}, + }, + timePicker: { + columns: {}, + container: {}, + item: {}, + itemText: {}, + label: {}, + pill: {}, + pillText: {}, + row: {}, + }, + timeSheet: { + container: {}, + content: {}, + }, + }, + scheduledMessageListSkeleton: { + animationTime: 1000, // in milliseconds + avatar: {}, + container: {}, + content: {}, + subtitle: {}, + textContainer: {}, + title: {}, + }, selectionCircle: { circle: {}, circleSelected: {}, diff --git a/package/src/i18n/__tests__/catalog.fixture.json b/package/src/i18n/__tests__/catalog.fixture.json index 5348291385..f62e5bc67b 100644 --- a/package/src/i18n/__tests__/catalog.fixture.json +++ b/package/src/i18n/__tests__/catalog.fixture.json @@ -409,10 +409,13 @@ "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.scheduledMessageBlocked.sharedLocation.error": "Locations can't 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,31 @@ "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.channelLimit.error": "You've reached the limit of scheduled messages in this channel.", + "scheduledMessages.dateTime.label": "{{ day }} at {{ time }}", + "scheduledMessages.disabled.error": "Scheduled messages are turned off", + "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.preset.tomorrow.label": "Tomorrow at {{ time }}", + "scheduledMessages.preset.weekday.label": "{{ day }} at {{ time }}", + "scheduledMessages.rescheduleFailed.error": "Couldn't reschedule the message. Try again", + "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.tooFar.error": "That's further ahead than your app allows", + "scheduledMessages.updateFailed.error": "Couldn't update the scheduled message. Try again", + "scheduledMessages.userLimit.error": "You've reached your limit of scheduled messages.", + "scheduledMessages.userLimitCount.error": "You've reached your limit of {{ count }} scheduled messages.", "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", diff --git a/package/src/i18n/keys.ts b/package/src/i18n/keys.ts index 90db0072c9..573df32e6e 100644 --- a/package/src/i18n/keys.ts +++ b/package/src/i18n/keys.ts @@ -420,10 +420,13 @@ 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.scheduledMessageBlocked.sharedLocation.error': "Locations can't 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,31 @@ 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.channelLimit.error': "You've reached the limit of scheduled messages in this channel."; + 'scheduledMessages.dateTime.label': '{{ day }} at {{ time }}'; + 'scheduledMessages.disabled.error': 'Scheduled messages are turned off'; + '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.preset.tomorrow.label': 'Tomorrow at {{ time }}'; + 'scheduledMessages.preset.weekday.label': '{{ day }} at {{ time }}'; + 'scheduledMessages.rescheduleFailed.error': "Couldn't reschedule the message. Try again"; + '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.tooFar.error': "That's further ahead than your app allows"; + 'scheduledMessages.updateFailed.error': "Couldn't update the scheduled message. Try again"; + 'scheduledMessages.userLimit.error': "You've reached your limit of scheduled messages."; + 'scheduledMessages.userLimitCount.error': "You've reached your limit of {{ count }} scheduled messages."; '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'; From 3bcb60b33473081b4286ebcb22c2f273644fea14 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj Date: Thu, 26 Nov 2026 21:05:37 +0100 Subject: [PATCH 03/24] feat(MessageComposer): schedule a message A long press on send opens the quick times. Custom time opens a date and time sheet on top of them. --- .../MessageInput/MessageComposer.tsx | 2 + .../components/OutputButtons/SendButton.tsx | 6 +- package/src/components/Reply/Reply.tsx | 16 +- .../ScheduledMessages/ScheduleCalendar.tsx | 307 ++++++++++++++++++ .../ScheduleMessageSheet.tsx | 244 ++++++++++++++ .../ScheduledMessages/ScheduleSheetHeader.tsx | 112 +++++++ .../ScheduledMessages/ScheduleSheetNotice.tsx | 95 ++++++ .../ScheduledMessages/ScheduleTimePicker.tsx | 257 +++++++++++++++ .../ScheduledMessages/ScheduleTimeSheet.tsx | 212 ++++++++++++ .../__tests__/ScheduledMessages.test.tsx | 205 ++++++++++++ .../__tests__/scheduleTime.test.ts | 10 + .../hooks/useScheduleComposerMessage.ts | 98 ++++++ .../src/components/ScheduledMessages/index.ts | 7 + .../componentsContext/defaultComponents.ts | 4 + .../MessageInputContext.tsx | 22 ++ .../hooks/useCreateMessageInputContext.ts | 6 + .../src/contexts/themeContext/utils/theme.ts | 14 - .../src/i18n/__tests__/catalog.fixture.json | 13 + package/src/i18n/keys.ts | 14 + package/src/i18n/runtimeDefaults.ts | 1 + 20 files changed, 1627 insertions(+), 18 deletions(-) create mode 100644 package/src/components/ScheduledMessages/ScheduleCalendar.tsx create mode 100644 package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx create mode 100644 package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx create mode 100644 package/src/components/ScheduledMessages/ScheduleSheetNotice.tsx create mode 100644 package/src/components/ScheduledMessages/ScheduleTimePicker.tsx create mode 100644 package/src/components/ScheduledMessages/ScheduleTimeSheet.tsx create mode 100644 package/src/components/ScheduledMessages/__tests__/ScheduledMessages.test.tsx create mode 100644 package/src/components/ScheduledMessages/hooks/useScheduleComposerMessage.ts diff --git a/package/src/components/MessageInput/MessageComposer.tsx b/package/src/components/MessageInput/MessageComposer.tsx index 2ddeef2458..ae7bc8f92e 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(); @@ -469,6 +470,7 @@ const MessageComposerWithContext = (props: MessageComposerPropsWithContext) => { /> ) : null} + ); }; 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/Reply/Reply.tsx b/package/src/components/Reply/Reply.tsx index f56b12184b..35ecff7424 100644 --- a/package/src/components/Reply/Reply.tsx +++ b/package/src/components/Reply/Reply.tsx @@ -103,6 +103,8 @@ export type ReplyPropsWithContext = { ImageComponent: React.ComponentType void; mode: 'reply' | 'edit'; + /** Replaces the title the mode gives, e.g. `Message to Maya Ross`. */ + title?: string; // Style overrides passed by `MessageContent`. styles?: { container?: ViewStyle; @@ -125,6 +127,7 @@ export const ReplyWithContext = (props: ReplyPropsWithContext) => { onDismiss, quotedMessage, styles: stylesProp, + title: titleProp, } = props; const { theme: { @@ -142,14 +145,15 @@ 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], + : t('message.reply.label', 'Reply')), + [mode, isMyMessage, quotedMessage?.user?.name, t, titleProp], ); if (!quotedMessage) { @@ -202,6 +206,7 @@ const areEqual = (prevProps: ReplyPropsWithContext, nextProps: ReplyPropsWithCon mode: prevMode, quotedMessage: prevQuotedMessage, onDismiss: prevOnDismiss, + title: prevTitle, } = prevProps; const { styles: nextStyles, @@ -210,6 +215,7 @@ const areEqual = (prevProps: ReplyPropsWithContext, nextProps: ReplyPropsWithCon mode: nextMode, quotedMessage: nextQuotedMessage, onDismiss: nextOnDismiss, + title: nextTitle, } = nextProps; if (prevStyles !== nextStyles) { @@ -233,6 +239,10 @@ const areEqual = (prevProps: ReplyPropsWithContext, nextProps: ReplyPropsWithCon return false; } + if (prevTitle !== nextTitle) { + return false; + } + const onDismissEqual = prevOnDismiss === nextOnDismiss; if (!onDismissEqual) { diff --git a/package/src/components/ScheduledMessages/ScheduleCalendar.tsx b/package/src/components/ScheduledMessages/ScheduleCalendar.tsx new file mode 100644 index 0000000000..4a408f1e0c --- /dev/null +++ b/package/src/components/ScheduledMessages/ScheduleCalendar.tsx @@ -0,0 +1,307 @@ +import React, { useMemo, useState } from 'react'; +import { I18nManager, Pressable, StyleSheet, Text, View } from 'react-native'; + +import { formatWithParser } from './hooks/useScheduledTimeFormatter'; + +import { isSameLocalDay } from './utils/scheduleTime'; + +import { useComponentsContext } from '../../contexts/componentsContext/ComponentsContext'; +import { useTheme } from '../../contexts/themeContext/ThemeContext'; +import { useTranslationContext } from '../../contexts/translationContext/TranslationContext'; +import { useStableCallback } from '../../hooks/useStableCallback'; +import { primitives } from '../../theme'; + +export type ScheduleCalendarProps = { + /** The first selectable day. Earlier days are shown disabled. */ + minimumDate: Date; + /** Called with the tapped day, keeping the time of `selectedDate`. */ + onSelectDate: (date: Date) => void; + selectedDate: Date; +}; + +const DAYS_IN_WEEK = 7; + +/** The days of a month, a week to a row, starting on Sunday. Empty cells are `undefined`. */ +export const getCalendarWeeks = (year: number, month: number) => { + const leadingBlanks = new Date(year, month, 1).getDay(); + const daysInMonth = new Date(year, month + 1, 0).getDate(); + const cells: (number | undefined)[] = [ + ...Array.from({ length: leadingBlanks }, () => undefined), + ...Array.from({ length: daysInMonth }, (_, index) => index + 1), + ]; + while (cells.length % DAYS_IN_WEEK) cells.push(undefined); + + return Array.from({ length: cells.length / DAYS_IN_WEEK }, (_, week) => + cells.slice(week * DAYS_IN_WEEK, (week + 1) * DAYS_IN_WEEK), + ); +}; + +const startOfDay = (date: Date) => { + const day = new Date(date); + day.setHours(0, 0, 0, 0); + return day; +}; + +type CalendarDayProps = { + accessibilityLabel: string; + dayOfMonth: number; + isPast: boolean; + isSelected: boolean; + isToday: boolean; + onSelect: (dayOfMonth: number) => void; +}; + +const CalendarDay = ({ + accessibilityLabel, + dayOfMonth, + isPast, + isSelected, + isToday, + onSelect, +}: CalendarDayProps) => { + const { + theme: { + scheduledMessages: { calendar: calendarTheme }, + semantics, + }, + } = useTheme(); + const styles = useStyles(); + const onPress = useStableCallback(() => onSelect(dayOfMonth)); + + const backgroundColor = isSelected + ? isToday + ? semantics.accentPrimary + : semantics.backgroundCoreInverse + : isToday + ? semantics.accentPrimarySubtle + : undefined; + const color = isSelected + ? isToday + ? semantics.textOnAccent + : semantics.textOnInverse + : isToday + ? semantics.accentPrimary + : isPast + ? semantics.textDisabled + : semantics.textPrimary; + + return ( + + + + {dayOfMonth} + + + + ); +}; + +export const ScheduleCalendar = ({ + minimumDate, + onSelectDate, + selectedDate, +}: ScheduleCalendarProps) => { + const { icons } = useComponentsContext(); + const { tDateTimeParser } = useTranslationContext(); + const { + theme: { + scheduledMessages: { calendar: calendarTheme }, + semantics, + }, + } = useTheme(); + const styles = useStyles(); + + const [shownMonth, setShownMonth] = useState(() => ({ + month: selectedDate.getMonth(), + year: selectedDate.getFullYear(), + })); + + const weeks = useMemo( + () => getCalendarWeeks(shownMonth.year, shownMonth.month), + [shownMonth.month, shownMonth.year], + ); + + const weekdayNames = useMemo(() => { + // Any Sunday works as the start of the week; 2023-01-01 was one. + const sunday = new Date(2023, 0, 1); + return Array.from({ length: DAYS_IN_WEEK }, (_, index) => { + const day = new Date(sunday); + day.setDate(sunday.getDate() + index); + return formatWithParser(tDateTimeParser, day, 'ddd').toUpperCase(); + }); + }, [tDateTimeParser]); + + const monthTitle = formatWithParser( + tDateTimeParser, + new Date(shownMonth.year, shownMonth.month, 1), + 'MMMM YYYY', + ); + + const firstSelectableDay = startOfDay(minimumDate); + const canGoBack = + new Date(shownMonth.year, shownMonth.month, 1) > + new Date(firstSelectableDay.getFullYear(), firstSelectableDay.getMonth(), 1); + const today = new Date(); + + const moveMonth = useStableCallback((delta: number) => + setShownMonth(({ month, year }) => { + const next = new Date(year, month + delta, 1); + return { month: next.getMonth(), year: next.getFullYear() }; + }), + ); + const showPreviousMonth = useStableCallback(() => moveMonth(-1)); + const showNextMonth = useStableCallback(() => moveMonth(1)); + + const selectDay = useStableCallback((dayOfMonth: number) => { + const next = new Date(selectedDate); + next.setFullYear(shownMonth.year, shownMonth.month, dayOfMonth); + onSelectDate(next); + }); + + const PreviousIcon = I18nManager.isRTL ? icons.ChevronRight : icons.ChevronLeft; + const NextIcon = I18nManager.isRTL ? icons.ChevronLeft : icons.ChevronRight; + + return ( + + + + {monthTitle} + + + + + + + + + + + + {weekdayNames.map((name) => ( + + {name} + + ))} + + {weeks.map((week, weekIndex) => ( + + {week.map((dayOfMonth, dayIndex) => { + if (!dayOfMonth) return ; + + const day = new Date(shownMonth.year, shownMonth.month, dayOfMonth); + + return ( + + ); + })} + + ))} + + ); +}; + +const DAY_SIZE = 40; + +const useStyles = () => + useMemo( + () => + StyleSheet.create({ + container: { + gap: primitives.spacingXxs, + }, + day: { + alignItems: 'center', + borderRadius: DAY_SIZE / 2, + height: DAY_SIZE, + justifyContent: 'center', + width: DAY_SIZE, + }, + dayCell: { + alignItems: 'center', + flex: 1, + paddingVertical: primitives.spacingXxs, + }, + dayText: { + fontSize: primitives.typographyFontSizeLg, + fontWeight: primitives.typographyFontWeightRegular, + }, + header: { + alignItems: 'center', + flexDirection: 'row', + justifyContent: 'space-between', + paddingBottom: primitives.spacingXs, + paddingHorizontal: primitives.spacingXs, + }, + monthTitle: { + fontSize: primitives.typographyFontSizeMd, + fontWeight: primitives.typographyFontWeightSemiBold, + }, + navigation: { + flexDirection: 'row', + gap: primitives.spacingLg, + }, + selectedDayText: { + fontWeight: primitives.typographyFontWeightSemiBold, + }, + week: { + flexDirection: 'row', + }, + weekday: { + flex: 1, + fontSize: primitives.typographyFontSizeXs, + fontWeight: primitives.typographyFontWeightSemiBold, + textAlign: 'center', + }, + }), + [], + ); diff --git a/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx b/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx new file mode 100644 index 0000000000..95c1134eba --- /dev/null +++ b/package/src/components/ScheduledMessages/ScheduleMessageSheet.tsx @@ -0,0 +1,244 @@ +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 { useScheduledTimeFormatter } from './hooks/useScheduledTimeFormatter'; + +import { ScheduleSheetHeader } from './ScheduleSheetHeader'; + +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 { 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 styles = useStyles(); + const color = disabled ? semantics.textDisabled : semantics.textPrimary; + 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, styles.option], + ); + + 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 } = useTranslationContext(); + const { formatPreset } = useScheduledTimeFormatter(); + const { + theme: { + scheduledMessages: { presetSheet }, + }, + } = useTheme(); + const styles = useStyles(); + + // 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 useStyles = () => + useMemo( + () => + StyleSheet.create({ + container: { + paddingBottom: primitives.spacingMd, + }, + option: { + alignItems: 'center', + borderRadius: primitives.radiusLg, + flexDirection: 'row', + gap: primitives.spacingSm, + minHeight: 48, + paddingHorizontal: primitives.spacingSm, + }, + optionLabel: { + flex: 1, + fontSize: primitives.typographyFontSizeMd, + lineHeight: primitives.typographyLineHeightNormal, + }, + options: { + paddingHorizontal: primitives.spacingXs, + }, + }), + [], + ); diff --git a/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx b/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx new file mode 100644 index 0000000000..84df1a56da --- /dev/null +++ b/package/src/components/ScheduledMessages/ScheduleSheetHeader.tsx @@ -0,0 +1,112 @@ +import React, { useCallback, useMemo } 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 { 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 styles = useStyles(); + + const renderConfirmIcon = useCallback( + (props: IconProps) => ( + + ), + [confirmDisabled, icons, semantics.textDisabled, semantics.textOnAccent], + ); + + return ( + + +