From d5d726117e8d64a45bbadc99c178624611f53883 Mon Sep 17 00:00:00 2001 From: martincupela Date: Wed, 11 Nov 2026 13:57:53 +0100 Subject: [PATCH 01/35] feat(ScheduledMessages): scheduled messages built on existing SDK patterns A leaner take on the scheduled-messages UI: list states through the ComponentContext list slots, InfiniteScrollPaginator, GlobalModal, ListLoadErrorIndicator, one composer preview, a ScheduledMessageListDialog slot, and the fixes from the PR review and the Figma review. Co-Authored-By: Claude Opus 5.5 --- ai-docs/ai-migration-v14-v15.md | 27 +- ai-docs/i18n-v15-migration.md | 14 +- ai-docs/v15-breaking-changes.md | 4 +- examples/vite/src/App.tsx | 9 +- .../src/ChatLayout/ChannelFreezeAction.tsx | 108 ++++ .../ChatLayout/ConfiguredChannelDetail.tsx | 35 +- ...ConfigurablePollCreationDialogControls.tsx | 157 ++++-- .../ConfigurableScheduledMessageItem.tsx | 21 + .../src/ComposerPreviews/previewSections.ts | 4 + examples/vite/src/i18n/de.ts | 6 + examples/vite/src/i18n/it.ts | 6 + examples/vite/src/icons.tsx | 15 + .../__tests__/ChatScheduledMessages.test.tsx | 134 +++++ src/components/Chat/hooks/useChat.ts | 2 + .../Dialog/styling/ContextMenu.scss | 16 +- .../EmptyStateIndicator.tsx | 21 +- src/components/Form/styling/TextInput.scss | 12 + src/components/Icons/icons.tsx | 32 ++ .../Loading/ListLoadErrorIndicator.tsx | 9 +- .../MessageComposerActions.tsx | 39 +- .../MessageComposerPreviews.defaults.tsx | 31 +- .../MessageComposerPreviews.tsx | 1 + .../MessageComposer/MessageComposerUI.tsx | 3 + .../hooks/useMessageComposerPreviewState.ts | 15 +- .../hooks/useMessageComposerSubmitFn.ts | 35 +- .../ScheduleMessageButton.tsx | 214 ++++++++ .../ScheduledMessages/ScheduleTimeDialog.tsx | 203 ++++++++ .../ScheduledMessageItem.tsx | 446 ++++++++++++++++ .../ScheduledMessageList.tsx | 223 ++++++++ .../ScheduledMessageListDialog.tsx | 123 +++++ .../ScheduledMessagePreview.tsx | 32 ++ .../ScheduledMessagesBanner.tsx | 144 ++++++ .../ScheduledMessagesNotice.tsx | 33 ++ .../__tests__/EditScheduledMessage.test.tsx | 155 ++++++ .../__tests__/ScheduleMessageButton.test.tsx | 451 +++++++++++++++++ .../ScheduledMessageActions.test.tsx | 394 +++++++++++++++ .../__tests__/ScheduledMessageList.test.tsx | 478 ++++++++++++++++++ .../ScheduledMessagesBanner.test.tsx | 429 ++++++++++++++++ .../ScheduledMessages/__tests__/utils.test.ts | 182 +++++++ .../ScheduledMessages/hooks/index.ts | 2 + .../hooks/useCanScheduleMessage.ts | 56 ++ .../hooks/useScheduledMessagePreview.ts | 55 ++ .../hooks/useScheduledMessages.ts | 88 ++++ src/components/ScheduledMessages/index.ts | 8 + .../styling/ScheduleMessageButton.scss | 50 ++ .../styling/ScheduleMessageDialog.scss | 74 +++ .../styling/ScheduledMessageActions.scss | 31 ++ .../styling/ScheduledMessageList.scss | 169 +++++++ .../styling/ScheduledMessagesBanner.scss | 47 ++ .../styling/ScheduledMessagesNotice.scss | 29 ++ .../ScheduledMessages/styling/index.scss | 6 + src/components/ScheduledMessages/utils.ts | 325 ++++++++++++ src/components/index.ts | 1 + src/context/ComponentContext.tsx | 21 + .../notifications/translators.ts | 36 ++ .../translatorsByNotificationType.ts | 11 + src/i18n/__tests__/Streami18n.test.ts | 6 +- src/i18n/__tests__/catalog.fixture.json | 92 ++++ ...uledMessageNotificationTranslators.test.ts | 183 +++++++ src/i18n/keys.ts | 92 ++++ src/i18n/runtimeDefaults.ts | 17 +- src/mock-builders/api/index.ts | 1 + src/mock-builders/api/scheduledMessages.ts | 50 ++ src/mock-builders/api/utils.ts | 2 +- src/mock-builders/event/index.ts | 1 + src/mock-builders/event/scheduledMessage.ts | 29 ++ src/mock-builders/generator/channel.ts | 4 + src/mock-builders/generator/index.ts | 1 + .../generator/scheduledMessage.ts | 28 + src/mock-builders/index.ts | 9 + src/mock-builders/utils.ts | 16 + src/plugins/ChannelDetail/ChannelDetail.tsx | 117 +++-- .../ChannelDetailSearchInput.tsx | 31 +- .../ScheduledMessagesView.tsx | 54 ++ .../__tests__/ScheduledMessagesView.test.tsx | 163 ++++++ .../Views/ScheduledMessagesView/index.ts | 1 + src/plugins/ChannelDetail/index.ts | 1 + .../styling/ScheduledMessagesView.scss | 20 + src/plugins/ChannelDetail/styling/index.scss | 1 + src/styling/index.scss | 1 + 80 files changed, 6047 insertions(+), 145 deletions(-) create mode 100644 examples/vite/src/ChatLayout/ChannelFreezeAction.tsx create mode 100644 examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx create mode 100644 src/components/Chat/__tests__/ChatScheduledMessages.test.tsx create mode 100644 src/components/ScheduledMessages/ScheduleMessageButton.tsx create mode 100644 src/components/ScheduledMessages/ScheduleTimeDialog.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessageItem.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessageList.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessageListDialog.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessagePreview.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessagesBanner.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessagesNotice.tsx create mode 100644 src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx create mode 100644 src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx create mode 100644 src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx create mode 100644 src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx create mode 100644 src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx create mode 100644 src/components/ScheduledMessages/__tests__/utils.test.ts create mode 100644 src/components/ScheduledMessages/hooks/index.ts create mode 100644 src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts create mode 100644 src/components/ScheduledMessages/hooks/useScheduledMessagePreview.ts create mode 100644 src/components/ScheduledMessages/hooks/useScheduledMessages.ts create mode 100644 src/components/ScheduledMessages/index.ts create mode 100644 src/components/ScheduledMessages/styling/ScheduleMessageButton.scss create mode 100644 src/components/ScheduledMessages/styling/ScheduleMessageDialog.scss create mode 100644 src/components/ScheduledMessages/styling/ScheduledMessageActions.scss create mode 100644 src/components/ScheduledMessages/styling/ScheduledMessageList.scss create mode 100644 src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss create mode 100644 src/components/ScheduledMessages/styling/ScheduledMessagesNotice.scss create mode 100644 src/components/ScheduledMessages/styling/index.scss create mode 100644 src/components/ScheduledMessages/utils.ts create mode 100644 src/i18n/__tests__/scheduledMessageNotificationTranslators.test.ts create mode 100644 src/mock-builders/api/scheduledMessages.ts create mode 100644 src/mock-builders/event/scheduledMessage.ts create mode 100644 src/mock-builders/generator/scheduledMessage.ts create mode 100644 src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx create mode 100644 src/plugins/ChannelDetail/Views/ScheduledMessagesView/__tests__/ScheduledMessagesView.test.tsx create mode 100644 src/plugins/ChannelDetail/Views/ScheduledMessagesView/index.ts create mode 100644 src/plugins/ChannelDetail/styling/ScheduledMessagesView.scss diff --git a/ai-docs/ai-migration-v14-v15.md b/ai-docs/ai-migration-v14-v15.md index 013e8db5a9..6c1f0b13f2 100644 --- a/ai-docs/ai-migration-v14-v15.md +++ b/ai-docs/ai-migration-v14-v15.md @@ -1692,12 +1692,7 @@ Where you pass the props depends on who renders the header: Both headers are exported. -To keep showing the content only while something is open beside the list (a sidebar toggle, for example), make it return `null` otherwise. Read the workspace from `useWorkspaceNavigation()`: - -- `openChannels` / `openThreads` list the channels and threads that the workspace's panels were opened with. Something opened over another item in the same panel (stacked) is not in them. In a workspace whose panels open with channels and threads only, a stacked item always sits over one that is in the lists, so "something is open" is either list being non-empty; `openThreads` alone misses a thread stacked over a channel. -- A panel opened with another kind, such as a `userProfile` panel, is in neither list, even with a channel stacked over it. If your layout opens such panels, check the layout instead: `useLayoutViewState()` from `stream-chat-react/slot-layout` returns each slot's binding (`slotBindings`) and stacked layers (`slotLayers`). -- To ask whether a given channel or thread is on screen, use `isChannelActive(cid)` / `isThreadActive(threadId)`, which follow what each panel shows. -- `ChatView` (or your own `WorkspaceNavigationProvider`, [section 4](#4-selecting-channels-and-opening-threads-workspace-navigation)) fills all of these. Without one the lists stay empty, so gate on your own selection state instead. +To keep the v14 behavior of showing the content only next to an open channel or thread (a sidebar toggle, for example), make the content return `null` otherwise: read `openChannels` / `openThreads` from `useWorkspaceNavigation()`. `ChatView` (or your own `WorkspaceNavigationProvider`, [section 4](#4-selecting-channels-and-opening-threads-workspace-navigation)) fills these lists; without one they stay empty, so gate on your own selection state instead. ```tsx // v14 @@ -1715,18 +1710,24 @@ import { // `SidebarToggle` stands for a control of your own. const SidebarToggle = () => ; -// Shown only while a channel or thread is open beside the list. -const SidebarToggleWhileContentOpen = () => { - const { openChannels, openThreads } = useWorkspaceNavigation(); - return openChannels.length > 0 || openThreads.length > 0 ? : null; +// Shown only while a channel is open, as in v14. +const SidebarToggleWhileChannelOpen = () => { + const { openChannels } = useWorkspaceNavigation(); + return openChannels.length > 0 ? : null; +}; + +// Shown only while a thread is open, as in v14. +const SidebarToggleWhileThreadOpen = () => { + const { openThreads } = useWorkspaceNavigation(); + return openThreads.length > 0 ? : null; }; const ChannelListHeaderWithToggle = () => ( - + ); const ThreadListHeaderWithToggle = () => ( - + ); // Declared once, so WithComponents gets the same object on every render. @@ -3601,7 +3602,7 @@ export const RemoveButton = ({ label }: { label: string }) => { }; ``` -Four formatter keys carry English day words inside their `calendarFormats` (`timestamp.DateSeparator`, `timestamp.ReminderNotification`, `timestamp.ChannelPreviewTimestamp`, `timestamp.ChannelDetailPinnedMessageTimestamp`) and must be overridden to translate Today / Tomorrow / Yesterday / Last; `dayjsLocaleConfigForLanguage` does not reach them. +Eight formatter keys carry English words inside their formats (`timestamp.DateSeparator`, `timestamp.ReminderNotification`, `timestamp.ChannelPreviewTimestamp`, `timestamp.ChannelDetailPinnedMessageTimestamp`, `timestamp.ScheduledMessageConfirmation`, `timestamp.ScheduledMessageGroup`, `timestamp.ScheduledMessageSendTime`, `timestamp.SchedulePreset`) and must be overridden to translate Today / Tomorrow / Yesterday / Last / at; `dayjsLocaleConfigForLanguage` does not reach them. --- diff --git a/ai-docs/i18n-v15-migration.md b/ai-docs/i18n-v15-migration.md index 04d88c399d..96c1c09281 100644 --- a/ai-docs/i18n-v15-migration.md +++ b/ai-docs/i18n-v15-migration.md @@ -174,11 +174,11 @@ These v14 keys (from `src/i18n/en.json` at `v14.10.0`, plural suffixes folded) h yarn i18n:export ``` - That writes `en.json` in the repo root with the 619 translatable keys. The 14 `timestamp.*`, + That writes `en.json` in the repo root with the 716 translatable keys. The 20 `timestamp.*`, `duration.*` and `translationBuilderTopic.*` entries are left out on purpose — they are dayjs and i18next expressions, and a TMS that "translates" `{{value, notification}}` breaks notifications - outright. Four of them do carry English day words; those are handled by overriding the key, see - [Date and time](#date-and-time). Pass `--all` for the complete 633-key catalog. + outright. Eight of them do carry English words; those are handled by overriding the key, see + [Date and time](#date-and-time). Pass `--all` for the complete 736-key catalog. [`ai-docs/i18n-v15-key-map.json`](https://github.com/GetStream/stream-chat-react/blob/master/ai-docs/i18n-v15-key-map.json) also lists every key, alongside the v14 string it replaced. @@ -243,7 +243,7 @@ formatter expressions, not text: "timestamp.MessageTimestamp": "{{ timestamp | timestampFormatter(calendar: false; format: HH:mm) }}" ``` -Most of them only need overriding to change _how_ a date is formatted. **Four of them also carry +Most of them only need overriding to change _how_ a date is formatted. **Eight of them also carry English words**, because dayjs takes the calendar wording as part of the format string: | Key | English baked into `calendarFormats` | @@ -252,8 +252,12 @@ English words**, because dayjs takes the calendar wording as part of the format | `timestamp.ReminderNotification` | `Today`, `Tomorrow`, `Yesterday`, `Last`, `at` | | `timestamp.ChannelPreviewTimestamp` | `Yesterday` | | `timestamp.ChannelDetailPinnedMessageTimestamp` | `Yesterday` | +| `timestamp.ScheduledMessageConfirmation` | `at` | +| `timestamp.ScheduledMessageGroup` | `Today`, `Tomorrow`, `Yesterday`, `Last` | +| `timestamp.ScheduledMessageSendTime` | `at` | +| `timestamp.SchedulePreset` | `Today`, `Tomorrow`, `Yesterday`, `Last`, `at` | -Translating those four means overriding the key itself — `dayjsLocaleConfigForLanguage` does not +Translating those eight means overriding the key itself — `dayjsLocaleConfigForLanguage` does not reach them. See [Date and time](#date-and-time) for the how and why. `relativeTime.*` ("Today", "{{ count }}d ago") is ordinary copy and translates normally, as does diff --git a/ai-docs/v15-breaking-changes.md b/ai-docs/v15-breaking-changes.md index b2203893a9..5ffe36ef95 100644 --- a/ai-docs/v15-breaking-changes.md +++ b/ai-docs/v15-breaking-changes.md @@ -2315,12 +2315,12 @@ const CustomThreadHeader = () => { - `ChannelListHeader` and `ThreadListHeader` take `StartContent` (before the title) and `EndContent` (after the title), as `ChannelHeader` / `ThreadHeader` do. Neither has a default. Types: `ChannelListHeaderProps`, `ThreadListHeaderProps`. - where the SDK renders the header, the props go through the header's override key: register a component that renders the default header with them. `ChannelListHeader` is read by `ChannelNavigation`; `ThreadListHeader` is a new key, read by `ThreadList`. `ThreadListHeader` is now exported. - where the app renders the header itself (for example `ChannelListHeader` above a standalone `ChannelList`), it passes the props directly; the override key does not reach that header. - - to show the content only while something is open beside the list, read `useWorkspaceNavigation()` in the content component and return `null` while both `openChannels` and `openThreads` are empty. The lists hold the channels and threads the workspace's panels were opened with: an item stacked over another one in a panel is not in them. Where panels open with channels and threads only, a stacked item always sits over one that is, so checking one list alone misses it (a thread stacked over a channel is not in `openThreads`). A panel opened with another kind (a `userProfile` panel, even with a channel stacked over it) is in neither list; such layouts check `useLayoutViewState()` (`slotBindings`, `slotLayers`) from `stream-chat-react/slot-layout` instead. Whether a given channel or thread is on screen is `isChannelActive(cid)` / `isThreadActive(threadId)`. `ChatView` or an app's own `WorkspaceNavigationProvider` fills these; without one the lists stay empty, so an app without either gates on its own selection state. + - to keep the v14 gate, read `useWorkspaceNavigation().openChannels` / `.openThreads` in the content component and return `null` while it is empty. `ChatView` or an app's own `WorkspaceNavigationProvider` fills these lists; without one they stay empty, so an app without either gates on its own selection state. - Evidence: - `release-v14:src/components/ChannelList/ChannelListHeader.tsx:15` `{channel && HeaderEndContent && }`; `release-v14:src/components/Threads/ThreadList/ThreadListHeader.tsx:12` `{activeThread && HeaderEndContent && }`; `release-v14:src/context/ComponentContext.tsx:303` - `master:src/components/ChannelList/ChannelListHeader.tsx` and `master:src/components/Threads/ThreadList/ThreadListHeader.tsx` (`StartContent` / `EndContent` props); `master:src/components/Threads/ThreadList/ThreadList.tsx` reads `ThreadListHeader` from `useComponentContext()`; `master:src/context/ComponentContext.tsx` `ThreadListHeader?` - ticket: REACT-1449 - - examples: `examples/vite/src/ChatLayout/SwitchableChannelNavigation.tsx` passes `EndContent={SidebarToggleWhileContentOpen}` to `ChannelListHeader`; `examples/vite/src/App.tsx` registers `ThreadListHeaderWithSidebarToggle` (`examples/vite/src/Sidebar/HeaderContent.tsx`) as `ThreadListHeader` + - examples: `examples/vite/src/ChatLayout/SwitchableChannelNavigation.tsx` passes `EndContent={SidebarToggleWhileChannelOpen}` to `ChannelListHeader`; `examples/vite/src/App.tsx` registers `ThreadListHeaderWithSidebarToggle` (`examples/vite/src/Sidebar/HeaderContent.tsx`) as `ThreadListHeader` - Docs impact: - `03-ui/03-components/01-channel-list-ui.md`, `03-ui/03-components/08-thread-list-ui.md`, `03-ui/03-components/12-overriding-components.md`, `06-component-reference/02-channel/04-componentcontext.md`, `06-component-reference/07-thread-list/01-threadlist.md`, `05-ui-cookbooks/10-layout/04-collapsible-sidebar.md`, `05-ui-cookbooks/03-search/03-mentions-inbox.md`, `08-release-guides/01-upgrade-to-v15.md` - Example needed: yes (the guide section has one) diff --git a/examples/vite/src/App.tsx b/examples/vite/src/App.tsx index bb82ec8324..f905abd288 100644 --- a/examples/vite/src/App.tsx +++ b/examples/vite/src/App.tsx @@ -22,8 +22,8 @@ import { isVoiceRecordingAttachment, MessageSearchSource, POLL_ONLY_COMPOSITION_MIDDLEWARE_ID, + SCHEDULED_MESSAGE_COMPOSITION_MIDDLEWARE_ID, SearchController, - USER_DATA_INJECTION_MIDDLEWARE_ID, UserSearchSource, } from 'stream-chat'; import { @@ -101,6 +101,7 @@ import { ConfigurableStartRecordingAudioButton, } from './ComposerPreviews/ConfigurableComposerPreviews.tsx'; import { ConfigurablePollCreationDialogControls } from './ComposerPreviews/ConfigurablePollCreationDialogControls.tsx'; +import { ConfigurableScheduledMessageItem } from './ComposerPreviews/ConfigurableScheduledMessageItem.tsx'; import { ConfigurableMessageBubbleContent } from './MessageBubble/ConfigurableMessageBubbleContent.tsx'; import { applySimulatedListQueryFailures, StreamDebugHandles } from './Debug'; import { @@ -582,11 +583,12 @@ const App = () => { // While the Poll preview shows, the poll dialog attaches the poll to the message being // composed (ConfigurablePollCreationDialogControls). Without the poll-only step the poll is // sent with the text and attachments rather than as a message of its own, and the composer - // clears after the send. Restored when the preview is turned off, since this setup re-runs. + // clears after the send. Restored when the preview is turned off, since this setup re-runs: + // after the scheduling check, where the SDK puts it, so a blocked schedule still stops first. if (pollDisabled) { composer.compositionMiddlewareExecutor.insert({ middleware: [createPollOnlyCompositionMiddleware(composer)], - position: { after: USER_DATA_INJECTION_MIDDLEWARE_ID }, + position: { after: SCHEDULED_MESSAGE_COMPOSITION_MIDDLEWARE_ID }, unique: true, }); } else { @@ -699,6 +701,7 @@ const App = () => { MessageBubbleContent: ConfigurableMessageBubbleContent, MessageComposerPreviews: ConfigurableComposerPreviews, PollCreationDialogControls: ConfigurablePollCreationDialogControls, + ScheduledMessageItem: ConfigurableScheduledMessageItem, StartRecordingAudioButton: ConfigurableStartRecordingAudioButton, MessageUI: InlineEditableMessage, ...messageUiOverrides, diff --git a/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx new file mode 100644 index 0000000000..536b015c4a --- /dev/null +++ b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx @@ -0,0 +1,108 @@ +import { useEffect, useMemo, useState } from 'react'; +import type { OwnCapabilitiesState } from 'stream-chat'; +import { + asDynamicKey, + ListItemLayout, + Switch, + useNotificationApi, + useStateStore, + useTranslationContext, +} from 'stream-chat-react'; +import { + type ChannelManagementActionItem, + defaultChannelManagementActionSet, + useChannelDetailContext, +} from 'stream-chat-react/channel-detail'; + +import { IconLock } from '../icons'; + +const toError = (error: unknown) => + error instanceof Error ? error : new Error('An unknown error occurred'); + +const selectCanFreeze = ({ ownCapabilities }: OwnCapabilitiesState) => ({ + canFreeze: !!ownCapabilities?.includes('freeze-channel'), +}); + +const FreezeActionIcon = () => ( + +); + +/** + * Freezes or unfreezes the channel, for a user whose role has the `UpdateChannelFrozen` + * permission. A frozen channel takes no new messages, which is also how a scheduled message + * can be made to fail with `channel_frozen`. The SDK ships no freeze action; it is demo code. + */ +const ChannelFreezeAction = () => { + const { channel } = useChannelDetailContext(); + const { addNotification } = useNotificationApi(); + const { t } = useTranslationContext(); + const { canFreeze } = useStateStore(channel.state, selectCanFreeze); + const [frozen, setFrozen] = useState(!!channel.data?.frozen); + + // follows a freeze made elsewhere, such as in the dashboard + useEffect(() => { + setFrozen(!!channel.data?.frozen); + const { unsubscribe } = channel.on('channel.updated', ({ channel: data }) => { + if (data?.frozen !== undefined) setFrozen(data.frozen); + }); + return unsubscribe; + }, [channel]); + + const TrailingSlot = useMemo(() => { + function ChannelFreezeSwitch() { + return ; + } + return ChannelFreezeSwitch; + }, [frozen]); + + if (!canFreeze) return null; + + const toggleFrozen = async () => { + const nextFrozen = !frozen; + setFrozen(nextFrozen); + try { + await channel.updatePartial({ set: { frozen: nextFrozen } }); + } catch (error) { + setFrozen(!nextFrozen); + addNotification({ + context: { channel }, + emitter: 'ChannelFreezeAction', + error: toError(error), + message: nextFrozen + ? t( + asDynamicKey('viteExample.channelFreeze.freezeError.text'), + "Couldn't freeze the channel", + ) + : t( + asDynamicKey('viteExample.channelFreeze.unfreezeError.text'), + "Couldn't unfreeze the channel", + ), + severity: 'error', + type: 'api:channel:freeze:failed', + }); + } + }; + + return ( + + ); +}; + +/** The SDK's channel actions with the freeze switch after Mute chat. */ +export const channelManagementActionSetWithFreeze: ChannelManagementActionItem[] = + defaultChannelManagementActionSet.flatMap((action) => + action.type === 'muteChannel' + ? [action, { Component: ChannelFreezeAction, type: 'freezeChannel' }] + : [action], + ); diff --git a/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx b/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx index 6f3fc6d9d9..b9d1fcc7df 100644 --- a/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx +++ b/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx @@ -5,6 +5,7 @@ import { type AvatarWithChannelDetailProps, ChannelDetail, type ChannelDetailProps, + ChannelManagementView, ChannelMembersView, type ChannelMembersViewModes, defaultChannelDetailSections, @@ -14,8 +15,16 @@ import { import { useAppSettingsSelector } from '../AppSettings/state'; import { getChannelMembersHeaderActionSet } from '../AppSettings/tabs/ChannelDetail'; +import { channelManagementActionSetWithFreeze } from './ChannelFreezeAction'; import { ChannelMembersRemoveView } from './ChannelMembersRemoveView'; +const ChannelManagementViewWithFreeze = (props: SectionNavigatorSectionContentProps) => ( + +); + const ChannelMembersRemoveTitle = () => { const { t } = useTranslationContext(); return ( @@ -43,18 +52,20 @@ const ConfiguredChannelDetail = (props: ChannelDetailProps) => { const sections = useMemo( () => [ ...defaultChannelDetailSections.map((section) => - section.id !== 'channel-members' - ? section - : { - ...section, - SectionContent: (sectionProps: SectionNavigatorSectionContentProps) => ( - - ), - }, + section.id === 'channel-info' + ? { ...section, SectionContent: ChannelManagementViewWithFreeze } + : section.id !== 'channel-members' + ? section + : { + ...section, + SectionContent: (sectionProps: SectionNavigatorSectionContentProps) => ( + + ), + }, ), ], [headerActionSet], diff --git a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx index a75562ef2f..e5425e1812 100644 --- a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx +++ b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx @@ -1,11 +1,18 @@ +import { useMemo, useState } from 'react'; import { flushSync } from 'react-dom'; +import { dateToNs, type LocalMessage, toScheduledMessagePreview } from 'stream-chat'; import { asDynamicKey, + GlobalModal, + IconClock, IconPoll, PollCreationDialogControls, type PollCreationDialogControlsProps, Prompt, + ScheduleTimeDialog, useCanCreatePoll, + useCanScheduleMessage, + useChatContext, useMessageComposerContext, useMessageComposerController, useTranslationContext, @@ -13,50 +20,134 @@ import { import { useAppSettingsSelector } from '../AppSettings'; +/** The message being composed with the poll the dialog is creating, to preview in the time dialog. */ +const usePollMessagePreview = (): LocalMessage => { + const { client } = useChatContext(); + const messageComposer = useMessageComposerController(); + const { name } = messageComposer.pollComposer.state.getLatestValue().data; + const { text } = messageComposer.textComposer; + const { attachments } = messageComposer.attachmentManager; + return useMemo(() => { + const now = dateToNs(new Date()); + const preview = toScheduledMessagePreview({ + cid: messageComposer.channel.cid, + created_at: now, + id: messageComposer.id, + message: { attachments, custom: {}, text }, + scheduled_at: now, + status: 'scheduled', + updated_at: now, + user: { id: client.userID ?? '', ...client.user } as never, + }); + return { ...preview, poll: { name } as LocalMessage['poll'] }; + }, [attachments, client, messageComposer, name, text]); +}; + /** * Creates the poll without sending it: the poll waits in the composer (`state.pollId`), shows in - * its Poll preview, and goes out with the next message's text and attachments. + * its Poll preview, and goes out with the next message's text and attachments. Schedule does the + * same and schedules that message right away; its time is picked first and only then is the poll + * created, so cancelling the time dialog leaves nothing behind. */ const AttachPollControls = ({ close }: PollCreationDialogControlsProps) => { const { t } = useTranslationContext(); const { textareaRef } = useMessageComposerContext(); const messageComposer = useMessageComposerController(); const canCreatePoll = useCanCreatePoll(); + const canSchedule = useCanScheduleMessage(); + const [isPickingTime, setIsPickingTime] = useState(false); + const previewMessage = usePollMessagePreview(); + + // As in the default controls: close and focus the composer synchronously, so focus does not + // blip through the attachment selector's trigger. + const closeAndFocusComposer = () => { + flushSync(() => close()); + textareaRef?.current?.focus(); + }; + + // rejects to keep the time dialog open, which then says the scheduling failed + const schedulePoll = async (scheduledAt: Date) => { + // a poll made by an earlier, failed attempt is reused + if (!messageComposer.pollId) await messageComposer.createPoll(); + if (!messageComposer.pollId) throw new Error('The poll was not created'); + const { error, status } = await messageComposer.schedule(scheduledAt); + if (status !== 'scheduled' && status !== 'sent') { + throw error ?? new Error(`The poll was not scheduled: ${status}`); + } + setIsPickingTime(false); + closeAndFocusComposer(); + }; return ( - - - - {t('common.cancel.label', 'Cancel')} - - { - // As in the default controls: close and focus the composer synchronously, so focus - // does not blip through the attachment selector's trigger. - flushSync(() => close()); - textareaRef?.current?.focus(); - try { - await messageComposer.createPoll(); - } catch { - // `createPoll()` already reported the failure as a notification. - } - }} - type='submit' - > - - {t( - asDynamicKey('viteExample.pollCreationDialog.attachPoll.text'), - 'Attach poll', + <> + + + + {t('common.cancel.label', 'Cancel')} + + {canSchedule && ( + setIsPickingTime(true)} + type='button' + > + + {t( + asDynamicKey('viteExample.pollCreationDialog.schedulePoll.text'), + 'Schedule', + )} + )} - - - + { + closeAndFocusComposer(); + try { + await messageComposer.createPoll(); + } catch { + // `createPoll()` already reported the failure as a notification. + } + }} + type='submit' + > + + {t( + asDynamicKey('viteExample.pollCreationDialog.attachPoll.text'), + 'Attach poll', + )} + + + + setIsPickingTime(false)} + open={isPickingTime} + > + {isPickingTime && ( + setIsPickingTime(false)} + errorMessage={t( + asDynamicKey('viteExample.pollCreationDialog.schedulePollFailed.text'), + "Couldn't schedule the poll. Try again", + )} + previewMessage={previewMessage} + submit={schedulePoll} + title={t( + asDynamicKey('viteExample.pollCreationDialog.schedulePollTitle.text'), + 'Schedule poll', + )} + /> + )} + + ); }; diff --git a/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx new file mode 100644 index 0000000000..4f270b5a20 --- /dev/null +++ b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx @@ -0,0 +1,21 @@ +import { ScheduledMessageItem, type ScheduledMessageItemProps } from 'stream-chat-react'; + +import { useAppSettingsSelector } from '../AppSettings'; + +/** + * Without the Scheduled message preview (Settings -> Composer), the composer could not show or + * cancel a scheduled message opened in it, so the list offers no Edit or Retry. + */ +export const ConfigurableScheduledMessageItem = ({ + onEdit, + ...props +}: ScheduledMessageItemProps) => { + const { disabledPreviewSections } = useAppSettingsSelector((state) => state.composer); + + return ( + + ); +}; diff --git a/examples/vite/src/ComposerPreviews/previewSections.ts b/examples/vite/src/ComposerPreviews/previewSections.ts index db97ca138e..c362971984 100644 --- a/examples/vite/src/ComposerPreviews/previewSections.ts +++ b/examples/vite/src/ComposerPreviews/previewSections.ts @@ -48,6 +48,10 @@ export const PREVIEW_SECTION_INFO: Record, ); + +/** The design system's `core/line/lock` icon, for the channel freeze switch. */ +export const IconLock = createIcon( + 'IconLock', + <> + + + , +); diff --git a/src/components/Chat/__tests__/ChatScheduledMessages.test.tsx b/src/components/Chat/__tests__/ChatScheduledMessages.test.tsx new file mode 100644 index 0000000000..db882690fa --- /dev/null +++ b/src/components/Chat/__tests__/ChatScheduledMessages.test.tsx @@ -0,0 +1,134 @@ +import React, { StrictMode } from 'react'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import { ScheduledMessagePaginator } from 'stream-chat'; +import type { StreamChat } from 'stream-chat'; + +import { Chat } from '..'; +import { + dispatchScheduledMessageEvent, + generateScheduledMessage, + getTestClientWithUser, + setWSConnectionStatus, +} from '../../../mock-builders'; + +const renderChat = async (client: StreamChat, { strict = false } = {}) => { + const chat = {null}; + + let result!: ReturnType; + await act(() => { + result = render(strict ? {chat} : chat); + }); + return result; +}; + +/** A list registered with the client, the only kind the scheduled message events reach. */ +const registerScheduledMessageList = (client: StreamChat) => { + const paginator = new ScheduledMessagePaginator({ client }); + client.scheduledMessagePaginators.insertPaginator({ paginator }); + return paginator; +}; + +const reconnect = async (client: StreamChat) => { + await act(() => { + setWSConnectionStatus(client, false); + setWSConnectionStatus(client, true); + }); +}; + +describe('Chat scheduled messages wiring', () => { + afterEach(() => { + cleanup(); + }); + + it('registers the scheduled message subscriptions while mounted', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + + await renderChat(client); + + expect(client.scheduledMessagePaginators.hasSubscriptions).toBe(true); + }); + + it('does not query the scheduled messages on its own', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + + await renderChat(client); + await reconnect(client); + + expect(client.queryScheduledMessages).not.toHaveBeenCalled(); + }); + + it('subscribes once under StrictMode', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + const scheduledMessage = generateScheduledMessage(); + const ingest = vi.spyOn(client.scheduledMessagePaginators, 'ingest'); + + await renderChat(client, { strict: true }); + act(() => { + dispatchScheduledMessageEvent({ + client, + scheduledMessage, + type: 'scheduled_message.created', + }); + }); + + await waitFor(() => expect(ingest).toHaveBeenCalledTimes(1)); + }); + + it('keeps the store in sync from events while mounted', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + const scheduledMessage = generateScheduledMessage(); + const list = registerScheduledMessageList(client); + await renderChat(client); + + act(() => { + dispatchScheduledMessageEvent({ + client, + scheduledMessage, + type: 'scheduled_message.created', + }); + }); + + await waitFor(() => expect(list.items).toEqual([scheduledMessage])); + }); + + // the banner turns into the failure; the send happens later, apart from any user action + it('does not notify about a scheduled message that failed to send', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + await renderChat(client); + + act(() => { + dispatchScheduledMessageEvent({ + client, + scheduledMessage: generateScheduledMessage({ + failure_reason: 'channel_frozen', + status: 'failed', + }), + type: 'scheduled_message.failed', + }); + }); + + expect(client.notifications.store.getLatestValue().notifications).toEqual([]); + }); + + it('unsubscribes on unmount', async () => { + const client = await getTestClientWithUser({ id: 'user-1' }); + const scheduledMessage = generateScheduledMessage(); + const list = registerScheduledMessageList(client); + const { unmount } = await renderChat(client); + + unmount(); + act(() => { + dispatchScheduledMessageEvent({ + client, + scheduledMessage, + type: 'scheduled_message.created', + }); + }); + await client.scheduledMessagePaginators.pipelines + .get('scheduled_message.created') + ?.drain(); + + expect(client.scheduledMessagePaginators.hasSubscriptions).toBe(false); + expect(list.items).toBeUndefined(); + }); +}); diff --git a/src/components/Chat/hooks/useChat.ts b/src/components/Chat/hooks/useChat.ts index 207ea64337..5702e4e3e3 100644 --- a/src/components/Chat/hooks/useChat.ts +++ b/src/components/Chat/hooks/useChat.ts @@ -43,6 +43,7 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.registerSubscriptions(); client.reminders.registerSubscriptions(); client.reminders.initTimers(); + client.scheduledMessagePaginators.registerSubscriptions(); return () => { releaseChannelManager(); @@ -50,6 +51,7 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.unregisterSubscriptions(); client.reminders.unregisterSubscriptions(); client.reminders.clearTimers(); + client.scheduledMessagePaginators.unregisterSubscriptions(); }; }, [client]); diff --git a/src/components/Dialog/styling/ContextMenu.scss b/src/components/Dialog/styling/ContextMenu.scss index df8efd596c..2bf16e0b03 100644 --- a/src/components/Dialog/styling/ContextMenu.scss +++ b/src/components/Dialog/styling/ContextMenu.scss @@ -94,6 +94,14 @@ font: var(--str-chat__font-caption-emphasis); } + // full width, through the menu's padding + .str-chat__context-menu__separator { + height: 1px; + margin-block: var(--str-chat__spacing-xxs); + margin-inline: calc(-1 * var(--str-chat__spacing-xxs)); + background-color: var(--str-chat__border-core-subtle); + } + .str-chat__context-menu__back-button { @include utils.button-reset; display: flex; @@ -194,11 +202,11 @@ } } - &:hover:not(:disabled) { + &:hover:not(:disabled, [aria-disabled='true']) { background-color: var(--str-chat__dialog-menu-button-hover-background-color); } - &:active:not(:disabled) { + &:active:not(:disabled, [aria-disabled='true']) { background-color: var(--str-chat__background-utility-pressed); } @@ -206,7 +214,9 @@ background-color: transparent; } - &:disabled { + // `aria-disabled` keeps the item focusable, so its reason can be read + &:disabled, + &[aria-disabled='true'] { background-color: transparent; color: var(--str-chat__text-disabled); cursor: default; diff --git a/src/components/EmptyStateIndicator/EmptyStateIndicator.tsx b/src/components/EmptyStateIndicator/EmptyStateIndicator.tsx index 0eccc27b81..6014bfb64f 100644 --- a/src/components/EmptyStateIndicator/EmptyStateIndicator.tsx +++ b/src/components/EmptyStateIndicator/EmptyStateIndicator.tsx @@ -6,7 +6,7 @@ import { asDynamicKey } from '../../i18n/utils'; export type EmptyStateIndicatorProps = { /** Which list is empty. A 'thread' list renders nothing. */ - listType?: 'channel' | 'message' | 'thread'; + listType?: 'channel' | 'message' | 'scheduled-message' | 'thread'; messageText?: string; }; @@ -14,7 +14,7 @@ const UnMemoizedEmptyStateIndicator = (props: EmptyStateIndicatorProps) => { const { listType, messageText } = props; const { t } = useTranslationContext(); - const { IconMessageBubble, IconMessageBubbles } = useComponentContextIcons(); + const { IconClock, IconMessageBubble, IconMessageBubbles } = useComponentContextIcons(); if (listType === 'thread') return null; @@ -50,6 +50,23 @@ const UnMemoizedEmptyStateIndicator = (props: EmptyStateIndicatorProps) => { ); } + if (listType === 'scheduled-message') { + return ( +
+ +

+ {t('scheduledMessages.noScheduledMessages', 'No scheduled messages')} +

+

+ {t( + 'scheduledMessages.clickTheArrowNextToTheSendButton', + 'Click the arrow next to the send button in a channel to schedule a message.', + )} +

+
+ ); + } + return

{t('emptyState.indicator.noItemsExist.text', 'No items exist')}

; }; diff --git a/src/components/Form/styling/TextInput.scss b/src/components/Form/styling/TextInput.scss index bcf0ea0d46..8e2a5a22bd 100644 --- a/src/components/Form/styling/TextInput.scss +++ b/src/components/Form/styling/TextInput.scss @@ -135,6 +135,18 @@ box-shadow: none; } +// Rendered while the field is empty too, so the field keeps its height; hidden, it can be neither +// focused nor clicked +.str-chat__form-text-input__clear-button--hidden { + visibility: hidden; +} + +// A field with its own clear button drops the native one, which the keyboard cannot reach +.str-chat__form-text-input__control-row:has(.str-chat__form-text-input__trailing) + .str-chat__form-text-input__input::-webkit-search-cancel-button { + display: none; +} + .str-chat__form-text-input.str-chat__form-text-input--disabled .str-chat__form-text-input__input { color: var(--str-chat__input-text-placeholder); diff --git a/src/components/Icons/icons.tsx b/src/components/Icons/icons.tsx index c0687d94f5..3e260ee0d4 100644 --- a/src/components/Icons/icons.tsx +++ b/src/components/Icons/icons.tsx @@ -289,6 +289,14 @@ export const IconCheckmark = createIcon( />, ); +export const IconCaretDown = createIcon( + 'IconCaretDown', + , +); + export const IconChevronDown = createIcon( 'IconChevronDown', , ); +export const IconChevronUp = createIcon( + 'IconChevronUp', + , +); + export const IconChevronLeft = createIcon( 'IconChevronLeft', , ); +export const IconCalendar = createIcon( + 'IconCalendar', + , +); + export const IconClock = createIcon( 'IconClock', ({ - editedMessage, +const messageComposerStateSelector = (state: MessageComposerState) => ({ + isEditing: isComposerEditing(state), }); const textComposerStateSelector = ({ command, text }: TextComposerState) => ({ @@ -41,11 +44,13 @@ export const MessageComposerActions = () => { const messageComposer = useMessageComposerController(); const { CooldownTimer = DefaultCooldownTimer, + ScheduleMessageButton: ScheduleMessageButtonOverride, SendButton, StopAIGenerationButton: StopAIGenerationButtonOverride, } = useComponentContext(); - const { editedMessage } = useStateStore( + const canScheduleMessage = useCanScheduleMessage(); + const { isEditing } = useStateStore( messageComposer.state, messageComposerStateSelector, ); @@ -75,6 +80,19 @@ export const MessageComposerActions = () => { // Accounts for an iOS requirement, see https://bugs.webkit.org/show_bug.cgi?id=252303 const recordingEnabled = !!(recordingController.recorder && navigator.mediaDevices); + const ScheduleMessageButton = + ScheduleMessageButtonOverride === undefined + ? DefaultScheduleMessageButton + : ScheduleMessageButtonOverride; + + const sendButton = SendButton ? ( + + ) : ( + + {isEditing || command ? : } + + ); + // One control fills the slot, first match wins. While the AI is answering, stopping it is the // only useful action, so the stop button outranks everything else, `hideSendButton` included. let content: React.ReactNode; @@ -84,16 +102,17 @@ export const MessageComposerActions = () => { return null; } else if (isCooldownActive) { content = ; - } else if (contentIsEmpty && !editedMessage && !command && recordingEnabled) { + } else if (contentIsEmpty && !isEditing && !command && recordingEnabled) { content = ; - } else if (SendButton) { - content = ; - } else { + } else if (canScheduleMessage && ScheduleMessageButton) { content = ( - - {editedMessage || command ? : } - +
+ {sendButton} + +
); + } else { + content = sendButton; } return
{content}
; diff --git a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx index c880b5b30a..bbd1081490 100644 --- a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx +++ b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx @@ -20,11 +20,16 @@ import { LinkPreviewList as DefaultLinkPreviewList } from './LinkPreviewList'; import type { MessageComposerPreviewSetItem } from './MessageComposerPreviews'; import { restorePreEditSnapshot } from './preEditSnapshot'; import { QuotedMessagePreview as DefaultQuotedMessagePreview } from './QuotedMessagePreview'; +import { ScheduledMessagePreview as DefaultScheduledMessagePreview } from '../ScheduledMessages/ScheduledMessagePreview'; const editedMessageSelector = ({ editedMessage }: MessageComposerState) => ({ editedMessage, }); +const scheduledMessageSelector = ({ editedScheduledMessage }: MessageComposerState) => ({ + editedScheduledMessage, +}); + const locationSelector = ({ location }: LocationComposerState) => ({ location }); const DefaultMessageComposerPreviewComponents = { @@ -44,6 +49,24 @@ const DefaultMessageComposerPreviewComponents = { /> ); }, + ScheduledMessage() { + const { ScheduledMessagePreview = DefaultScheduledMessagePreview } = + useComponentContext(); + const messageComposer = useMessageComposerController(); + const { editedScheduledMessage } = useStateStore( + messageComposer.state, + scheduledMessageSelector, + ); + + if (!editedScheduledMessage) return null; + + return ( + + ); + }, QuotedMessage() { const { QuotedMessagePreview = DefaultQuotedMessagePreview } = useComponentContext(); return ; @@ -92,10 +115,16 @@ export const defaultMessageComposerPreviewSet: MessageComposerPreviewSetItem[] = isVisible: ({ editedMessage }) => !!editedMessage, type: 'editedMessage', }, + { + Component: DefaultMessageComposerPreviewComponents.ScheduledMessage, + isVisible: ({ editedScheduledMessage }) => !!editedScheduledMessage, + type: 'scheduledMessage', + }, { Component: DefaultMessageComposerPreviewComponents.QuotedMessage, // The edited message preview takes the quoted message's place while editing. - isVisible: ({ editedMessage, quotedMessage }) => !editedMessage && !!quotedMessage, + isVisible: ({ editedMessage, editedScheduledMessage, quotedMessage }) => + !editedMessage && !editedScheduledMessage && !!quotedMessage, type: 'quotedMessage', }, { diff --git a/src/components/MessageComposer/MessageComposerPreviews.tsx b/src/components/MessageComposer/MessageComposerPreviews.tsx index 218fd3e710..2fe85ec3b7 100644 --- a/src/components/MessageComposer/MessageComposerPreviews.tsx +++ b/src/components/MessageComposer/MessageComposerPreviews.tsx @@ -14,6 +14,7 @@ export type DefaultMessageComposerPreviewType = | 'linkPreviews' | 'location' | 'quotedMessage' + | 'scheduledMessage' | 'voiceRecording'; export type MessageComposerPreviewSetItem = { diff --git a/src/components/MessageComposer/MessageComposerUI.tsx b/src/components/MessageComposer/MessageComposerUI.tsx index dfad78ad78..30fdfc758e 100644 --- a/src/components/MessageComposer/MessageComposerUI.tsx +++ b/src/components/MessageComposer/MessageComposerUI.tsx @@ -21,6 +21,7 @@ import { useStateStore } from '../../store'; import type { TextComposerState } from 'stream-chat'; import { CommandChip as DefaultCommandChip } from './CommandChip'; import { MessageComposerPreviews as DefaultMessageComposerPreviews } from './MessageComposerPreviews'; +import { ScheduledMessagesBanner as DefaultScheduledMessagesBanner } from '../ScheduledMessages/ScheduledMessagesBanner'; const textComposerCommandSelector = ({ command }: TextComposerState) => ({ command }); @@ -40,6 +41,7 @@ export const MessageComposerUI = () => { AudioRecorder = DefaultAudioRecorder, CommandChip = DefaultCommandChip, MessageComposerPreviews = DefaultMessageComposerPreviews, + ScheduledMessagesBanner = DefaultScheduledMessagesBanner, SendToChannelCheckbox = DefaultSendToChannelCheckbox, TextareaComposer = DefaultTextareaComposer, } = useComponentContext(); @@ -49,6 +51,7 @@ export const MessageComposerUI = () => { className='str-chat__message-composer-container' component='div' > + {!message && ScheduledMessagesBanner && }
({ editedMessage, + editedScheduledMessage, pollId, quotedMessage, }); @@ -47,6 +49,11 @@ export type MessageComposerPreviewVisibilityFilterParams = { /** The composer's custom data (`messageComposer.customDataManager`). */ customData: CustomDataManagerState['custom']; editedMessage: MessageComposerState['editedMessage']; + /** + * The scheduled message open in the composer: a pending one is edited, a failed one is sent or + * scheduled again. + */ + editedScheduledMessage: MessageComposerState['editedScheduledMessage']; /** Link previews that are loading or loaded. */ linkPreviews: LinkPreview[]; location: LocationComposerState['location']; @@ -65,10 +72,8 @@ export type MessageComposerPreviewVisibilityFilterParams = { export const useMessageComposerPreviewState = (): MessageComposerPreviewVisibilityFilterParams => { const messageComposer = useMessageComposerController(); - const { editedMessage, pollId, quotedMessage } = useStateStore( - messageComposer.state, - messageComposerStateSelector, - ); + const { editedMessage, editedScheduledMessage, pollId, quotedMessage } = + useStateStore(messageComposer.state, messageComposerStateSelector); const { attachments } = useStateStore( messageComposer.attachmentManager.state, attachmentManagerStateSelector, @@ -101,6 +106,7 @@ export const useMessageComposerPreviewState = attachments, customData, editedMessage, + editedScheduledMessage, linkPreviews, location, pollId, @@ -110,6 +116,7 @@ export const useMessageComposerPreviewState = attachments, customData, editedMessage, + editedScheduledMessage, linkPreviews, location, pollId, diff --git a/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts b/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts index b2c59665ca..0079de12a0 100644 --- a/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts +++ b/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts @@ -1,20 +1,39 @@ import { useCallback } from 'react'; +import { useChatContext } from '../../../context'; +import { + isFailedScheduledMessage, + reloadOnScheduledMessageConflict, +} from '../../ScheduledMessages/utils'; import { useMessageComposerController } from './useMessageComposerController'; /** - * Submits the composer: saves the edit while a message is being edited, sends a new message - * otherwise. The choice is made when the callback runs and every submit control uses this hook, so - * the send button and the Enter key cannot disagree. + * Submits the composer: saves the edit while a message or a scheduled message is being edited, + * sends a new message otherwise. The choice is made when the callback runs and every submit control + * uses this hook, so the send button and the Enter key cannot disagree. * * @returns Submit callback, stable while the composer is the same. */ export const useMessageComposerSubmitFn = () => { + const { client } = useChatContext(); const messageComposer = useMessageComposerController(); - return useCallback( - () => - messageComposer.editedMessage ? messageComposer.update() : messageComposer.send(), - [messageComposer], - ); + return useCallback(async () => { + // a failed one open in the composer is sent or scheduled again instead + const { editedScheduledMessage } = messageComposer; + if (editedScheduledMessage && !isFailedScheduledMessage(editedScheduledMessage)) { + const result = await messageComposer.updateScheduledMessage(); + if (result.status === 'failed') { + reloadOnScheduledMessageConflict( + client, + messageComposer.channel.cid, + result.error, + ); + } + return result; + } + return messageComposer.editedMessage + ? messageComposer.update() + : messageComposer.send(); + }, [client, messageComposer]); }; diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx new file mode 100644 index 0000000000..bec0c417f4 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -0,0 +1,214 @@ +import React, { useCallback, useRef, useState } from 'react'; +import { + dateToNs, + getScheduledMessageErrorReason, + ScheduledMessageErrorReason, + toScheduledMessagePreview, +} from 'stream-chat'; +import type { LocalMessage, UserResponse } from 'stream-chat'; + +import { + useChatContext, + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { Button } from '../Button'; +import { CHANNEL_CONTAINER_ID } from '../Channel/constants'; +import { + ContextMenu, + ContextMenuButton, + ContextMenuHeader, + useDialogIsOpen, + useDialogOnNearestManager, +} from '../Dialog'; +import { useMessageComposerHasSendableData } from '../MessageComposer/hooks'; +import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; +import { GlobalModal } from '../Modal'; +import { Portal } from '../Portal/Portal'; +import { ScheduleTimeDialog } from './ScheduleTimeDialog'; +import { getSchedulePresets, getScheduleTimeBounds } from './utils'; + +const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); + +const ScheduleMessageMenuHeader = () => { + const { t } = useTranslationContext(); + return ( + + {t('scheduledMessages.scheduleMessage', 'Schedule message')} + + ); +}; + +/** + * The chevron next to the send button: schedules the composition at a preset time or opens a + * dialog to pick one. + */ +export const ScheduleMessageButton = () => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const { IconChevronUp, IconClock } = useComponentContextIcons(); + const { ContextMenu: ContextMenuComponent = ContextMenu, Modal = GlobalModal } = + useComponentContext(); + const messageComposer = useMessageComposerController(); + const hasSendableData = useMessageComposerHasSendableData(); + + const menuId = `schedule-message-menu${messageComposer.threadId ? '-thread' : ''}`; + const { dialog: menu, dialogManager } = useDialogOnNearestManager({ id: menuId }); + const isMenuOpen = useDialogIsOpen(menuId, dialogManager?.id); + const buttonRef = useRef(null); + const [dialogPreview, setDialogPreview] = useState(); + + // the banner confirms a scheduled message, so success needs no notification + const scheduleMessage = useCallback( + async (scheduledAt: Date) => { + const { error, status } = await messageComposer.schedule(scheduledAt); + if (status === 'scheduled' || status === 'sent') return; + // the server keeps the ID of a message it scheduled; the next attempt needs a new one + if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.IdTaken) { + messageComposer.refreshId(); + } + throw error ?? new Error(`Message not scheduled: ${status}`); + }, + [messageComposer], + ); + + // the dialog shows the failure itself, so the composer's notification of it is dropped + const scheduleMessageFromDialog = useCallback( + async (scheduledAt: Date) => { + const { notifications } = client; + const shownBefore = new Set(notifications.notifications.map(({ id }) => id)); + try { + await scheduleMessage(scheduledAt); + } catch (error) { + notifications.notifications + .filter( + ({ id, origin }) => + !shownBefore.has(id) && origin.context?.composer === messageComposer, + ) + .forEach(({ id }) => notifications.remove(id)); + throw error; + } + }, + [client, messageComposer, scheduleMessage], + ); + + const openDialog = () => { + menu.close(); + const now = dateToNs(new Date()); + const { attachmentManager, channel, id, textComposer } = messageComposer; + setDialogPreview( + toScheduledMessagePreview({ + cid: channel.cid, + created_at: now, + id, + message: { + attachments: attachmentManager.attachments, + custom: {}, + text: textComposer.text, + }, + scheduled_at: now, + status: 'scheduled', + updated_at: now, + user: (client.user ?? { id: client.userID ?? '' }) as UserResponse, + }), + ); + }; + + const closeDialog = () => { + setDialogPreview(undefined); + // the menu item that opened the dialog is gone, so focus returns to the chevron + requestAnimationFrame(() => buttonRef.current?.focus()); + }; + + return ( + <> + + ('.str-chat__split-send-button') ?? + buttonRef.current + } + tabIndex={-1} + > + {isMenuOpen && + getSchedulePresets( + new Date(), + getScheduleTimeBounds(messageComposer.channel), + ).map((scheduledAt) => ( + { + menu.close(); + scheduleMessage(scheduledAt).catch(() => undefined); + }} + > + {t('timestamp.SchedulePreset', { timestamp: scheduledAt })} + + ))} +
+ + {t('scheduledMessages.customTime', 'Custom time')} + + + + + {dialogPreview && ( + + )} + + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx new file mode 100644 index 0000000000..e87ab6495f --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -0,0 +1,203 @@ +import React, { type MouseEvent, useState } from 'react'; +import type { Channel, LocalMessage } from 'stream-chat'; + +import { useComponentContextIcons, useTranslationContext } from '../../context'; +import { useIsMounted } from '../Channel/hooks/useIsMounted'; +import { useWSConnectionState } from '../Chat/hooks/useWSConnectionState'; +import { useChannelDisplayName } from '../ChannelListItem/hooks/useChannelDisplayName'; +import { Prompt } from '../Dialog'; +import { TextInput } from '../Form'; +import { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; +import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; +import { + formatTimeZoneOffset, + fromInputValues, + getDefaultScheduledAt, + getScheduleTimeBounds, + getScheduleTimeError, + toDateInputValue, + toTimeInputValue, + translateScheduledMessageError, +} from './utils'; + +export type ScheduleTimeDialogProps = { + channel: Channel; + close: () => void; + /** Shown when `submit` rejects with an error that says nothing more specific; the dialog stays open. */ + errorMessage: string; + previewMessage: LocalMessage; + /** Closes the dialog once it resolves. */ + submit: (scheduledAt: Date) => Promise; + title: string; + initialScheduledAt?: Date; + /** Above the preview; "Message to {{ name }}" by default. */ + previewLabel?: string; + submitLabel?: string; + /** Why an earlier time is refused; "Choose a later time" by default. */ + tooSoonMessage?: string; +}; + +/** A click anywhere in a field, its icons included, opens the field's picker. */ +const openNativePicker = ({ target }: MouseEvent) => { + const input = (target as Element) + .closest('.str-chat__form-text-input__wrapper') + ?.querySelector('input'); + try { + input?.showPicker?.(); + } catch { + // not allowed outside a user gesture in some browsers + } +}; + +/** Picks a date and time within the channel's limits and submits it. */ +export const ScheduleTimeDialog = ({ + channel, + close, + errorMessage, + initialScheduledAt, + previewLabel, + previewMessage, + submit, + submitLabel, + title, + tooSoonMessage, +}: ScheduleTimeDialogProps) => { + const { t } = useTranslationContext(); + const { IconCalendar, IconCaretDown, IconClock } = useComponentContextIcons(); + const channelDisplayName = useChannelDisplayName(channel); + const isOnline = useWSConnectionState()?.isHealthy ?? false; + const isMounted = useIsMounted(); + + const [bounds] = useState(() => getScheduleTimeBounds(channel)); + const [dateValue, setDateValue] = useState(() => + toDateInputValue(initialScheduledAt ?? getDefaultScheduledAt(bounds)), + ); + const [timeValue, setTimeValue] = useState(() => + toTimeInputValue(initialScheduledAt ?? getDefaultScheduledAt(bounds)), + ); + const [status, setStatus] = useState<'failed' | 'idle' | 'submitting'>('idle'); + const [submitError, setSubmitError] = useState(); + + const scheduledAt = fromInputValues(dateValue, timeValue); + const timeError = scheduledAt && getScheduleTimeError(scheduledAt, bounds); + const selectedDate = fromInputValues(dateValue); + const canSubmit = !!scheduledAt && !timeError && isOnline && status !== 'submitting'; + + const submitScheduledAt = async () => { + if (!scheduledAt) return; + setStatus('submitting'); + try { + await submit(scheduledAt); + if (isMounted.current) close(); + } catch (error) { + if (!isMounted.current) return; + setSubmitError(error); + setStatus('failed'); + } + }; + + return ( + + + + + {!isOnline && ( + + {t( + 'scheduledMessages.youreOfflineReconnectToScheduleThisMessage', + "You're offline. Reconnect to schedule this message.", + )} + + )} + {status === 'failed' && ( + + {translateScheduledMessageError(t, submitError) ?? errorMessage} + + )} +
+ + + + {selectedDate && + t('timestamp.ScheduleDate', { timestamp: selectedDate })} + + + } + max={bounds.latest && toDateInputValue(bounds.latest)} + min={toDateInputValue(bounds.earliest)} + onChange={({ target }) => setDateValue(target.value)} + required + trailing={} + type='date' + value={dateValue} + /> + } + onChange={({ target }) => setTimeValue(target.value)} + required + trailing={} + type='time' + value={timeValue} + /> +
+ {/* a time out of bounds takes the time zone's place */} + {timeError ? ( + + {timeError === 'tooSoon' + ? (tooSoonMessage ?? + t('scheduledMessages.chooseALaterTime', 'Choose a later time')) + : t('scheduledMessages.chooseAnEarlierTime', 'Choose an earlier time')} + + ) : ( + + {t( + 'scheduledMessages.sentInYourTimeZoneTimezone', + 'Sent in your time zone ({{ timeZone }})', + { timeZone: formatTimeZoneOffset(scheduledAt ?? bounds.earliest) }, + )} + + )} +
+ + + + {t('scheduledMessages.cancel', 'Cancel')} + + + {submitLabel ?? t('scheduledMessages.schedule', 'Schedule')} + + + +
+ ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx new file mode 100644 index 0000000000..5057c4f09a --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -0,0 +1,446 @@ +import clsx from 'clsx'; +import React, { useRef, useState } from 'react'; +import { nsToDate, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; +import type { OwnCapabilitiesState, ScheduledMessageResponse } from 'stream-chat'; + +import { + useChatContext, + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { ChannelAvatar } from '../Avatar'; +import { Button } from '../Button'; +import { useIsMounted } from '../Channel/hooks/useIsMounted'; +import { useChannelPreviewInfo } from '../ChannelListItem/hooks/useChannelPreviewInfo'; +import { + Alert, + ContextMenu, + ContextMenuButton, + useDialogIsOpen, + useDialogOnNearestManager, +} from '../Dialog'; +import { GlobalModal } from '../Modal'; +import { useNotificationApi } from '../Notifications'; +import { useStateStore } from '../../store'; +import { SummarizedMessagePreview } from '../SummarizedMessagePreview'; +import { useStableId } from '../UtilityComponents/useStableId'; +import { VisuallyHidden } from '../VisuallyHidden'; +import { SCHEDULE_MESSAGE_CAPABILITY } from './hooks'; +import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; +import { ScheduleTimeDialog } from './ScheduleTimeDialog'; +import { + getChannelByCid, + getScheduledMessageActions, + isFailedScheduledMessage, + reloadOnScheduledMessageConflict, + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, + translateScheduledMessageError, + translateScheduledMessageFailureReason, +} from './utils'; +import type { ScheduledMessageAction } from './utils'; + +export type ScheduledMessageItemProps = { + scheduledMessage: ScheduledMessageResponse; + /** Opens the message in the composer; without it the list offers no edit action. */ + onEdit?: (scheduledMessage: ScheduledMessageResponse) => void; +}; + +type OpenDialog = 'delete' | 'reschedule'; + +const selectComposeCapabilities = ({ ownCapabilities }: OwnCapabilitiesState) => ({ + canSchedule: !!ownCapabilities?.includes(SCHEDULE_MESSAGE_CAPABILITY), + canSend: !!ownCapabilities?.includes('send-message'), +}); + +/** A scheduled message: when it is sent, where, its status and what can be done with it. */ +export const ScheduledMessageItem = ({ + onEdit, + scheduledMessage, +}: ScheduledMessageItemProps) => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const { + IconClock, + IconCopy, + IconDelete, + IconEdit, + IconExclamationTriangleFill, + IconLoading, + IconMore, + IconSend, + } = useComponentContextIcons(); + const { ContextMenu: ContextMenuComponent = ContextMenu, Modal = GlobalModal } = + useComponentContext(); + const { addNotification } = useNotificationApi(); + const isMounted = useIsMounted(); + + const { cid, failure_reason, id, message, scheduled_at, status } = scheduledMessage; + // shown from a loaded channel only; an action creates the instance it needs + const loadedChannel = client.channelManager.get(cid); + const { displayImage, displayTitle, groupChannelDisplayInfo } = useChannelPreviewInfo({ + channel: loadedChannel, + }); + const composeCapabilities = useStateStore( + loadedChannel?.state, + selectComposeCapabilities, + ); + const editUnavailableId = useStableId(); + const getChannel = () => getChannelByCid(client, cid); + const previewMessage = useScheduledMessagePreview(scheduledMessage); + const sendTime = nsToDate(scheduled_at); + const isFailed = isFailedScheduledMessage(scheduledMessage); + // a pending message is saved by scheduling it, a failed one is scheduled or sent again; a frozen + // channel allows neither. Unknown for a channel not loaded, so left on there. + const canEdit = + !composeCapabilities || + composeCapabilities.canSchedule || + (isFailed && composeCapabilities.canSend); + const editUnavailableProps = canEdit + ? undefined + : { 'aria-describedby': editUnavailableId, 'aria-disabled': true }; + + const menuId = `scheduled-message-actions-${id}`; + const { dialog: menu, dialogManager } = useDialogOnNearestManager({ id: menuId }); + const isMenuOpen = useDialogIsOpen(menuId, dialogManager?.id); + const menuButtonRef = useRef(null); + const [openDialog, setOpenDialog] = useState(); + const [isPending, setIsPending] = useState(false); + + const actions = getScheduledMessageActions(scheduledMessage, !!onEdit); + // a pending message keeps "edit" as its own button, outside the menu + const hasEditButton = !isFailed && actions.includes('edit'); + const menuActions = hasEditButton + ? actions.filter((action) => action !== 'edit') + : actions; + + const closeDialog = () => { + setOpenDialog(undefined); + requestAnimationFrame(() => menuButtonRef.current?.focus()); + }; + + const run = async ( + request: () => Promise, + failure: { message: string; type: string }, + success?: { message: string; type: string }, + ) => { + setIsPending(true); + try { + await request(); + if (success) { + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + severity: 'success', + ...success, + }); + } + } catch (error) { + reloadOnScheduledMessageConflict(client, cid, error); + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + error: error as Error, + severity: 'error', + ...failure, + message: translateScheduledMessageError(t, error) ?? failure.message, + }); + } finally { + if (isMounted.current) setIsPending(false); + } + }; + + const menuItems: Record< + ScheduledMessageAction, + { Icon: typeof IconClock; label: string; select: () => void } + > = { + copy: { + Icon: IconCopy, + label: t('scheduledMessages.copyText', 'Copy text'), + select: () => + navigator.clipboard?.writeText(message.text ?? '').catch(() => undefined), + }, + delete: { + Icon: IconDelete, + label: t('scheduledMessages.delete', 'Delete'), + select: () => setOpenDialog('delete'), + }, + edit: { + Icon: IconEdit, + label: t('scheduledMessages.editReschedule', 'Edit & reschedule'), + select: () => onEdit?.(scheduledMessage), + }, + reschedule: { + Icon: IconClock, + label: t('scheduledMessages.reschedule', 'Reschedule'), + select: () => setOpenDialog('reschedule'), + }, + send_now: { + Icon: IconSend, + label: t('scheduledMessages.sendNow', 'Send now'), + select: () => + run( + () => getChannel().sendScheduledMessageNow(id), + { + message: t( + 'scheduledMessages.couldntSendTheMessageTryAgain', + "Couldn't send the message. Try again", + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowFailed, + }, + { + message: t( + 'scheduledMessages.scheduledMessageSent', + 'Scheduled message sent', + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowSucceeded, + }, + ), + }, + }; + + const rescheduleErrorMessage = t( + 'scheduledMessages.couldntRescheduleTheMessageTryAgain', + "Couldn't reschedule the message. Try again", + ); + const reschedule = async (scheduledAt: Date) => { + try { + await getChannel().updateScheduledMessage(id, { scheduled_at: scheduledAt }); + } catch (error) { + reloadOnScheduledMessageConflict(client, cid, error); + // the dialog stays open and shows the failure + throw error; + } + }; + + const deleteScheduledMessage = () => { + closeDialog(); + void run(() => getChannel().deleteScheduledMessage(id), { + message: t( + 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain', + "Couldn't delete the scheduled message. Try again", + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.deleteFailed, + }); + }; + + return ( +
+ +
+ + {hasEditButton && ( + + )} + + {menuActions.map((action, index) => { + const { Icon, label, select } = menuItems[action]; + const isDelete = action === 'delete'; + return ( + + {/* Delete stands apart, unless it is the only action */} + {isDelete && index > 0 && ( +
+ )} + { + if (action === 'edit' && !canEdit) return; + menu.close(); + select(); + }} + variant={isDelete ? 'destructive' : undefined} + > + {label} + + + ); + })} + +
+ {!canEdit && ( + + {t( + 'scheduledMessages.cantSendInThisChannel', + "Unavailable: you can't send messages in this channel", + )} + + )} +
+
+ + {openDialog === 'reschedule' && ( + + )} + + + {openDialog === 'delete' && ( + + + + + + + + )} + +
+ ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageList.tsx b/src/components/ScheduledMessages/ScheduledMessageList.tsx new file mode 100644 index 0000000000..a15975f515 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -0,0 +1,223 @@ +import React, { useEffect, useMemo } from 'react'; +import type { + ChannelDataState, + OwnCapabilitiesState, + PaginatorState, + ScheduledMessageResponse, +} from 'stream-chat'; + +import { + useChatContext, + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { useStateStore } from '../../store'; +import { EmptyStateIndicator } from '../EmptyStateIndicator'; +import { InfiniteScrollPaginator } from '../InfiniteScrollPaginator'; +import { + ListLoadErrorIndicator as BaseListLoadErrorIndicator, + LoadingIndicator, +} from '../Loading'; +import type { ListLoadErrorIndicatorProps } from '../Loading'; +import { getFirstPageLoadError } from '../Loading/getFirstPageLoadError'; +import { useFirstPageLoadRetry } from '../Loading/hooks/useFirstPageLoadRetry'; +import { SCHEDULE_MESSAGE_CAPABILITY, useScheduledMessages } from './hooks'; +import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; +import { ScheduledMessageItem as DefaultScheduledMessageItem } from './ScheduledMessageItem'; +import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; +import { + getChannelByCid, + groupScheduledMessages, + searchScheduledMessages, +} from './utils'; + +export type ScheduledMessageListProps = Pick & { + /** The channel whose scheduled messages to list; all of them without it. */ + cid?: string; + parentId?: string; + /** Lists only the messages whose text contains it. */ + searchQuery?: string; +}; + +const selectLoadState = (state: PaginatorState) => ({ + firstPageLoadError: getFirstPageLoadError(state), + hasMoreTail: state.hasMoreTail, + isFirstPageLoading: state.items === undefined && !state.lastQueryError, + isLoading: state.isLoading, + lastQueryFailed: !!state.lastQueryError, +}); + +const DefaultListLoadErrorIndicator = (props: ListLoadErrorIndicatorProps) => ( + +); + +const DefaultEmptyListIndicator = () => ( + +); + +const DefaultFirstPageLoadingIndicator = () => { + const { t } = useTranslationContext(); + return ( +
+ +
+ ); +}; + +const DefaultLoadingNextPageIndicator = ({ isLoading }: { isLoading?: boolean }) => + isLoading ? : null; + +const NoSearchResults = () => { + const { t } = useTranslationContext(); + const { IconSearch } = useComponentContextIcons(); + return ( +
+ +

+ {t('scheduledMessages.noMessagesFound', 'No messages found')} +

+
+ ); +}; + +const selectScheduling = ({ + data, + ownCapabilities, +}: ChannelDataState & OwnCapabilitiesState) => ({ + // unknown until the channel is loaded + canSchedule: + ownCapabilities === undefined || + ownCapabilities.includes(SCHEDULE_MESSAGE_CAPABILITY), + frozen: !!data?.frozen, +}); + +/** Why the channel takes no scheduled messages: frozen, or the user is not allowed to. */ +const SchedulingUnavailableNotice = ({ cid }: { cid: string }) => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const channel = getChannelByCid(client, cid); + const { canSchedule, frozen } = useStateStore(channel.state, selectScheduling); + if (canSchedule) return null; + return ( + + {frozen + ? t( + 'scheduledMessages.channelFrozenNotice', + "This channel is frozen. Scheduled messages won't be sent", + ) + : t( + 'scheduledMessages.schedulingUnavailableNotice', + "You can't schedule messages in this channel", + )} + + ); +}; + +const ScheduledMessageListBody = ({ + cid, + onEdit, + parentId, + searchQuery, +}: ScheduledMessageListProps) => { + const { t } = useTranslationContext(); + const { + EmptyListIndicator = DefaultEmptyListIndicator, + FirstPageLoadingIndicator = DefaultFirstPageLoadingIndicator, + ListLoadErrorIndicator = DefaultListLoadErrorIndicator, + LoadingNextPageIndicator = DefaultLoadingNextPageIndicator, + ScheduledMessageItem = DefaultScheduledMessageItem, + } = useComponentContext(); + const { paginator, scheduledMessages } = useScheduledMessages({ cid, parentId }); + const { + firstPageLoadError, + hasMoreTail, + isFirstPageLoading, + isLoading, + lastQueryFailed, + } = useStateStore(paginator.state, selectLoadState); + const firstPageLoadRetry = useFirstPageLoadRetry({ + firstPageLoadError, + loadedMessage: t('scheduledMessages.loaded', 'Scheduled messages loaded'), + paginator, + reload: paginator.reload, + }); + const groups = useMemo( + () => groupScheduledMessages(searchScheduledMessages(scheduledMessages, searchQuery)), + [scheduledMessages, searchQuery], + ); + const showsNothing = !isFirstPageLoading && !groups.length; + // stops at a failed page instead of retrying it + const loadsFurther = showsNothing && hasMoreTail && !lastQueryFailed; + + // the matches may be on a page not loaded yet + useEffect(() => { + if (loadsFurther && !isLoading) paginator.toTail(); + }, [isLoading, loadsFurther, paginator]); + + if (firstPageLoadRetry.error) { + return ( + + ); + } + if (isFirstPageLoading) return ; + if (showsNothing) { + if (loadsFurther) return ; + return scheduledMessages.length ? : ; + } + + return ( + + {groups.map(({ day, key, scheduledMessages: groupMessages }) => ( +
+

+ {day + ? t('timestamp.ScheduledMessageGroup', { timestamp: day }) + : t('scheduledMessages.failed', 'Failed')} +

+
    + {groupMessages.map((scheduledMessage) => ( +
  • + +
  • + ))} +
+
+ ))} + +
+ ); +}; + +/** + * Scheduled messages grouped by the day they are sent on, failed ones first, paginated on scroll. + * Loading, failing and empty states use the list-state components `ChannelList` uses. Scoping to a + * thread and searching filter the loaded messages, so further pages load while none of them match. + */ +export const ScheduledMessageList = (props: ScheduledMessageListProps) => ( + <> + {props.cid && } + + +); diff --git a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx new file mode 100644 index 0000000000..a134c77eac --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx @@ -0,0 +1,123 @@ +import clsx from 'clsx'; +import React, { useRef, useState } from 'react'; + +import { + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { Button } from '../Button'; +import { CHANNEL_CONTAINER_ID } from '../Channel/constants'; +import { Prompt } from '../Dialog'; +import { TextInput } from '../Form'; +import { GlobalModal } from '../Modal'; +import { Portal } from '../Portal/Portal'; +import { useScheduledMessages } from './hooks'; +import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; +import { ScheduledMessageList as DefaultScheduledMessageList } from './ScheduledMessageList'; + +const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); + +export type ScheduledMessageListDialogProps = Pick< + ScheduledMessageItemProps, + 'onEdit' +> & { + /** The channel whose scheduled messages to list. */ + cid: string; + close: () => void; + open: boolean; + /** The thread whose scheduled replies to list. */ + parentId?: string; +}; + +/** + * The scheduled messages of a channel or thread in a modal, with a search field. The banner's + * "View all" opens it; an override can show the list elsewhere, such as in a channel detail view. + */ +export const ScheduledMessageListDialog = ({ + cid, + close, + onEdit, + open, + parentId, +}: ScheduledMessageListDialogProps) => { + const { t } = useTranslationContext(); + const { IconSearch, IconXCircle } = useComponentContextIcons(); + const { Modal = GlobalModal, ScheduledMessageList = DefaultScheduledMessageList } = + useComponentContext(); + const { scheduledMessages } = useScheduledMessages({ cid, parentId }); + const searchInputRef = useRef(null); + const [searchQuery, setSearchQuery] = useState(''); + + const closeDialog = () => { + setSearchQuery(''); + close(); + }; + + return ( + + + {open && ( + + + + {scheduledMessages.length > 0 && ( + } + onChange={({ target }) => setSearchQuery(target.value)} + placeholder={t('scheduledMessages.search', 'Search')} + ref={searchInputRef} + trailing={ + + } + type='search' + value={searchQuery} + /> + )} + + + + )} + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx new file mode 100644 index 0000000000..2a8ffabaa4 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx @@ -0,0 +1,32 @@ +import React from 'react'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { useTranslationContext } from '../../context'; +import { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; +import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; +import { isFailedScheduledMessage } from './utils'; + +export type ScheduledMessagePreviewProps = { + onCancel: () => void; + scheduledMessage: ScheduledMessageResponse; +}; + +/** Above the composer while a scheduled message is edited, or a failed one scheduled again. */ +export const ScheduledMessagePreview = ({ + onCancel, + scheduledMessage, +}: ScheduledMessagePreviewProps) => { + const { t } = useTranslationContext(); + const previewMessage = useScheduledMessagePreview(scheduledMessage); + return ( + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx new file mode 100644 index 0000000000..9dd7c97d98 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx @@ -0,0 +1,144 @@ +import clsx from 'clsx'; +import React, { useEffect, useRef, useState } from 'react'; +import { nsToDate } from 'stream-chat'; +import type { + MessageComposerState, + PaginatorState, + ScheduledMessageResponse, +} from 'stream-chat'; + +import { + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { useStateStore } from '../../store'; +import { useAriaLiveAnnouncer } from '../Accessibility'; +import { useChannelCapabilities } from '../Channel/hooks/useChannelCapabilities'; +import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; +import { SCHEDULE_MESSAGE_CAPABILITY, useScheduledMessages } from './hooks'; +import { ScheduledMessageListDialog as DefaultScheduledMessageListDialog } from './ScheduledMessageListDialog'; +import { isFailedScheduledMessage } from './utils'; + +const selectIsLoaded = ({ items }: PaginatorState) => ({ + isLoaded: items !== undefined, +}); + +// hidden for a failed scheduled message open in the composer too +const selectIsEditing = ({ + editedMessage, + editedScheduledMessage, +}: MessageComposerState) => ({ + isEditing: !!editedMessage || !!editedScheduledMessage, +}); + +/** + * Above the composer: when the only scheduled message in the channel (or thread) is sent, how many + * are scheduled, or how many failed. "View all" opens the `ScheduledMessageListDialog` slot. Hidden + * while the composer edits a message; its changes are announced to screen readers. + */ +export const ScheduledMessagesBanner = () => { + const { t } = useTranslationContext(); + const { IconClock, IconExclamationMark } = useComponentContextIcons(); + const { ScheduledMessageListDialog = DefaultScheduledMessageListDialog } = + useComponentContext(); + const messageComposer = useMessageComposerController(); + const { cid } = messageComposer.channel; + const parentId = messageComposer.threadId ?? undefined; + const canSchedule = useChannelCapabilities({ cid }).has(SCHEDULE_MESSAGE_CAPABILITY); + const { paginator, scheduledMessages } = useScheduledMessages({ cid, parentId }); + const { isLoaded } = useStateStore(paginator.state, selectIsLoaded); + const { isEditing } = useStateStore(messageComposer.state, selectIsEditing); + const announce = useAriaLiveAnnouncer(); + const announcedLabelRef = useRef(undefined); + const [isDialogOpen, setIsDialogOpen] = useState(false); + + const failedCount = scheduledMessages.filter(isFailedScheduledMessage).length; + const isVisible = + !isEditing && (failedCount > 0 || (canSchedule && scheduledMessages.length > 0)); + const [onlyScheduledMessage] = scheduledMessages.length === 1 ? scheduledMessages : []; + + const label = failedCount + ? t('scheduledMessages.banner.failedToSend', { + count: failedCount, + defaultValue_one: '{{ count }} failed to send', + defaultValue_other: '{{ count }} failed to send', + }) + : onlyScheduledMessage + ? t('scheduledMessages.banner.scheduledFor', 'Scheduled for {{ time }}', { + time: t('timestamp.ScheduledMessageConfirmation', { + timestamp: nsToDate(onlyScheduledMessage.scheduled_at), + }), + }) + : parentId + ? t('scheduledMessages.banner.scheduledReplies', { + count: scheduledMessages.length, + defaultValue_one: '{{ count }} scheduled reply', + defaultValue_other: '{{ count }} scheduled replies', + }) + : t('scheduledMessages.banner.scheduledMessages', { + count: scheduledMessages.length, + defaultValue_one: '{{ count }} scheduled message', + defaultValue_other: '{{ count }} scheduled messages', + }); + const announcedLabel = isVisible ? label : undefined; + + // a change, such as a message just scheduled or failed; not the banner the list loaded with + useEffect(() => { + if (!isLoaded) { + announcedLabelRef.current = undefined; + return; + } + const previousLabel = announcedLabelRef.current; + announcedLabelRef.current = announcedLabel ?? ''; + if ( + previousLabel === undefined || + !announcedLabel || + previousLabel === announcedLabel + ) + return; + announce(announcedLabel); + }, [announce, announcedLabel, isLoaded]); + + if (!isVisible && !isDialogOpen) return null; + + const closeDialog = () => setIsDialogOpen(false); + const editScheduledMessage = (scheduledMessage: ScheduledMessageResponse) => { + closeDialog(); + messageComposer.editScheduledMessage(scheduledMessage); + }; + + const Icon = failedCount ? IconExclamationMark : IconClock; + + return ( + <> + {isVisible && ( +
0, + })} + data-testid='scheduled-messages-banner' + > + + {label} + +
+ )} + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessagesNotice.tsx b/src/components/ScheduledMessages/ScheduledMessagesNotice.tsx new file mode 100644 index 0000000000..f2b3e34f82 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessagesNotice.tsx @@ -0,0 +1,33 @@ +import clsx from 'clsx'; +import React from 'react'; + +import { useComponentContextIcons } from '../../context'; + +export type ScheduledMessagesNoticeProps = { + children: string; + className?: string; + isError?: boolean; +}; + +/** A tinted line of information or error, as the scheduling dialogs and the list show it. */ +export const ScheduledMessagesNotice = ({ + children, + className, + isError, +}: ScheduledMessagesNoticeProps) => { + const { IconExclamationCircleFill, IconInfo } = useComponentContextIcons(); + const Icon = isError ? IconExclamationCircleFill : IconInfo; + return ( +
+ + {children} +
+ ); +}; diff --git a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx new file mode 100644 index 0000000000..1da1337d63 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx @@ -0,0 +1,155 @@ +import '../../..'; +import React from 'react'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; + +import { Channel } from '../../Channel'; +import { Chat } from '../../Chat'; +import { MessageComposer } from '../../MessageComposer'; +import { + generateScheduledMessage, + generateUser, + initClientWithChannels, +} from '../../../mock-builders'; + +const user = generateUser({ id: 'user-id' }); + +const renderComposer = async () => { + const { + channels: [channel], + client, + } = await initClientWithChannels({ + channelsData: [ + { + channel: { + id: 'general', + own_capabilities: ['send-message', 'schedule-message'], + type: 'messaging', + }, + }, + ], + customUser: user, + }); + + await act(() => { + render( + + + + + , + ); + }); + + const scheduledMessage = generateScheduledMessage({ + cid: channel.cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }); + const { messageComposer } = channel; + + const failedMessage = generateScheduledMessage({ + cid: channel.cid, + failure_reason: 'channel_frozen', + message: { custom: {}, text: 'Launch moved to Monday' }, + status: 'failed', + }); + + const startEditing = () => + act(() => messageComposer.editScheduledMessage(scheduledMessage)); + + const startSchedulingAgain = () => + act(() => messageComposer.editScheduledMessage(failedMessage)); + + return { + channel, + client, + failedMessage, + messageComposer, + scheduledMessage, + startEditing, + startSchedulingAgain, + }; +}; + +describe('editing a scheduled message in the composer', () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it('shows the scheduled edit preview and hides the schedule button', async () => { + const { startEditing } = await renderComposer(); + + await startEditing(); + + expect(screen.getByText('Edit scheduled message')).toBeInTheDocument(); + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + }); + + it('saves the edit with updateScheduledMessage instead of sending', async () => { + const { channel, messageComposer, scheduledMessage, startEditing } = + await renderComposer(); + const updateScheduledMessage = vi + .spyOn(messageComposer, 'updateScheduledMessage') + .mockResolvedValue({ scheduledMessage, status: 'scheduled' }); + const sendMessage = vi.spyOn(channel, 'sendMessage'); + + await startEditing(); + await act(() => fireEvent.click(screen.getByTestId('send-button'))); + + expect(updateScheduledMessage).toHaveBeenCalledTimes(1); + expect(sendMessage).not.toHaveBeenCalled(); + }); + + it('restores the earlier draft when the edit is cancelled', async () => { + const { messageComposer, startEditing } = await renderComposer(); + await act(() => messageComposer.textComposer.setText('my unsent draft')); + + await startEditing(); + await act(() => + fireEvent.click(screen.getByRole('button', { name: /cancel|remove/i })), + ); + + expect(screen.queryByText('Edit scheduled message')).not.toBeInTheDocument(); + expect(messageComposer.textComposer.text).toBe('my unsent draft'); + }); + + describe('scheduling a failed message again', () => { + it('shows the schedule-again preview and keeps the schedule button', async () => { + const { startSchedulingAgain } = await renderComposer(); + + await startSchedulingAgain(); + + expect(screen.getByText('Schedule again')).toBeInTheDocument(); + expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); + }); + + it('restores the earlier draft when cancelled', async () => { + const { messageComposer, startSchedulingAgain } = await renderComposer(); + await act(() => messageComposer.textComposer.setText('my unsent draft')); + + await startSchedulingAgain(); + await act(() => + fireEvent.click(screen.getByRole('button', { name: /cancel|remove/i })), + ); + + expect(screen.queryByText('Schedule again')).not.toBeInTheDocument(); + expect(messageComposer.textComposer.text).toBe('my unsent draft'); + }); + + it('deletes the failed message after sending it now', async () => { + const { channel, failedMessage, startSchedulingAgain } = await renderComposer(); + vi.spyOn(channel, 'sendMessage').mockResolvedValue( + fromPartial({ message: { id: 'sent-id', text: 'Launch moved to Monday' } }), + ); + const deleteScheduledMessage = vi + .spyOn(channel, 'deleteScheduledMessage') + .mockResolvedValue(failedMessage); + + await startSchedulingAgain(); + await act(() => fireEvent.click(screen.getByTestId('send-button'))); + + expect(deleteScheduledMessage).toHaveBeenCalledWith(failedMessage.id); + }); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx new file mode 100644 index 0000000000..4695f96f24 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -0,0 +1,451 @@ +import '../../..'; +import React from 'react'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { ScheduledMessageErrorReason } from 'stream-chat'; +import type { + Channel as ChannelType, + ScheduledMessageResponse, + ScheduledMessageSubmitResult, + StreamChat, +} from 'stream-chat'; + +import { axe } from '../../../../axe-helper'; +import { Channel } from '../../Channel'; +import { Chat } from '../../Chat'; +import { WithComponents } from '../../../context/WithComponents'; +import { MessageComposer } from '../../MessageComposer'; +import { + convertDateToTimestamp, + erroredScheduledMessageApi, + generateScheduledMessage, + generateUser, + initClientWithChannels, + sendScheduledMessageApi, + setWSConnectionStatus, + useMockedApis, +} from '../../../mock-builders'; + +const user = generateUser({ id: 'user-id' }); + +const WEDNESDAY_MORNING = new Date(2026, 9, 28, 10, 30); +const MONDAY_MORNING = new Date(2026, 10, 2, 13, 0); + +const channelDataWith = (ownCapabilities: string[]) => ({ + channel: { + id: 'general', + own_capabilities: ownCapabilities, + type: 'messaging', + }, +}); + +type SetupOptions = { + canSchedule?: boolean; + components?: Parameters[0]['overrides']; + text?: string; +}; + +const renderComposer = async ({ + canSchedule = true, + components = {}, + text = 'Launch moved to Monday', +}: SetupOptions = {}) => { + const ownCapabilities = canSchedule + ? ['send-message', 'schedule-message'] + : ['send-message']; + const { + channels: [channel], + client, + } = await initClientWithChannels({ + channelsData: [channelDataWith(ownCapabilities)], + customUser: user, + }); + + await act(() => { + render( + + + + + + + , + ); + }); + + if (text) { + await act(() => channel.messageComposer.textComposer.setText(text)); + } + + return { channel, client }; +}; + +const openMenu = async () => { + await act(() => fireEvent.click(screen.getByTestId('schedule-message-button'))); + + return screen.findByTestId('schedule-message-menu'); +}; + +const openDialog = async () => { + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Custom time'))); + + return screen.findByTestId('schedule-message-dialog'); +}; + +const getNotifications = (client: StreamChat) => + client.notifications.store.getLatestValue().notifications; + +const mockSchedule = (channel: ChannelType) => + vi.spyOn(channel.messageComposer, 'schedule'); + +const scheduledResult = ( + scheduledMessage: ScheduledMessageResponse, +): ScheduledMessageSubmitResult => ({ scheduledMessage, status: 'scheduled' }); + +describe('ScheduleMessageButton', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] }); + vi.setSystemTime(WEDNESDAY_MORNING); + }); + + afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + describe('split send button', () => { + it('renders the chevron next to the send button with the capability', async () => { + await renderComposer(); + + const chevron = screen.getByTestId('schedule-message-button'); + + expect(screen.getByTestId('send-button')).toBeInTheDocument(); + expect(chevron).toHaveAttribute('aria-haspopup', 'menu'); + expect(chevron).toHaveAttribute('aria-expanded', 'false'); + expect(chevron.closest('.str-chat__split-send-button')).not.toBeNull(); + }); + + it('keeps the single send button without the capability', async () => { + await renderComposer({ canSchedule: false }); + + expect(screen.getByTestId('send-button')).toBeInTheDocument(); + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + expect(document.querySelector('.str-chat__split-send-button')).toBeNull(); + }); + + it('hides the chevron for a slash command', async () => { + await renderComposer({ text: '/giphy hello' }); + + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + }); + + it('can be removed through ComponentContext', async () => { + await renderComposer({ components: { ScheduleMessageButton: null } }); + + expect(screen.getByTestId('send-button')).toBeInTheDocument(); + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + }); + + it('still sends immediately from the send button', async () => { + const { channel } = await renderComposer(); + const schedule = mockSchedule(channel); + const sendMessage = vi + .spyOn(channel, 'sendMessage') + .mockResolvedValue(fromPartial({ message: { id: 'sent' } })); + + await act(() => fireEvent.click(screen.getByTestId('send-button'))); + + await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1)); + expect(sendMessage.mock.calls[0][0].scheduled_at).toBeUndefined(); + expect(schedule).not.toHaveBeenCalled(); + }); + }); + + describe('menu', () => { + it('shows the heading, the presets and Custom time', async () => { + await renderComposer(); + + const menu = await openMenu(); + + expect(menu).toHaveTextContent('Schedule message'); + expect(screen.getByText('Tomorrow at 09:00')).toBeInTheDocument(); + expect(screen.getByText('Tomorrow at 13:00')).toBeInTheDocument(); + expect(screen.getByText('Monday at 09:00')).toBeInTheDocument(); + expect(screen.getByText('Custom time')).toBeInTheDocument(); + expect(screen.getByTestId('schedule-message-button')).toHaveAttribute( + 'aria-expanded', + 'true', + ); + }); + + it('labels the next-Monday preset with the weekday on a Monday', async () => { + vi.setSystemTime(MONDAY_MORNING); + await renderComposer(); + + await openMenu(); + + expect(screen.getByText('Tomorrow at 09:00')).toBeInTheDocument(); + expect(screen.getByText('Monday at 09:00')).toBeInTheDocument(); + }); + + // the banner confirms it + it('schedules at the picked preset without a notification', async () => { + const { channel, client } = await renderComposer(); + const serverScheduledAt = new Date(2026, 9, 29, 9, 0); + const scheduledMessage = generateScheduledMessage({ + cid: channel.cid, + scheduled_at: convertDateToTimestamp(serverScheduledAt), + }); + const schedule = mockSchedule(channel).mockResolvedValue( + scheduledResult(scheduledMessage), + ); + + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 09:00'))); + + expect(schedule).toHaveBeenCalledWith(new Date(2026, 9, 29, 9, 0)); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-menu')).not.toBeInTheDocument(), + ); + expect(getNotifications(client)).toEqual([]); + }); + + it('sends the composition with scheduled_at to the API', async () => { + const { channel, client } = await renderComposer(); + const scheduledMessage = generateScheduledMessage({ cid: channel.cid }); + useMockedApis(client, [sendScheduledMessageApi(scheduledMessage)]); + const sendMessage = vi.spyOn(channel, 'sendMessage'); + + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 13:00'))); + + await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1)); + expect(sendMessage.mock.calls[0][0].message.text).toBe('Launch moved to Monday'); + expect(sendMessage.mock.calls[0][0].scheduled_at).toEqual( + new Date(2026, 9, 29, 13, 0), + ); + await waitFor(() => expect(channel.messageComposer.textComposer.text).toBe('')); + }); + + it('refreshes the composer id when the server reports the id as taken', async () => { + const { channel, client } = await renderComposer(); + useMockedApis(client, [ + erroredScheduledMessageApi(119, ScheduledMessageErrorReason.IdTaken), + ]); + const idBefore = channel.messageComposer.id; + + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 09:00'))); + + await waitFor(() => expect(channel.messageComposer.id).not.toBe(idBefore)); + expect(channel.messageComposer.textComposer.text).toBe('Launch moved to Monday'); + }); + + it('has no axe violations', async () => { + await renderComposer(); + + const menu = await openMenu(); + + expect(await axe(menu)).toHaveNoViolations(); + }); + }); + + describe('custom time dialog', () => { + it('opens with the message preview, the default time and the time zone', async () => { + await renderComposer(); + + const dialog = await openDialog(); + + expect(dialog).toHaveTextContent('Schedule message'); + expect(dialog).toHaveTextContent('Launch moved to Monday'); + expect(screen.getByLabelText('Date')).toHaveValue('2026-10-28'); + expect(screen.getByLabelText('Time')).toHaveValue('11:00'); + expect(dialog).toHaveTextContent('Sent in your time zone (GMT)'); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); + }); + + it('shows the picked date in the design format', async () => { + await renderComposer(); + + const dialog = await openDialog(); + fireEvent.change(screen.getByLabelText('Date'), { + target: { value: '2026-11-03' }, + }); + + expect( + dialog.querySelector('.str-chat__schedule-message-dialog__date-value'), + ).toHaveTextContent('Tue, Nov 3, 2026'); + }); + + it('schedules at the picked date and time and closes', async () => { + const { channel } = await renderComposer(); + const schedule = mockSchedule(channel).mockResolvedValue( + scheduledResult(generateScheduledMessage({ cid: channel.cid })), + ); + + await openDialog(); + fireEvent.change(screen.getByLabelText('Date'), { + target: { value: '2026-11-03' }, + }); + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '16:45' } }); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(schedule).toHaveBeenCalledWith(new Date(2026, 10, 3, 16, 45)); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + }); + + it('blocks a time before the minimum lead time', async () => { + await renderComposer(); + + await openDialog(); + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '10:31' } }); + + expect(screen.getByText('Choose a later time')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); + }); + + it('blocks a time beyond the maximum lead time', async () => { + await renderComposer(); + + await openDialog(); + fireEvent.change(screen.getByLabelText('Date'), { + target: { value: '2027-06-01' }, + }); + + expect(screen.getByText('Choose an earlier time')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); + }); + + it('keeps the dialog open and shows the error when scheduling fails', async () => { + const { channel } = await renderComposer(); + const schedule = mockSchedule(channel).mockResolvedValue({ + error: new Error('failed'), + status: 'failed', + }); + + const dialog = await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(await within(dialog).findByRole('alert')).toHaveTextContent( + "Couldn't schedule message. Try again", + ); + expect(screen.getByTestId('schedule-message-dialog')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); + + schedule.mockResolvedValue( + scheduledResult(generateScheduledMessage({ cid: channel.cid })), + ); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(schedule).toHaveBeenCalledTimes(2); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + }); + + it('reports a failure once: in the dialog, not also as a notification', async () => { + const { channel, client } = await renderComposer(); + const { messageComposer } = channel; + // as the composer does, notifying of its own failure + mockSchedule(channel).mockImplementation(() => { + const error = new Error('failed'); + client.notifications.addError({ + message: 'Failed to schedule the message', + origin: { context: { composer: messageComposer }, emitter: 'MessageComposer' }, + }); + return Promise.resolve({ error, status: 'failed' }); + }); + + const dialog = await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(await within(dialog).findByRole('alert')).toHaveTextContent( + "Couldn't schedule message. Try again", + ); + expect(getNotifications(client)).toEqual([]); + }); + + it.each(['blocked', 'nothing-to-send'] as const)( + 'keeps the dialog open when the message is %s', + async (status) => { + const { channel } = await renderComposer(); + mockSchedule(channel).mockResolvedValue({ status }); + + const dialog = await openDialog(); + await act(() => + fireEvent.click(screen.getByRole('button', { name: 'Schedule' })), + ); + + expect(await within(dialog).findByRole('alert')).toHaveTextContent( + "Couldn't schedule message. Try again", + ); + expect(screen.getByTestId('schedule-message-dialog')).toBeInTheDocument(); + }, + ); + + it('opens the picker from anywhere in the field, its icons included', async () => { + await renderComposer(); + + const dialog = await openDialog(); + const time = screen.getByLabelText('Time') as HTMLInputElement; + const showPicker = vi.fn(); + time.showPicker = showPicker; + const caret = time + .closest('.str-chat__form-text-input__wrapper') + ?.querySelector('.str-chat__form-text-input__trailing'); + fireEvent.click(caret ?? dialog); + + expect(showPicker).toHaveBeenCalledTimes(1); + }); + + it('disables Schedule while offline and enables it again on reconnect', async () => { + const { client } = await renderComposer(); + + await openDialog(); + await act(() => setWSConnectionStatus(client, false)); + + expect( + screen.getByText("You're offline. Reconnect to schedule this message."), + ).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); + + await act(() => setWSConnectionStatus(client, true)); + + expect( + screen.queryByText("You're offline. Reconnect to schedule this message."), + ).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); + }); + + it('closes without scheduling on Cancel', async () => { + const { channel } = await renderComposer(); + const schedule = mockSchedule(channel); + + await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))); + + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(); + expect(schedule).not.toHaveBeenCalled(); + }); + + it('has no axe violations', async () => { + await renderComposer(); + + const dialog = await openDialog(); + + expect(await axe(dialog)).toHaveNoViolations(); + }); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx new file mode 100644 index 0000000000..2a07176636 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -0,0 +1,394 @@ +import React from 'react'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { + SCHEDULED_MESSAGE_FAILURE_REASON, + SCHEDULED_MESSAGE_STATUS, + StreamAPIError, +} from 'stream-chat'; +import type { ScheduledMessageResponse, StreamChat } from 'stream-chat'; + +import { axe } from '../../../../axe-helper'; +import { + ChatProvider, + DialogManagerProvider, + TranslationProvider, +} from '../../../context'; +import { WithComponents } from '../../../context/WithComponents'; +import { Streami18n } from '../../../i18n'; +import { + convertDateToTimestamp, + generateScheduledMessage, + getTestClientWithUser, + hydrateScheduledMessages, + mockChatContext, +} from '../../../mock-builders'; +import { SCHEDULED_MESSAGE_NOTIFICATION_TYPE } from '../utils'; +import { ScheduledMessageList } from '../ScheduledMessageList'; +import type { EditScheduledMessage } from '../types'; + +const cid = 'messaging:general'; + +const getChannel = (client: StreamChat) => client.channel('messaging', 'general'); + +const WEDNESDAY_MORNING = new Date(2026, 9, 28, 10, 30); + +const notFoundError = new StreamAPIError('not found', { + code: 16, + response: fromPartial>({ + data: { code: 16 }, + status: 404, + }), + status: 404, +}); + +type RenderActionsOptions = { + components?: Parameters[0]['overrides']; + onEdit?: EditScheduledMessage; + scheduledMessage?: ScheduledMessageResponse; +}; + +const renderActions = async ({ + components = {}, + onEdit, + scheduledMessage = generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + scheduled_at: convertDateToTimestamp(new Date(2026, 9, 29, 9, 0)), + }), +}: RenderActionsOptions = {}) => { + const client = await getTestClientWithUser({ id: 'user-id' }); + hydrateScheduledMessages(client, cid, [scheduledMessage]); + client + .channel('messaging', 'general') + .state.partialNext({ ownCapabilities: ['send-message', 'schedule-message'] }); + + const { t, tDateTimeParser } = await new Streami18n({ language: 'en' }).init(); + + const view = render( + + + + + + + + + , + ); + + return { ...view, client, scheduledMessage }; +}; + +const openActionsMenu = async () => { + await act(() => + fireEvent.click(screen.getByTestId('scheduled-message-actions-button')), + ); + + return screen.findByTestId('scheduled-message-actions-menu'); +}; + +const selectAction = async (action: string) => { + await openActionsMenu(); + await act(() => + fireEvent.click(screen.getByTestId(`scheduled-message-action-${action}`)), + ); +}; + +const getNotificationTypes = (client: StreamChat) => + client.notifications.store.getLatestValue().notifications.map(({ type }) => type); + +const getMenuLabels = () => + screen.getAllByRole('menuitem').map(({ textContent }) => textContent?.trim()); + +describe('ScheduledMessageActions', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] }); + vi.setSystemTime(WEDNESDAY_MORNING); + }); + + afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('offers an Edit button and Reschedule, Send now and Delete for a scheduled message', async () => { + await renderActions({ onEdit: vi.fn() }); + + await openActionsMenu(); + + expect(screen.getByTestId('scheduled-message-edit-button')).toBeInTheDocument(); + expect(getMenuLabels()).toEqual(['Reschedule', 'Send now', 'Delete']); + expect(screen.getAllByRole('separator')).toHaveLength(1); + }); + + it('leaves out Edit when the list has no edit handler', async () => { + await renderActions(); + + await openActionsMenu(); + + expect(screen.queryByTestId('scheduled-message-edit-button')).not.toBeInTheDocument(); + expect(getMenuLabels()).toEqual(['Reschedule', 'Send now', 'Delete']); + }); + + describe('in a channel that allows neither sending nor scheduling', () => { + // as a frozen channel does + const removeComposeCapabilities = (client: StreamChat) => + act(() => + client.channel('messaging', 'general').state.partialNext({ ownCapabilities: [] }), + ); + + it('disables Edit, keeping it focusable and saying why', async () => { + const onEdit = vi.fn(); + const { client } = await renderActions({ onEdit }); + removeComposeCapabilities(client); + + const edit = screen.getByTestId('scheduled-message-edit-button'); + fireEvent.click(edit); + + expect(edit).toHaveAttribute('aria-disabled', 'true'); + expect(edit).not.toBeDisabled(); + expect(edit).toHaveAccessibleDescription( + "Unavailable: you can't send messages in this channel", + ); + expect(onEdit).not.toHaveBeenCalled(); + }); + + it('disables Edit & reschedule of a failed message', async () => { + const onEdit = vi.fn(); + const { client } = await renderActions({ + onEdit, + scheduledMessage: generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + }); + removeComposeCapabilities(client); + + await selectAction('edit'); + + const editAndReschedule = screen.getByTestId('scheduled-message-action-edit'); + expect(editAndReschedule).toHaveAttribute('aria-disabled', 'true'); + expect(editAndReschedule).toHaveAccessibleDescription( + "Unavailable: you can't send messages in this channel", + ); + expect(onEdit).not.toHaveBeenCalled(); + // the menu stays open on the unavailable item + expect(screen.getByTestId('scheduled-message-actions-menu')).toBeInTheDocument(); + }); + }); + + it('disables the actions while the message is being sent', async () => { + await renderActions({ + scheduledMessage: generateScheduledMessage({ + cid, + status: SCHEDULED_MESSAGE_STATUS.Sending, + }), + }); + + expect(screen.getByTestId('scheduled-message-actions-button')).toBeDisabled(); + }); + + it('offers Copy and Delete for a message in a deleted channel', async () => { + await renderActions({ + onEdit: vi.fn(), + scheduledMessage: generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + }); + + await openActionsMenu(); + + expect(getMenuLabels()).toEqual(['Copy text', 'Delete']); + // Delete stands apart in a two-item menu too + expect(screen.getByRole('separator')).toBeInTheDocument(); + }); + + it('hands the scheduled message to the edit handler', async () => { + const onEdit = vi.fn(); + const { scheduledMessage } = await renderActions({ onEdit }); + + await act(() => fireEvent.click(screen.getByTestId('scheduled-message-edit-button'))); + + expect(onEdit).toHaveBeenCalledWith(scheduledMessage); + }); + + it('sends the message now and confirms it', async () => { + const { client, scheduledMessage } = await renderActions(); + const sendNow = vi + .spyOn(getChannel(client), 'sendScheduledMessageNow') + .mockResolvedValue(scheduledMessage); + + await selectAction('send_now'); + + expect(sendNow).toHaveBeenCalledWith(scheduledMessage.id); + await waitFor(() => + expect(getNotificationTypes(client)).toContain( + SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowSucceeded, + ), + ); + }); + + it('reports a send-now failure with its error', async () => { + const { client } = await renderActions(); + vi.spyOn(getChannel(client), 'sendScheduledMessageNow').mockRejectedValue( + notFoundError, + ); + + await selectAction('send_now'); + + await waitFor(() => + expect(client.notifications.store.getLatestValue().notifications).toEqual([ + expect.objectContaining({ + // the error's own copy, given where the notification is made + message: 'Already sent', + originalError: notFoundError, + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowFailed, + }), + ]), + ); + }); + + it('deletes only after the deletion is confirmed', async () => { + const { client, scheduledMessage } = await renderActions(); + const deleteScheduledMessage = vi + .spyOn(getChannel(client), 'deleteScheduledMessage') + .mockResolvedValue(scheduledMessage); + + await selectAction('delete'); + const alert = await screen.findByTestId('delete-scheduled-message-alert'); + + expect(alert).toHaveTextContent('Delete scheduled message?'); + expect(alert).toHaveTextContent("This message won't be sent. This can't be undone."); + expect(deleteScheduledMessage).not.toHaveBeenCalled(); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Delete' }))); + + expect(deleteScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id); + }); + + it('keeps the message when the deletion is cancelled', async () => { + const { client } = await renderActions(); + const deleteScheduledMessage = vi.spyOn(getChannel(client), 'deleteScheduledMessage'); + + await selectAction('delete'); + await screen.findByTestId('delete-scheduled-message-alert'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))); + + expect(deleteScheduledMessage).not.toHaveBeenCalled(); + expect( + screen.queryByTestId('delete-scheduled-message-alert'), + ).not.toBeInTheDocument(); + }); + + it('reschedules from the dialog pre-filled with the current time', async () => { + const { client, scheduledMessage } = await renderActions(); + const updateScheduledMessage = vi + .spyOn(getChannel(client), 'updateScheduledMessage') + .mockResolvedValue(scheduledMessage); + + await selectAction('reschedule'); + const dialog = await screen.findByTestId('schedule-message-dialog'); + + expect(dialog).toHaveTextContent('Reschedule message'); + expect(dialog).toHaveTextContent('Scheduled for Thu, Oct 29 at 09:00'); + expect(screen.getByLabelText('Date')).toHaveValue('2026-10-29'); + expect(screen.getByLabelText('Time')).toHaveValue('09:00'); + + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { + scheduled_at: new Date(2026, 9, 29, 14, 30), + }); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + }); + + it('keeps the reschedule dialog open and reports a failure', async () => { + const { client } = await renderActions(); + vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( + notFoundError, + ); + + await selectAction('reschedule'); + await screen.findByTestId('schedule-message-dialog'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + // the error's own copy: the message was sent meanwhile + expect(await screen.findByText('Already sent')).toBeInTheDocument(); + // the dialog reports it, so it is not repeated as a notification + expect(getNotificationTypes(client)).toEqual([]); + }); + + it('reports a reschedule failure without a specific reason generically', async () => { + const { client } = await renderActions(); + vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( + new Error('Network Error'), + ); + + await selectAction('reschedule'); + await screen.findByTestId('schedule-message-dialog'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + expect( + await screen.findByText("Couldn't reschedule the message. Try again"), + ).toBeInTheDocument(); + }); + + it('explains in place of the time zone why a reschedule is too soon', async () => { + await renderActions(); + + await selectAction('reschedule'); + const dialog = await screen.findByTestId('schedule-message-dialog'); + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '00:00' } }); + fireEvent.change(screen.getByLabelText('Date'), { target: { value: '2020-01-01' } }); + + expect(within(dialog).getByRole('alert')).toHaveTextContent( + "Pick a later time. Editing can't send a message right away.", + ); + expect(dialog).not.toHaveTextContent('Sent in your time zone'); + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); + }); + + it('copies the text of a message from a deleted channel', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText }, + }); + await renderActions({ + scheduledMessage: generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + message: { custom: {}, text: 'Launch moved to Monday' }, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + }); + + await selectAction('copy'); + + expect(writeText).toHaveBeenCalledWith('Launch moved to Monday'); + }); + + it('has no accessibility violations with the menu open', async () => { + const { container } = await renderActions({ onEdit: vi.fn() }); + + await openActionsMenu(); + + expect(await axe(container)).toHaveNoViolations(); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx new file mode 100644 index 0000000000..1a43ece265 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -0,0 +1,478 @@ +import React from 'react'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { SCHEDULED_MESSAGE_FAILURE_REASON, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; +import type { PaginatorState, ScheduledMessageResponse, StreamChat } from 'stream-chat'; + +import { axe } from '../../../../axe-helper'; +import { + ChatProvider, + DialogManagerProvider, + TranslationProvider, +} from '../../../context'; +import { WithComponents } from '../../../context/WithComponents'; +import { Streami18n } from '../../../i18n'; +import { + convertDateToTimestamp, + generatePoll, + generateScheduledMessage, + getScheduledMessagesPaginator, + getTestClientWithUser, + hydrateScheduledMessages, + mockChatContext, +} from '../../../mock-builders'; +import { ScheduledMessageList } from '../ScheduledMessageList'; +import type { EditScheduledMessage, ScheduledMessageItemProps } from '../types'; + +const cid = 'messaging:general'; + +const WEDNESDAY_MORNING = new Date(2026, 9, 28, 10, 30); + +const atLocalTime = (day: number, hour: number) => + convertDateToTimestamp(new Date(2026, 9, day, hour, 0)); + +type RenderListOptions = { + client?: StreamChat; + components?: Parameters[0]['overrides']; + onEdit?: EditScheduledMessage; + scheduledMessages?: ScheduledMessageResponse[]; + searchQuery?: string; +}; + +const renderList = async ({ + client: clientArg, + components = {}, + onEdit, + scheduledMessages = [], + searchQuery, +}: RenderListOptions = {}) => { + const client = clientArg ?? (await getTestClientWithUser({ id: 'user-id' })); + hydrateScheduledMessages(client, cid, scheduledMessages); + + const { t, tDateTimeParser } = await new Streami18n({ language: 'en' }).init(); + + const view = render( + + + + + + + + + , + ); + + return { ...view, client }; +}; + +const getGroupHeaders = () => + screen.getAllByRole('heading', { level: 3 }).map(({ textContent }) => textContent); + +const getPaginator = (client: StreamChat) => getScheduledMessagesPaginator(client, cid); + +const setPaginatorState = ( + client: StreamChat, + state: Partial>, +) => act(() => getPaginator(client).state.partialNext(state)); + +const setNextCursor = (client: StreamChat) => + setPaginatorState(client, { hasMoreTail: true }); + +describe('ScheduledMessageList', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] }); + vi.setSystemTime(WEDNESDAY_MORNING); + }); + + afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + describe('in a channel that takes no scheduled messages', () => { + const setCapabilities = ( + client: StreamChat, + ownCapabilities: string[], + frozen = false, + ) => + act(() => { + const channel = client.channel('messaging', 'general'); + channel.data = { ...channel.data, frozen }; + channel.state.partialNext({ ownCapabilities }); + }); + + it('says a frozen channel will not send them', async () => { + const { client } = await renderList({ + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + setCapabilities(client, [], true); + + expect(screen.getByRole('alert')).toHaveTextContent( + "This channel is frozen. Scheduled messages won't be sent", + ); + }); + + it('says the user cannot schedule here, even with nothing scheduled', async () => { + const { client } = await renderList(); + + setCapabilities(client, ['send-message']); + + expect(screen.getByRole('alert')).toHaveTextContent( + "You can't schedule messages in this channel", + ); + expect(screen.getByText('No scheduled messages')).toBeInTheDocument(); + }); + + it('shows nothing while the channel can schedule', async () => { + const { client } = await renderList(); + + setCapabilities(client, ['send-message', 'schedule-message']); + + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + }); + + it('shows the empty state without scheduled messages', async () => { + await renderList(); + + expect(screen.getByText('No scheduled messages')).toBeInTheDocument(); + expect( + screen.getByText( + 'Click the arrow next to the send button in a channel to schedule a message.', + ), + ).toBeInTheDocument(); + }); + + it('shows skeleton rows while the first page loads', async () => { + const { client } = await renderList(); + + setPaginatorState(client, { isLoading: true, items: undefined }); + + expect(screen.queryByText('No scheduled messages')).not.toBeInTheDocument(); + expect( + screen.getByRole('status', { name: 'Loading scheduled messages' }), + ).toBeInTheDocument(); + }); + + it('shows the empty state while a later reload runs', async () => { + const { client } = await renderList(); + + setPaginatorState(client, { isLoading: true }); + + expect(screen.getByText('No scheduled messages')).toBeInTheDocument(); + expect( + screen.queryByTestId('scheduled-message-list-loading'), + ).not.toBeInTheDocument(); + }); + + it('shows the load error and reloads on retry', async () => { + const { client } = await renderList(); + const reload = vi.spyOn(getPaginator(client), 'reload').mockResolvedValue(undefined); + + setPaginatorState(client, { + isLoading: false, + items: undefined, + lastQueryError: new Error('offline'), + }); + fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + + expect(screen.getByText("Couldn't load scheduled messages")).toBeInTheDocument(); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it('keeps showing stored messages when a reload fails', async () => { + const { client } = await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }), + ], + }); + + setPaginatorState(client, { lastQueryError: new Error('offline') }); + + expect(screen.getByText('Launch moved to Monday')).toBeInTheDocument(); + expect( + screen.queryByText("Couldn't load scheduled messages"), + ).not.toBeInTheDocument(); + }); + + it('shows only the messages matching the search query', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }), + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + searchQuery: 'launch', + }); + + expect(screen.getByText('Launch moved to Monday')).toBeInTheDocument(); + expect(screen.queryByText('Lunch at noon')).not.toBeInTheDocument(); + }); + + it('shows no results when the search matches nothing', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }), + ], + searchQuery: 'friday', + }); + + expect(screen.getByText('No messages found')).toBeInTheDocument(); + expect(screen.queryByText('No scheduled messages')).not.toBeInTheDocument(); + }); + + it('loads further pages while the search matches nothing loaded', async () => { + const { client } = await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + searchQuery: 'friday', + }); + const query = vi.spyOn(client, 'queryScheduledMessages').mockResolvedValue({ + duration: '', + scheduled_messages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Friday demo' } }), + ], + } as never); + + setNextCursor(client); + + expect(await screen.findByText('Friday demo')).toBeInTheDocument(); + expect(query).toHaveBeenCalledTimes(1); + }); + + it('stops loading further pages when one fails', async () => { + const { client } = await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + searchQuery: 'friday', + }); + const query = vi + .spyOn(client, 'queryScheduledMessages') + .mockRejectedValue(new Error('offline')); + + setNextCursor(client); + + expect(await screen.findByText('No messages found')).toBeInTheDocument(); + expect(query).toHaveBeenCalledTimes(1); + }); + + it('renders the list states through the list-state slots', async () => { + const { client } = await renderList({ + components: { + EmptyListIndicator: () =>
Nothing here
, + FirstPageLoadingIndicator: () =>
Loading here
, + }, + }); + + expect(screen.getByText('Nothing here')).toBeInTheDocument(); + + setPaginatorState(client, { isLoading: true, items: undefined }); + + expect(screen.getByText('Loading here')).toBeInTheDocument(); + }); + + it('lists failed messages first, then one group per day', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid, scheduled_at: atLocalTime(29, 9) }), + generateScheduledMessage({ cid, scheduled_at: atLocalTime(30, 13) }), + generateScheduledMessage({ + cid, + scheduled_at: atLocalTime(29, 13), + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + ], + }); + + expect(getGroupHeaders()).toEqual(['Failed', 'Tomorrow', 'Friday']); + }); + + it('shows the send time and preview of each message', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + scheduled_at: atLocalTime(29, 9), + }), + ], + }); + + const item = screen.getByTestId('scheduled-message-item'); + + expect(within(item).getByText('Launch moved to Monday')).toBeInTheDocument(); + expect(within(item).getByText('Send Thu, Oct 29 at 09:00')).toBeInTheDocument(); + expect(within(item).queryByText('Scheduled')).not.toBeInTheDocument(); + }); + + describe('a scheduled poll', () => { + const scheduledPoll = () => + generateScheduledMessage({ + cid, + message: { custom: {}, poll_id: 'poll-1', text: '' }, + }); + + // the row reads "Poll", as a channel preview does; the composer preview shows the question + it('loads the poll it carries only the ID of, and shows it as a poll', async () => { + const client = await getTestClientWithUser({ id: 'user-id' }); + const getPoll = vi.spyOn(client, 'getPoll').mockResolvedValue({ + duration: '', + poll: generatePoll({ + created_by: { id: 'user-id' }, + id: 'poll-1', + name: 'Where do we eat?', + vote_count: 0, + }), + } as never); + + await renderList({ client, scheduledMessages: [scheduledPoll()] }); + + expect(await screen.findByText('Poll')).toBeInTheDocument(); + expect(getPoll).toHaveBeenCalledWith({ poll_id: 'poll-1' }); + }); + + it('takes a poll the client already holds without loading it', async () => { + const client = await getTestClientWithUser({ id: 'user-id' }); + const getPoll = vi.spyOn(client, 'getPoll').mockResolvedValue({ + duration: '', + poll: generatePoll({ id: 'poll-1', name: 'Pizza or pasta?' }), + } as never); + await client.polls.getPoll('poll-1'); + getPoll.mockClear(); + + await renderList({ client, scheduledMessages: [scheduledPoll()] }); + + expect(screen.getByText('Poll')).toBeInTheDocument(); + expect(getPoll).not.toHaveBeenCalled(); + }); + }); + + it('summarises attachments when the message has no text', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { + attachments: [ + { custom: {}, image_url: 'https://example.com/a.png', type: 'image' }, + ], + custom: {}, + text: '', + }, + }), + ], + }); + + expect(screen.getByText('Image')).toBeInTheDocument(); + }); + + it('marks a message that is being sent', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid, status: SCHEDULED_MESSAGE_STATUS.Sending }), + ], + }); + + expect(screen.getByText('Sending...')).toBeInTheDocument(); + }); + + it('explains why a message failed', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + ], + }); + + const item = screen.getByTestId('scheduled-message-item'); + + expect(item).toHaveClass('str-chat__scheduled-message-item--failed'); + expect(within(item).getByText('This channel is frozen')).toBeInTheDocument(); + }); + + it('loads the next page when scrolled to the end', async () => { + const { client } = await renderList({ + scheduledMessages: [generateScheduledMessage({ cid })], + }); + const query = vi + .spyOn(client, 'queryScheduledMessages') + .mockResolvedValue({ duration: '', scheduled_messages: [] } as never); + setNextCursor(client); + const list = screen.getByTestId('scheduled-message-list'); + Object.defineProperties(list, { + clientHeight: { configurable: true, value: 100 }, + offsetParent: { configurable: true, value: document.body }, + scrollTop: { configurable: true, value: 0, writable: true }, + }); + Object.defineProperty(list.firstElementChild, 'scrollHeight', { + configurable: true, + value: 1000, + }); + + list.scrollTop = 900; + fireEvent.scroll(list); + + await waitFor(() => expect(query).toHaveBeenCalledTimes(1)); + }); + + it('renders items through the ScheduledMessageItem slot', async () => { + const CustomItem = ({ scheduledMessage }: ScheduledMessageItemProps) => ( +
{scheduledMessage.id}
+ ); + + await renderList({ + components: { ScheduledMessageItem: CustomItem }, + scheduledMessages: [generateScheduledMessage({ cid, id: 'scheduled-id' })], + }); + + expect(screen.getByTestId('custom-item')).toHaveTextContent('scheduled-id'); + }); + + it.each([ + ['loading', { isLoading: true, items: undefined }], + [ + 'load error', + { isLoading: false, items: undefined, lastQueryError: new Error('offline') }, + ], + ])('has no accessibility violations in the %s state', async (_, state) => { + const { client, container } = await renderList(); + + setPaginatorState(client, state); + + expect(await axe(container)).toHaveNoViolations(); + }); + + it('has no accessibility violations', async () => { + const { container } = await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid }), + generateScheduledMessage({ cid, status: SCHEDULED_MESSAGE_STATUS.Failed }), + ], + }); + + expect(await axe(container)).toHaveNoViolations(); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx new file mode 100644 index 0000000000..9ee95b1aa0 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -0,0 +1,429 @@ +import '../../..'; +import React from 'react'; +import type { PropsWithChildren } from 'react'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { formatMessage, ScheduledMessageEventType, Thread } from 'stream-chat'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import type { ScheduledMessageListDialogProps } from '../ScheduledMessageListDialog'; + +import { axe } from '../../../../axe-helper'; +import { AriaLiveAnnouncerContext } from '../../Accessibility'; +import type { AriaLiveAnnounce } from '../../Accessibility'; +import { Channel } from '../../Channel'; +import { Chat } from '../../Chat'; +import { WithComponents } from '../../../context/WithComponents'; +import { MessageComposer } from '../../MessageComposer'; +import { ThreadProvider } from '../../Threads'; +import { + convertDateToTimestamp, + dispatchScheduledMessageEvent, + generateMessage, + generateScheduledMessage, + generateUser, + getScheduledMessagesPaginator, + hydrateScheduledMessages, + initClientWithChannels, +} from '../../../mock-builders'; + +const user = generateUser({ id: 'user-id' }); + +const cid = 'messaging:general'; +const parentId = 'parent-1'; + +const threadReply = () => + generateScheduledMessage({ + cid, + message: { custom: {}, parent_id: parentId, text: 'reply' }, + }); + +type RenderComposerOptions = { + announce?: AriaLiveAnnounce; + awaitsScheduledMessages?: boolean; + canSchedule?: boolean; + components?: Parameters[0]['overrides']; + inThread?: boolean; + scheduledMessages?: ScheduledMessageResponse[]; +}; + +const renderComposer = async ({ + announce, + awaitsScheduledMessages = true, + canSchedule = true, + components = {}, + inThread = false, + scheduledMessages = [], +}: RenderComposerOptions = {}) => { + const ownCapabilities = canSchedule + ? ['send-message', 'schedule-message'] + : ['send-message']; + const { + channels: [channel], + client, + } = await initClientWithChannels({ + channelsData: [ + { + channel: { id: 'general', own_capabilities: ownCapabilities, type: 'messaging' }, + }, + ], + customUser: user, + }); + vi.spyOn(client, 'queryScheduledMessages').mockResolvedValue( + fromPartial({ duration: '', scheduled_messages: scheduledMessages }), + ); + + const thread = inThread + ? new Thread({ + channel, + client, + parentMessage: formatMessage(generateMessage({ cid, id: parentId })), + }) + : undefined; + + const ThreadScope = ({ children }: PropsWithChildren) => + thread ? {children} : children; + + await act(() => { + render( + + + + + + + + + + + , + ); + }); + + if (awaitsScheduledMessages) { + await waitFor(() => + expect(getScheduledMessagesPaginator(client, cid).hasLoadedPage).toBe(true), + ); + } + + return { channel, client }; +}; + +const AnnouncerScope = ({ + announce, + children, +}: PropsWithChildren<{ announce?: AriaLiveAnnounce }>) => + announce ? ( + + {children} + + ) : ( + children + ); + +const queryBanner = () => screen.queryByTestId('scheduled-messages-banner'); + +const ON_JANUARY_15 = convertDateToTimestamp(new Date(2030, 0, 15, 9, 0)); + +describe('ScheduledMessagesBanner', () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it('stays hidden without scheduled messages', async () => { + await renderComposer(); + + expect(queryBanner()).not.toBeInTheDocument(); + }); + + it('counts the scheduled messages of the channel', async () => { + await renderComposer({ + scheduledMessages: [ + generateScheduledMessage({ cid }), + generateScheduledMessage({ cid }), + threadReply(), + ], + }); + + expect(queryBanner()).toHaveTextContent('2 scheduled messages'); + }); + + it('shows when the only scheduled message is sent, with View', async () => { + await renderComposer({ + scheduledMessages: [generateScheduledMessage({ cid, scheduled_at: ON_JANUARY_15 })], + }); + + expect(queryBanner()).toHaveTextContent('Scheduled for Tue, Jan 15 at 09:00'); + expect(screen.getByRole('button', { name: 'View' })).toBeInTheDocument(); + }); + + it('is hidden while the composer edits a scheduled message', async () => { + const scheduledMessage = generateScheduledMessage({ cid }); + const { channel } = await renderComposer({ scheduledMessages: [scheduledMessage] }); + + await act(() => channel.messageComposer.editScheduledMessage(scheduledMessage)); + + expect(queryBanner()).not.toBeInTheDocument(); + }); + + it('announces a change, but not the banner the channel opens with', async () => { + const announce = vi.fn(() => () => undefined); + const scheduledMessage = generateScheduledMessage({ + cid, + scheduled_at: ON_JANUARY_15, + }); + const { client } = await renderComposer({ + announce, + scheduledMessages: [scheduledMessage], + }); + + expect(announce).not.toHaveBeenCalled(); + + act(() => + dispatchScheduledMessageEvent({ + client, + scheduledMessage: { ...scheduledMessage, status: 'failed' }, + type: ScheduledMessageEventType.Failed, + }), + ); + + await waitFor(() => expect(announce).toHaveBeenCalledWith('1 failed to send')); + }); + + it('switches to the failed count when a scheduled message failed', async () => { + await renderComposer({ + scheduledMessages: [ + generateScheduledMessage({ cid }), + generateScheduledMessage({ cid, status: 'failed' }), + ], + }); + + expect(queryBanner()).toHaveTextContent('1 failed to send'); + expect(queryBanner()).not.toHaveTextContent('scheduled messages'); + expect(queryBanner()).toHaveClass('str-chat__scheduled-messages-banner--failed'); + }); + + it('leaves out the failed count when nothing failed', async () => { + await renderComposer({ scheduledMessages: [generateScheduledMessage({ cid })] }); + + expect(queryBanner()).not.toHaveTextContent('failed'); + }); + + it('disappears when the store is reset for another user', async () => { + const { client } = await renderComposer({ + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + act(() => getScheduledMessagesPaginator(client, cid).resetState()); + + expect(queryBanner()).not.toBeInTheDocument(); + }); + + it('follows the scheduled messages of the next user after a reset', async () => { + const { client } = await renderComposer({ + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + act(() => getScheduledMessagesPaginator(client, cid).resetState()); + act(() => + hydrateScheduledMessages(client, cid, [ + generateScheduledMessage({ cid }), + generateScheduledMessage({ cid }), + ]), + ); + + expect(queryBanner()).toHaveTextContent('2 scheduled messages'); + }); + + it('counts only the replies of the thread in a thread composer', async () => { + await renderComposer({ + inThread: true, + scheduledMessages: [ + generateScheduledMessage({ cid }), + threadReply(), + threadReply(), + ], + }); + + expect(queryBanner()).toHaveTextContent('2 scheduled replies'); + }); + + it('stays hidden without the schedule-message capability', async () => { + await renderComposer({ + canSchedule: false, + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + expect(queryBanner()).not.toBeInTheDocument(); + }); + + it('shows failed scheduled messages without the schedule-message capability', async () => { + await renderComposer({ + canSchedule: false, + scheduledMessages: [generateScheduledMessage({ cid, status: 'failed' })], + }); + + expect(queryBanner()).toHaveTextContent('1 failed to send'); + expect(queryBanner()).toHaveTextContent('View all'); + }); + + it('updates when scheduled message events arrive', async () => { + const { client } = await renderComposer(); + const scheduledMessage = generateScheduledMessage({ cid }); + + act(() => + dispatchScheduledMessageEvent({ + client, + scheduledMessage, + type: ScheduledMessageEventType.Created, + }), + ); + + await waitFor(() => expect(queryBanner()).toHaveTextContent('Scheduled for')); + + act(() => + dispatchScheduledMessageEvent({ + client, + scheduledMessage: { ...scheduledMessage, status: 'sent' }, + type: ScheduledMessageEventType.Sent, + }), + ); + + await waitFor(() => expect(queryBanner()).not.toBeInTheDocument()); + }); + + it('opens the scheduled message list from View', async () => { + await renderComposer({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }), + ], + }); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View' }))); + + const dialog = await screen.findByTestId('scheduled-message-list-dialog'); + + expect(dialog).toHaveTextContent('Scheduled messages'); + expect(dialog).toHaveTextContent('Launch moved to Monday'); + }); + + it('filters the scheduled message list with the search field', async () => { + await renderComposer({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }), + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + }); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View all' }))); + const dialog = await screen.findByTestId('scheduled-message-list-dialog'); + const search = within(dialog).getByRole('searchbox', { name: 'Search' }); + fireEvent.change(search, { target: { value: 'launch' } }); + + expect(dialog).toHaveTextContent('Launch moved to Monday'); + expect(dialog).not.toHaveTextContent('Lunch at noon'); + + // a button, so the keyboard reaches it + fireEvent.click(within(dialog).getByRole('button', { name: 'Clear search' })); + + expect(search).toHaveValue(''); + expect(search).toHaveFocus(); + // kept in place so the field keeps its height, hidden from pointer and keyboard + expect(screen.getByRole('button', { name: 'Clear search' })).toHaveClass( + 'str-chat__form-text-input__clear-button--hidden', + ); + expect(dialog).toHaveTextContent('Lunch at noon'); + }); + + it('titles the list as replies in a thread', async () => { + await renderComposer({ inThread: true, scheduledMessages: [threadReply()] }); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View' }))); + + expect(await screen.findByTestId('scheduled-message-list-dialog')).toHaveTextContent( + 'Scheduled replies', + ); + }); + + it('opens what the ScheduledMessageListDialog slot renders', async () => { + const scheduledMessage = generateScheduledMessage({ cid }); + const ScheduledMessageListDialog = vi.fn( + ({ close, onEdit, open }: ScheduledMessageListDialogProps) => + open ? ( +
+ + +
+ ) : null, + ); + const { channel } = await renderComposer({ + components: { ScheduledMessageListDialog }, + scheduledMessages: [scheduledMessage], + }); + + expect(screen.queryByTestId('custom-list')).not.toBeInTheDocument(); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View' }))); + + expect(screen.getByTestId('custom-list')).toBeInTheDocument(); + expect(ScheduledMessageListDialog).toHaveBeenLastCalledWith( + expect.objectContaining({ cid, open: true, parentId: undefined }), + undefined, + ); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Close list' }))); + + expect(screen.queryByTestId('custom-list')).not.toBeInTheDocument(); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View' }))); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Edit it' }))); + + // editing closes the list and opens the message in the composer + expect(screen.queryByTestId('custom-list')).not.toBeInTheDocument(); + expect(channel.messageComposer.editedScheduledMessage?.id).toBe(scheduledMessage.id); + }); + + it('can be hidden through the ScheduledMessagesBanner slot', async () => { + const { client } = await renderComposer({ + awaitsScheduledMessages: false, + components: { ScheduledMessagesBanner: null }, + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + expect(queryBanner()).not.toBeInTheDocument(); + expect(client.queryScheduledMessages).not.toHaveBeenCalled(); + }); + + it('has no accessibility violations', async () => { + await renderComposer({ scheduledMessages: [generateScheduledMessage({ cid })] }); + + expect(await axe(queryBanner() as HTMLElement)).toHaveNoViolations(); + }); + + it('has no accessibility violations with failed messages', async () => { + await renderComposer({ + scheduledMessages: [generateScheduledMessage({ cid, status: 'failed' })], + }); + + expect(await axe(queryBanner() as HTMLElement)).toHaveNoViolations(); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts new file mode 100644 index 0000000000..e9fcc0aa8e --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -0,0 +1,182 @@ +import { SCHEDULED_MESSAGE_FAILURE_REASON } from 'stream-chat'; +import type { Channel } from 'stream-chat'; + +import { convertDateToTimestamp, generateScheduledMessage } from '../../../mock-builders'; +import { + formatTimeZoneOffset, + fromInputValues, + getDefaultScheduledAt, + getScheduledMessageActions, + getSchedulePresets, + getScheduleTimeBounds, + getScheduleTimeError, + groupScheduledMessages, + searchScheduledMessages, + translateScheduledMessageFailureReason, +} from '../utils'; + +const at = (day: number, hour: number) => new Date(2026, 9, day, hour, 0); +const scheduledAt = (day: number, hour: number) => ({ + scheduled_at: convertDateToTimestamp(at(day, hour)), +}); +const withLimits = (minLeadTimeSeconds: number, maxLeadTimeSeconds: number) => + ({ + serverConfig: { + scheduled_messages_max_lead_time_seconds: maxLeadTimeSeconds, + scheduled_messages_max_per_channel: 10, + scheduled_messages_max_per_user: 100, + scheduled_messages_min_lead_time_seconds: minLeadTimeSeconds, + }, + }) as unknown as Channel; + +describe('scheduled message utils', () => { + it('groups pending messages by day and puts the failed ones first', () => { + const morning = generateScheduledMessage(scheduledAt(29, 9)); + const evening = generateScheduledMessage(scheduledAt(29, 18)); + const nextDay = generateScheduledMessage(scheduledAt(30, 9)); + const failed = generateScheduledMessage({ ...scheduledAt(28, 9), status: 'failed' }); + + const groups = groupScheduledMessages([morning, evening, nextDay, failed]); + + expect(groups.map(({ key }) => key)).toEqual(['failed', '2026-10-29', '2026-10-30']); + expect(groups[0].day).toBeUndefined(); + expect(groups[1].scheduledMessages).toEqual([morning, evening]); + }); + + it('searches the text case-insensitively and ignores a blank query', () => { + const lunch = generateScheduledMessage({ + message: { custom: {}, text: 'Lunch at noon' }, + }); + const launch = generateScheduledMessage({ message: { custom: {}, text: 'Launch' } }); + + expect(searchScheduledMessages([lunch, launch], ' LUNCH ')).toEqual([lunch]); + expect(searchScheduledMessages([lunch, launch], ' ')).toEqual([lunch, launch]); + }); + + describe('time bounds', () => { + it('starts a minute after the minimum lead time and ends at the maximum', () => { + const now = at(28, 10); + + const { earliest, latest } = getScheduleTimeBounds(withLimits(60, 3600), now); + + expect(earliest).toEqual(new Date(now.getTime() + 2 * 60 * 1000)); + expect(latest).toEqual(new Date(now.getTime() + 3600 * 1000)); + }); + + it('leaves the latest time open for a channel without limits', () => { + expect(getScheduleTimeBounds({} as Channel, at(28, 10)).latest).toBeUndefined(); + }); + + it('reports a time outside the bounds', () => { + const bounds = { earliest: at(28, 10), latest: at(29, 10) }; + + expect(getScheduleTimeError(at(28, 9), bounds)).toBe('tooSoon'); + expect(getScheduleTimeError(at(30, 9), bounds)).toBe('tooFar'); + expect(getScheduleTimeError(at(28, 12), bounds)).toBeUndefined(); + }); + + it('defaults to the next full hour after the earliest time', () => { + expect(getDefaultScheduledAt({ earliest: new Date(2026, 9, 28, 10, 25) })).toEqual( + at(28, 11), + ); + }); + }); + + describe('presets', () => { + const open = { earliest: new Date(0) }; + + it('offers tomorrow morning and afternoon and next Monday morning', () => { + // a Wednesday + expect(getSchedulePresets(at(28, 10), open)).toEqual([ + at(29, 9), + at(29, 13), + new Date(2026, 10, 2, 9, 0), + ]); + }); + + it('leaves out next Monday when it is tomorrow', () => { + // a Sunday + expect(getSchedulePresets(new Date(2026, 10, 1, 10, 0), open)).toHaveLength(2); + }); + + it('leaves out a preset outside the bounds', () => { + expect(getSchedulePresets(at(28, 10), { earliest: at(29, 12) })).toEqual([ + at(29, 13), + new Date(2026, 10, 2, 9, 0), + ]); + }); + }); + + describe('actions', () => { + it('offers every action for a pending message, without edit when it cannot open', () => { + const pending = generateScheduledMessage(); + + expect(getScheduledMessageActions(pending, true)).toEqual([ + 'edit', + 'reschedule', + 'send_now', + 'delete', + ]); + expect(getScheduledMessageActions(pending, false)).not.toContain('edit'); + }); + + it('offers nothing while the message is being sent', () => { + expect( + getScheduledMessageActions(generateScheduledMessage({ status: 'sending' }), true), + ).toEqual([]); + }); + + it('offers copy and delete for a message whose channel was deleted', () => { + const failed = generateScheduledMessage({ + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + status: 'failed', + }); + + expect(getScheduledMessageActions(failed, true)).toEqual(['copy', 'delete']); + }); + }); + + it('explains a failure, except when the user was deleted', () => { + const t = ((_key: string, defaultValue: string) => defaultValue) as never; + + expect( + translateScheduledMessageFailureReason( + t, + SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + ), + ).toBe('This channel is frozen'); + expect( + translateScheduledMessageFailureReason( + t, + SCHEDULED_MESSAGE_FAILURE_REASON.UserDeleted, + ), + ).toBeUndefined(); + expect(translateScheduledMessageFailureReason(t)).toBe("Couldn't send. Try again"); + expect( + translateScheduledMessageFailureReason( + t, + SCHEDULED_MESSAGE_FAILURE_REASON.InternalError, + ), + ).toBe('Something went wrong. Try again'); + expect( + translateScheduledMessageFailureReason( + t, + SCHEDULED_MESSAGE_FAILURE_REASON.PendingNotSupported, + ), + ).toBe('This channel now needs approval. Schedule it again'); + }); + + it('reads the date and time inputs, rejecting an invalid value', () => { + expect(fromInputValues('2026-10-28', '14:30')).toEqual(new Date(2026, 9, 28, 14, 30)); + expect(fromInputValues('2026-10-28')).toEqual(at(28, 0)); + expect(fromInputValues('', '14:30')).toBeUndefined(); + expect(fromInputValues('not-a-date', '14:30')).toBeUndefined(); + }); + + it('formats the time zone offset', () => { + const date = new Date(); + vi.spyOn(date, 'getTimezoneOffset').mockReturnValue(-330); + + expect(formatTimeZoneOffset(date)).toBe('GMT+5:30'); + }); +}); diff --git a/src/components/ScheduledMessages/hooks/index.ts b/src/components/ScheduledMessages/hooks/index.ts new file mode 100644 index 0000000000..57ca671146 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/index.ts @@ -0,0 +1,2 @@ +export * from './useCanScheduleMessage'; +export * from './useScheduledMessages'; diff --git a/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts new file mode 100644 index 0000000000..ad6f9122ff --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts @@ -0,0 +1,56 @@ +import { useMemo } from 'react'; +import type { + MessageComposerState, + ScheduledMessagePaginatorsManagerState, +} from 'stream-chat'; + +import { useChatContext } from '../../../context'; +import { useStateStore } from '../../../store'; +import { useChannelCapabilities } from '../../Channel/hooks/useChannelCapabilities'; +import { useMessageComposerController } from '../../MessageComposer/hooks/useMessageComposerController'; +import { isComposerEditing } from '../utils'; + +export const SCHEDULE_MESSAGE_CAPABILITY = 'schedule-message'; + +const selectIsDisabled = ({ isDisabled }: ScheduledMessagePaginatorsManagerState) => ({ + isDisabled, +}); + +const selectIsEditing = (state: MessageComposerState) => ({ + isEditing: isComposerEditing(state), +}); + +/** + * Whether the composition can be scheduled: the channel allows it, the feature is on, nothing is + * being edited and the composition holds nothing that cannot be scheduled (a command, a poll, a + * location). `scheduleBlockReason` reads three stores, so each is subscribed to. + */ +export const useCanScheduleMessage = () => { + const { client } = useChatContext(); + const messageComposer = useMessageComposerController(); + const { channel, locationComposer, textComposer } = messageComposer; + const channelCapabilities = useChannelCapabilities({ cid: channel.cid }); + + const selectBlockReason = useMemo( + () => () => ({ scheduleBlockReason: messageComposer.scheduleBlockReason }), + [messageComposer], + ); + + const { isDisabled } = useStateStore( + client.scheduledMessagePaginators.state, + selectIsDisabled, + ); + const { isEditing } = useStateStore(messageComposer.state, selectIsEditing); + const blockReasons = [ + useStateStore(messageComposer.state, selectBlockReason).scheduleBlockReason, + useStateStore(textComposer.state, selectBlockReason).scheduleBlockReason, + useStateStore(locationComposer.state, selectBlockReason).scheduleBlockReason, + ]; + + return ( + channelCapabilities.has(SCHEDULE_MESSAGE_CAPABILITY) && + !isDisabled && + !isEditing && + !blockReasons.some(Boolean) + ); +}; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessagePreview.ts b/src/components/ScheduledMessages/hooks/useScheduledMessagePreview.ts new file mode 100644 index 0000000000..8c94534344 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessagePreview.ts @@ -0,0 +1,55 @@ +import { useEffect, useMemo, useState } from 'react'; +import { toScheduledMessagePreview } from 'stream-chat'; +import type { + LocalMessage, + Poll, + PollState, + ScheduledMessageResponse, +} from 'stream-chat'; + +import { useChatContext } from '../../../context'; +import { useStateStore } from '../../../store'; + +const selectPollPreview = ({ created_by, name, vote_count }: PollState) => ({ + created_by, + name, + vote_count, +}); + +/** + * The scheduled message as a message to preview. A scheduled poll carries only its ID, so the poll + * is taken from `client.polls`, loaded once when it is not there yet. + */ +export const useScheduledMessagePreview = ( + scheduledMessage: ScheduledMessageResponse, +): LocalMessage => { + const { client } = useChatContext(); + const pollId = scheduledMessage.message.poll_id; + const [loadedPoll, setLoadedPoll] = useState(); + const poll = pollId + ? (client.polls.fromState(pollId) ?? + (loadedPoll?.id === pollId ? loadedPoll : undefined)) + : undefined; + + useEffect(() => { + if (!pollId || client.polls.fromState(pollId)) return; + let isActive = true; + client.polls + .getPoll(pollId) + .then((fetched) => { + if (isActive && fetched) setLoadedPoll(fetched); + }) + .catch(() => undefined); + return () => { + isActive = false; + }; + }, [client, pollId]); + + const pollPreview = useStateStore(poll?.state, selectPollPreview); + + return useMemo(() => { + const preview = toScheduledMessagePreview(scheduledMessage); + if (!pollId || !pollPreview) return preview; + return { ...preview, poll: { ...pollPreview, id: pollId } as LocalMessage['poll'] }; + }, [pollId, pollPreview, scheduledMessage]); +}; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts new file mode 100644 index 0000000000..8b8d80dca4 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts @@ -0,0 +1,88 @@ +import { useEffect, useMemo } from 'react'; +import { ScheduledMessagePaginator } from 'stream-chat'; +import type { PaginatorState, ScheduledMessageResponse, StreamChat } from 'stream-chat'; + +import { useChatContext } from '../../../context'; +import { useStateStore } from '../../../store'; +import { getChannelByCid, scopeScheduledMessages } from '../utils'; + +const ALL_SCHEDULED_MESSAGES_PAGINATOR_ID = 'stream-chat-react-scheduled-messages'; + +const allScheduledMessagesPaginators = new WeakMap< + StreamChat, + ScheduledMessagePaginator +>(); + +/** One list of all the user's scheduled messages per client, shared by every component. */ +const getAllScheduledMessagesPaginator = (client: StreamChat) => { + const registered = client.scheduledMessagePaginators.getPaginatorById( + ALL_SCHEDULED_MESSAGES_PAGINATOR_ID, + ); + if (registered) return registered; + let paginator = allScheduledMessagesPaginators.get(client); + if (!paginator) { + paginator = new ScheduledMessagePaginator({ + client, + id: ALL_SCHEDULED_MESSAGES_PAGINATOR_ID, + }); + allScheduledMessagesPaginators.set(client, paginator); + } + return paginator; +}; + +const NO_SCHEDULED_MESSAGES: ScheduledMessageResponse[] = []; + +const selectItems = ({ items }: PaginatorState) => ({ items }); + +const createAwaitsFirstPageSelector = + (paginator: ScheduledMessagePaginator) => + ({ isLoading, lastQueryError }: PaginatorState) => ({ + awaitsFirstPage: !paginator.hasLoadedPage && !isLoading && !lastQueryError, + }); + +export type UseScheduledMessagesParams = { + /** The channel whose scheduled messages to list; all of them without it. */ + cid?: string; + /** The thread whose scheduled replies to list. */ + parentId?: string; +}; + +/** + * The scheduled messages of a channel (its own list, filled by the channel query), a thread in it, + * or all of them (a list registered with the client, so events reach it). Loads the first page + * unless one is loaded, as `ChannelList` does. + */ +export const useScheduledMessages = ({ + cid, + parentId, +}: UseScheduledMessagesParams = {}) => { + const { client } = useChatContext(); + const paginator = cid + ? getChannelByCid(client, cid).scheduledMessagesPaginator + : getAllScheduledMessagesPaginator(client); + + // after render, as registering publishes the manager's state + useEffect(() => { + const { scheduledMessagePaginators } = client; + if (cid || scheduledMessagePaginators.getPaginatorById(paginator.id)) return; + scheduledMessagePaginators.insertPaginator({ paginator }); + }, [cid, client, paginator]); + + const awaitsFirstPageSelector = useMemo( + () => createAwaitsFirstPageSelector(paginator), + [paginator], + ); + const { awaitsFirstPage } = useStateStore(paginator.state, awaitsFirstPageSelector); + useEffect(() => { + if (awaitsFirstPage) paginator.toTailDebounced(); + }, [awaitsFirstPage, paginator]); + + const { items } = useStateStore(paginator.state, selectItems); + const scheduledMessages = useMemo( + () => + items ? scopeScheduledMessages(items, { cid, parentId }) : NO_SCHEDULED_MESSAGES, + [cid, items, parentId], + ); + + return { paginator, scheduledMessages }; +}; diff --git a/src/components/ScheduledMessages/index.ts b/src/components/ScheduledMessages/index.ts new file mode 100644 index 0000000000..44e5465a4a --- /dev/null +++ b/src/components/ScheduledMessages/index.ts @@ -0,0 +1,8 @@ +export * from './hooks'; +export * from './ScheduledMessageItem'; +export * from './ScheduledMessageList'; +export * from './ScheduledMessageListDialog'; +export * from './ScheduledMessagePreview'; +export * from './ScheduledMessagesBanner'; +export * from './ScheduleMessageButton'; +export * from './ScheduleTimeDialog'; diff --git a/src/components/ScheduledMessages/styling/ScheduleMessageButton.scss b/src/components/ScheduledMessages/styling/ScheduleMessageButton.scss new file mode 100644 index 0000000000..4baa454cad --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduleMessageButton.scss @@ -0,0 +1,50 @@ +@use '../../../styling/utils'; + +$caret-size: var(--str-chat__button-visual-height-xs); + +.str-chat { + .str-chat__split-send-button { + position: relative; + display: inline-flex; + + .str-chat__send-button.str-chat__button--circular { + aspect-ratio: auto; + // the shrunk icon would leave the button 28px tall + min-height: var(--str-chat__button-visual-height-sm); + + .str-chat__icon.str-chat__icon--send { + position: relative; + z-index: 1; + height: var(--str-chat__icon-size-sm); + width: var(--str-chat__icon-size-sm); + } + + padding-inline: var(--str-chat__spacing-sm) + calc(var(--str-chat__spacing-xs) + #{$caret-size} + var(--str-chat__spacing-xxs)); + } + + .str-chat__schedule-message-button { + position: absolute; + inset-inline-end: var(--str-chat__spacing-xxs); + inset-block-start: 50%; + translate: 0 -50%; + + &[aria-expanded='true']:not(:hover)::after { + content: none; + } + } + + &:has(.str-chat__schedule-message-button[aria-expanded='true']) + .str-chat__send-button:not(:disabled) { + @include utils.overlay-after(var(--str-chat__background-utility-selected)); + } + } + + .str-chat__schedule-message-menu { + min-width: 224px; + + .str-chat__schedule-message-menu__header { + padding: var(--str-chat__spacing-xs); + } + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduleMessageDialog.scss b/src/components/ScheduledMessages/styling/ScheduleMessageDialog.scss new file mode 100644 index 0000000000..80bbe888fd --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduleMessageDialog.scss @@ -0,0 +1,74 @@ +@use '../../../styling/utils'; + +.str-chat { + .str-chat__schedule-message-dialog { + width: 100%; + max-width: 504px; + + .str-chat__schedule-message-dialog__body { + display: flex; + flex-direction: column; + gap: var(--str-chat__spacing-md); + } + + .str-chat__schedule-message-dialog__preview { + background-color: var(--str-chat__chat-bg-outgoing); + + .str-chat__quoted-message-indicator { + background-color: var(--str-chat__chat-reply-indicator-outgoing); + } + } + + .str-chat__schedule-message-dialog__fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--str-chat__spacing-sm); + + input[type='date'], + input[type='time'] { + cursor: pointer; + } + + .str-chat__form-text-input__wrapper { + box-sizing: border-box; + justify-content: center; + min-height: var(--str-chat__button-visual-height-md); + } + + .str-chat__form-text-input__input { + font: var(--str-chat__font-caption-default); + } + + input::-webkit-calendar-picker-indicator { + display: none; + } + } + + .str-chat__schedule-message-dialog__date { + .str-chat__form-text-input__wrapper { + position: relative; + } + + .str-chat__form-text-input__leading { + display: flex; + flex: 1; + align-items: center; + justify-content: flex-start; + gap: var(--str-chat__spacing-xs); + min-width: 0; + } + + .str-chat__form-text-input__input { + position: absolute; + inset: 0; + opacity: 0; + } + } + + .str-chat__schedule-message-dialog__date-value { + @include utils.ellipsis-text(); + font: var(--str-chat__font-caption-default); + color: var(--str-chat__input-text-default); + } + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss b/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss new file mode 100644 index 0000000000..8436e110ba --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss @@ -0,0 +1,31 @@ +@use '../../../styling/utils'; + +.str-chat { + .str-chat__scheduled-message-group__item { + position: relative; + + &:hover, + &:focus-within, + &:has(.str-chat__scheduled-message-actions--active) { + background-color: var(--str-chat__background-utility-hover); + + .str-chat__scheduled-message-actions { + opacity: 1; + pointer-events: auto; + } + } + } + + .str-chat__scheduled-message-actions { + display: flex; + position: absolute; + inset-block-start: var(--str-chat__spacing-xs); + inset-inline-end: var(--str-chat__spacing-md); + padding: var(--str-chat__spacing-xxs); + border-radius: var(--str-chat__radius-md); + background-color: var(--str-chat__background-core-elevation-3); + box-shadow: var(--str-chat__box-shadow-2); + opacity: 0; + pointer-events: none; + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss new file mode 100644 index 0000000000..d48ac91624 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss @@ -0,0 +1,169 @@ +@use '../../../styling/utils'; + +.str-chat { + .str-chat__scheduled-message-list-dialog { + width: 520px; + max-width: 100%; + + // the list scrolls, so reaching its end loads the next page + .str-chat__scheduled-message-list-dialog__body { + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; + + // rows run to the dialog's edges; on the list, as its own overflow would clip them + .str-chat__scheduled-message-list { + margin-inline: calc(-1 * var(--str-chat__spacing-xl)); + } + } + } + + // the pill of the ChannelDetail search, as the design has it + .str-chat__scheduled-message-list-dialog__search { + margin-block-end: var(--str-chat__spacing-xs); + + .str-chat__form-text-input__wrapper--outline { + border-radius: var(--str-chat__radius-max); + } + } + + .str-chat__scheduled-message-list { + flex: 1; + min-height: 0; + } + + .str-chat__scheduled-message-list-notice { + flex-shrink: 0; + margin-block-end: var(--str-chat__spacing-xs); + } + + .str-chat__scheduled-message-group { + display: flex; + flex-direction: column; + + .str-chat__scheduled-message-group__header { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } + + .str-chat__scheduled-message-group__items { + display: flex; + flex-direction: column; + margin: 0; + padding: 0; + list-style: none; + } + + .str-chat__scheduled-message-group__item { + padding: var(--str-chat__spacing-md) var(--str-chat__spacing-xl); + border-block-end: 1px solid var(--str-chat__border-core-subtle); + } + } + + .str-chat__scheduled-message-group:last-of-type + .str-chat__scheduled-message-group__item:last-child { + border-block-end: none; + } + + .str-chat__scheduled-message-item { + display: flex; + flex-direction: column; + gap: var(--str-chat__spacing-xs); + min-width: 0; + + .str-chat__scheduled-message-item__time { + color: var(--str-chat__text-tertiary); + font: var(--str-chat__font-caption-default); + } + + .str-chat__scheduled-message-item__body { + display: flex; + align-items: flex-start; + gap: var(--str-chat__spacing-sm); + min-width: 0; + } + + .str-chat__scheduled-message-item__content { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + color: var(--str-chat__text-primary); + font: var(--str-chat__font-body-default); + } + + .str-chat__scheduled-message-item__channel-name { + @include utils.ellipsis-text(); + color: var(--str-chat__text-secondary); + font: var(--str-chat__font-caption-emphasis); + } + + .str-chat__summarized-message-preview { + min-width: 0; + } + + .str-chat__scheduled-message-item__status { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-xxs); + margin-block-start: var(--str-chat__spacing-xxs); + color: var(--str-chat__text-secondary); + font: var(--str-chat__font-metadata-default); + } + + .str-chat__scheduled-message-item__status--failed { + color: var(--str-chat__accent-error); + font: var(--str-chat__font-caption-default); + } + + .str-chat__scheduled-message-item__status-icon { + flex-shrink: 0; + height: var(--str-chat__icon-size-sm); + width: var(--str-chat__icon-size-sm); + } + } + + // fills the dialog or view it is in, centred both ways + .str-chat__scheduled-messages-empty-list { + @include utils.flex-col-center; + @include utils.empty-theme('scheduled-messages'); + flex: 1; + gap: var(--str-chat__spacing-xxs); + padding-block: var(--str-chat__spacing-3xl); + padding-inline: var(--str-chat__spacing-md); + + .str-chat__scheduled-messages-empty-list__icon { + margin-block-end: var(--str-chat__spacing-xs); + color: var(--str-chat__text-tertiary); + } + + .str-chat__scheduled-messages-empty-list__title, + .str-chat__scheduled-messages-empty-list__description { + margin: 0; + } + + .str-chat__scheduled-messages-empty-list__title { + color: var(--str-chat__text-primary); + font: var(--str-chat__font-caption-emphasis); + } + + .str-chat__scheduled-messages-empty-list__description { + color: var(--str-chat__text-secondary); + font: var(--str-chat__font-caption-default); + } + } + + .str-chat__scheduled-message-list-loading { + @include utils.flex-row-center; + flex: 1; + padding-block: var(--str-chat__spacing-3xl); + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss b/src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss new file mode 100644 index 0000000000..c70e88e786 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss @@ -0,0 +1,47 @@ +@use '../../../styling/utils'; + +.str-chat { + .str-chat__scheduled-messages-banner { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-sm); + width: 100%; + box-sizing: border-box; + padding: var(--str-chat__spacing-xs) var(--str-chat__spacing-md); + border-radius: var(--str-chat__radius-max); + background-color: var(--str-chat__background-core-elevation-2); + box-shadow: var(--str-chat__box-shadow-3); + color: var(--str-chat__text-primary); + font: var(--str-chat__font-metadata-emphasis); + + .str-chat__scheduled-messages-banner__icon { + flex-shrink: 0; + height: var(--str-chat__icon-size-md); + width: var(--str-chat__icon-size-md); + color: var(--str-chat__accent-primary); + } + + .str-chat__scheduled-messages-banner__label { + @include utils.ellipsis-text(); + flex: 1; + min-width: 0; + } + + &.str-chat__scheduled-messages-banner--failed + .str-chat__scheduled-messages-banner__icon { + color: var(--str-chat__accent-error); + } + + .str-chat__scheduled-messages-banner__view-button { + @include utils.button-reset; + flex-shrink: 0; + cursor: pointer; + color: var(--str-chat__text-link); + font: var(--str-chat__font-metadata-default); + + &:focus-visible { + @include utils.focusable; + } + } + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessagesNotice.scss b/src/components/ScheduledMessages/styling/ScheduledMessagesNotice.scss new file mode 100644 index 0000000000..4b1bcd639e --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessagesNotice.scss @@ -0,0 +1,29 @@ +.str-chat { + // tinted with its accent: the primary one, or the error one + .str-chat__scheduled-messages-notice { + --str-chat__scheduled-messages-notice-accent: var(--str-chat__accent-primary); + display: flex; + align-items: center; + gap: var(--str-chat__spacing-xs); + padding: var(--str-chat__spacing-sm); + border-radius: var(--str-chat__radius-md); + background-color: color-mix( + in srgb, + var(--str-chat__scheduled-messages-notice-accent) 5%, + transparent + ); + color: var(--str-chat__text-primary); + font: var(--str-chat__font-metadata-emphasis); + + .str-chat__scheduled-messages-notice__icon { + flex-shrink: 0; + height: var(--str-chat__icon-size-sm); + width: var(--str-chat__icon-size-sm); + color: var(--str-chat__scheduled-messages-notice-accent); + } + } + + .str-chat__scheduled-messages-notice--error { + --str-chat__scheduled-messages-notice-accent: var(--str-chat__accent-error); + } +} diff --git a/src/components/ScheduledMessages/styling/index.scss b/src/components/ScheduledMessages/styling/index.scss new file mode 100644 index 0000000000..6e20b67fea --- /dev/null +++ b/src/components/ScheduledMessages/styling/index.scss @@ -0,0 +1,6 @@ +@use 'ScheduledMessageActions'; +@use 'ScheduledMessageList'; +@use 'ScheduledMessagesBanner'; +@use 'ScheduledMessagesNotice'; +@use 'ScheduleMessageButton'; +@use 'ScheduleMessageDialog'; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts new file mode 100644 index 0000000000..424198bdc2 --- /dev/null +++ b/src/components/ScheduledMessages/utils.ts @@ -0,0 +1,325 @@ +import { + getChannelLevelScheduledMessages, + getScheduledMessageErrorReason, + getScheduledMessageLimits, + getThreadScheduledMessages, + isScheduledMessageNotFoundError, + nsToDate, + SCHEDULED_MESSAGE_FAILURE_REASON, + SCHEDULED_MESSAGE_STATUS, + ScheduledMessageErrorReason, + StreamAPIError, +} from 'stream-chat'; +import type { + Channel, + MessageComposerState, + ScheduledMessageFailureReason, + ScheduledMessageResponse, + StreamChat, +} from 'stream-chat'; + +import type { StreamTFunction } from '../../i18n/types'; + +const MS_IN_SECOND = 1000; +/** Keeps the earliest offered time ahead of the server's minimum despite clock skew. */ +const CLOCK_SKEW_BUFFER_MS = 60 * MS_IN_SECOND; +const MORNING_HOUR = 9; +const AFTERNOON_HOUR = 13; + +/** Notifications the UI emits; the composer's own come from `CORE_NOTIFICATION_TYPE`. */ +export const SCHEDULED_MESSAGE_NOTIFICATION_TYPE = { + deleteFailed: 'api:scheduled-message:delete:failed', + sendNowFailed: 'api:scheduled-message:send-now:failed', + sendNowSucceeded: 'api:scheduled-message:send-now:success', +} as const; + +export const SCHEDULED_MESSAGES_EMITTER = 'ScheduledMessages'; + +export type ScheduleTimeBounds = { earliest: Date; latest?: Date }; + +export type ScheduledMessageGroup = { + /** The local day the group's messages are sent on; absent for the failed group. */ + day?: Date; + key: string; + scheduledMessages: ScheduledMessageResponse[]; +}; + +export type ScheduledMessageAction = + | 'copy' + | 'delete' + | 'edit' + | 'reschedule' + | 'send_now'; + +export const getChannelByCid = (client: StreamChat, cid: string) => { + const [type, id] = cid.split(':'); + return client.channelManager.get(cid) ?? client.channel(type, id); +}; + +export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) => + status === SCHEDULED_MESSAGE_STATUS.Failed; + +/** A channel's list holds its replies too: a thread keeps its own, a channel its top-level ones. */ +export const scopeScheduledMessages = ( + scheduledMessages: ScheduledMessageResponse[], + { cid, parentId }: { cid?: string; parentId?: string }, +) => { + if (parentId) return getThreadScheduledMessages(scheduledMessages, parentId); + return cid ? getChannelLevelScheduledMessages(scheduledMessages) : scheduledMessages; +}; + +export const searchScheduledMessages = ( + scheduledMessages: ScheduledMessageResponse[], + searchQuery = '', +) => { + const query = searchQuery.trim().toLocaleLowerCase(); + if (!query) return scheduledMessages; + return scheduledMessages.filter(({ message }) => + message.text?.toLocaleLowerCase().includes(query), + ); +}; + +export const toDateInputValue = (date: Date) => + [ + date.getFullYear(), + String(date.getMonth() + 1).padStart(2, '0'), + String(date.getDate()).padStart(2, '0'), + ].join('-'); + +export const toTimeInputValue = (date: Date) => + `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + +/** The local date of `` and time of ``, if both are valid. */ +export const fromInputValues = (dateValue: string, timeValue = '00:00') => { + if (!dateValue || !timeValue) return undefined; + const date = new Date(`${dateValue}T${timeValue}`); + return Number.isNaN(date.getTime()) ? undefined : date; +}; + +/** + * Groups the list (pending by `scheduled_at`, then failed) by the local day pending messages are + * sent on, with the failed ones in one group shown first. + */ +export const groupScheduledMessages = (scheduledMessages: ScheduledMessageResponse[]) => { + const groups = scheduledMessages.reduce( + (groups, scheduledMessage) => { + const isFailed = isFailedScheduledMessage(scheduledMessage); + const day = nsToDate(scheduledMessage.scheduled_at); + const key = isFailed ? 'failed' : toDateInputValue(day); + const lastGroup = groups[groups.length - 1]; + + if (lastGroup?.key === key) lastGroup.scheduledMessages.push(scheduledMessage); + else + groups.push({ + day: isFailed ? undefined : day, + key, + scheduledMessages: [scheduledMessage], + }); + + return groups; + }, + [], + ); + const failedGroup = + groups[groups.length - 1]?.key === 'failed' ? groups.pop() : undefined; + return failedGroup ? [failedGroup, ...groups] : groups; +}; + +/** The times the channel accepts; no `latest` when it reports no limits. */ +export const getScheduleTimeBounds = (channel: Channel, now = new Date()) => { + const limits = getScheduledMessageLimits(channel); + const nowMs = now.getTime(); + const bounds: ScheduleTimeBounds = { + earliest: new Date( + nowMs + (limits?.minLeadTimeSeconds ?? 0) * MS_IN_SECOND + CLOCK_SKEW_BUFFER_MS, + ), + latest: limits && new Date(nowMs + limits.maxLeadTimeSeconds * MS_IN_SECOND), + }; + return bounds; +}; + +export const getScheduleTimeError = ( + scheduledAt: Date, + { earliest, latest }: ScheduleTimeBounds, +) => { + if (scheduledAt < earliest) return 'tooSoon' as const; + if (latest && scheduledAt > latest) return 'tooFar' as const; + return undefined; +}; + +/** The next full hour after the earliest allowed time. */ +export const getDefaultScheduledAt = ({ earliest }: ScheduleTimeBounds) => { + const scheduledAt = new Date(earliest); + scheduledAt.setHours(scheduledAt.getHours() + 1, 0, 0, 0); + return scheduledAt; +}; + +const atLocalHour = (date: Date, dayOffset: number, hour: number) => { + const localDate = new Date(date); + localDate.setDate(date.getDate() + dayOffset); + localDate.setHours(hour, 0, 0, 0); + return localDate; +}; + +/** Tomorrow morning and afternoon and next Monday morning, within `bounds`. */ +export const getSchedulePresets = (now: Date, bounds: ScheduleTimeBounds) => { + const daysUntilMonday = (8 - now.getDay()) % 7 || 7; + const presets = [ + atLocalHour(now, 1, MORNING_HOUR), + atLocalHour(now, 1, AFTERNOON_HOUR), + ...(daysUntilMonday === 1 ? [] : [atLocalHour(now, daysUntilMonday, MORNING_HOUR)]), + ]; + return presets.filter((preset) => !getScheduleTimeError(preset, bounds)); +}; + +export const formatTimeZoneOffset = (date: Date) => { + const offsetMinutes = -date.getTimezoneOffset(); + if (!offsetMinutes) return 'GMT'; + const sign = offsetMinutes < 0 ? '-' : '+'; + const hours = Math.floor(Math.abs(offsetMinutes) / 60); + const minutes = Math.abs(offsetMinutes) % 60; + return `GMT${sign}${hours}${minutes ? `:${String(minutes).padStart(2, '0')}` : ''}`; +}; + +/** What the user may do with a scheduled message; `edit` only where the list can open it. */ +export const getScheduledMessageActions = ( + { failure_reason, status }: ScheduledMessageResponse, + canEdit: boolean, +): ScheduledMessageAction[] => { + if (status === SCHEDULED_MESSAGE_STATUS.Sending) return []; + const actions: ScheduledMessageAction[] = + status !== SCHEDULED_MESSAGE_STATUS.Failed + ? ['edit', 'reschedule', 'send_now', 'delete'] + : failure_reason === SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted + ? ['copy', 'delete'] + : ['edit', 'delete']; + return canEdit ? actions : actions.filter((action) => action !== 'edit'); +}; + +/** + * Whether the composer edits a message: a message, or a pending scheduled one. A failed scheduled + * message open in it is not edited but sent or scheduled again, so the composer works as usual. + */ +export const isComposerEditing = ({ + editedMessage, + editedScheduledMessage, +}: Pick) => + !!editedMessage || + (!!editedScheduledMessage && !isFailedScheduledMessage(editedScheduledMessage)); + +/** + * After a conflict (the message changed elsewhere), reloads the lists that may hold the stale copy: + * the channel's own and the ones registered with the client. + */ +export const reloadOnScheduledMessageConflict = ( + client: StreamChat, + cid: string, + error: unknown, +) => { + if (getScheduledMessageErrorReason(error) !== ScheduledMessageErrorReason.Conflict) + return; + const { scheduledMessagesPaginator } = getChannelByCid(client, cid); + if (scheduledMessagesPaginator.hasLoadedPage) { + scheduledMessagesPaginator.reload().catch(() => undefined); + } + void client.scheduledMessagePaginators.recover(); +}; + +/** Why a scheduled message failed; `undefined` when the reason needs no explanation. */ +export const translateScheduledMessageFailureReason = ( + t: StreamTFunction, + reason?: ScheduledMessageFailureReason, +) => { + switch (reason) { + case SCHEDULED_MESSAGE_FAILURE_REASON.Banned: + return t( + 'scheduledMessages.youCantSendMessagesInThisChannel', + "You can't send messages in this channel", + ); + case SCHEDULED_MESSAGE_FAILURE_REASON.NoPermission: + return t( + 'scheduledMessages.youreNoLongerAllowedToPostHere', + "You're no longer allowed to post here", + ); + case SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen: + return t('scheduledMessages.thisChannelIsFrozen', 'This channel is frozen'); + case SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted: + return t('scheduledMessages.thisChannelWasDeleted', 'This channel was deleted'); + case SCHEDULED_MESSAGE_FAILURE_REASON.UserDeleted: + return undefined; + case SCHEDULED_MESSAGE_FAILURE_REASON.ModerationBlocked: + return t('scheduledMessages.blockedByModeration', 'Blocked by moderation'); + case SCHEDULED_MESSAGE_FAILURE_REASON.HookRejected: + return t('scheduledMessages.rejectedByTheApp', 'Rejected by the app'); + case SCHEDULED_MESSAGE_FAILURE_REASON.Expired: + return t( + 'scheduledMessages.notSentTheServiceWasDelayed', + 'Not sent: the service was delayed', + ); + case SCHEDULED_MESSAGE_FAILURE_REASON.InvalidMessage: + return t( + 'scheduledMessages.theMessageNoLongerMeetsTheAppsLimits', + "The message no longer meets the app's limits. Edit it", + ); + case SCHEDULED_MESSAGE_FAILURE_REASON.PendingNotSupported: + return t( + 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain', + 'This channel now needs approval. Schedule it again', + ); + case SCHEDULED_MESSAGE_FAILURE_REASON.InternalError: + return t( + 'scheduledMessages.somethingWentWrongTryAgain', + 'Something went wrong. Try again', + ); + default: + return t('scheduledMessages.couldntSendTryAgain', "Couldn't send. Try again"); + } +}; + +const FORBIDDEN_STATUS = 403; + +/** What a failed scheduled-message request tells the user, when its error says something specific. */ +export const translateScheduledMessageError = (t: StreamTFunction, error: unknown) => { + switch (getScheduledMessageErrorReason(error)) { + case ScheduledMessageErrorReason.Disabled: + return t( + 'scheduledMessages.notification.disabled', + 'Scheduled messages are turned off', + ); + case ScheduledMessageErrorReason.TooSoon: + return t('scheduledMessages.chooseALaterTime', 'Choose a later time'); + case ScheduledMessageErrorReason.TooFar: + return t('scheduledMessages.chooseAnEarlierTime', 'Choose an earlier time'); + case ScheduledMessageErrorReason.ChannelLimit: + return t( + 'scheduledMessages.notification.channelLimit', + "You've reached the limit of scheduled messages in this channel", + ); + case ScheduledMessageErrorReason.UserLimit: + return t( + 'scheduledMessages.notification.userLimit', + "You've reached the limit of scheduled messages", + ); + case ScheduledMessageErrorReason.Sending: + return t('scheduledMessages.notification.sending', 'This message is being sent'); + case ScheduledMessageErrorReason.Conflict: + return t('scheduledMessages.notification.conflict', 'Updated elsewhere. Try again'); + case ScheduledMessageErrorReason.NotEditable: + return t( + 'scheduledMessages.notification.notEditable', + "Failed messages can't be edited", + ); + default: + break; + } + if (isScheduledMessageNotFoundError(error)) { + return t('scheduledMessages.notification.alreadySent', 'Already sent'); + } + if (error instanceof StreamAPIError && error.status === FORBIDDEN_STATUS) { + return t( + 'scheduledMessages.notification.forbidden', + "You can't schedule messages here", + ); + } + return undefined; +}; diff --git a/src/components/index.ts b/src/components/index.ts index 64061386f3..9f1f998c3b 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -10,6 +10,7 @@ export * from './Channel'; export * from './ChannelHeader'; export * from './ChannelList'; export * from './ChannelListItem'; +export * from './ScheduledMessages'; export * from './Search'; export * from './SkipNavigation'; export * from './Chat'; diff --git a/src/context/ComponentContext.tsx b/src/context/ComponentContext.tsx index 45195702fe..45ff125bf7 100644 --- a/src/context/ComponentContext.tsx +++ b/src/context/ComponentContext.tsx @@ -78,6 +78,12 @@ import type { SummarizedMessagePreviewProps } from '../components/SummarizedMess import type { TypingIndicatorProps } from '../components/TypingIndicator'; import type { AttachmentUploadProgressIndicatorProps } from '../components/Attachment/components/AttachmentUploadProgressIndicator'; import type { IconSlots } from '../components/Icons/slots'; +import type { + ScheduledMessageItemProps, + ScheduledMessageListDialogProps, + ScheduledMessageListProps, + ScheduledMessagePreviewProps, +} from '../components/ScheduledMessages'; export type ComponentContextValue = { /** Progress of an attachment whose upload is still in flight. */ @@ -307,6 +313,21 @@ export type ComponentContextValue = { RecordingPermissionDeniedNotification?: React.ComponentType; /** Message reminder information in the message UI. */ ReminderNotification?: React.ComponentType; + /** One item of `ScheduledMessageList`. */ + ScheduledMessageItem?: React.ComponentType; + /** Scheduled messages in the banner's dialog and the Channel Detail section. */ + ScheduledMessageList?: React.ComponentType; + /** + * What the banner's "View all" opens: a modal with the channel's (or thread's) scheduled messages + * by default. Receives `open` and `close`, so an override can show the list elsewhere. + */ + ScheduledMessageListDialog?: React.ComponentType; + /** Above the composer while a scheduled message is edited or a failed one scheduled again. */ + ScheduledMessagePreview?: React.ComponentType; + /** Scheduled messages banner above the composer; `null` hides it. */ + ScheduledMessagesBanner?: React.ComponentType | null; + /** Schedule button next to the send button; `null` hides it. */ + ScheduleMessageButton?: React.ComponentType | null; /** Translation indicator, shown when the message has `i18n`. */ MessageTranslationIndicator?: React.ComponentType; /** diff --git a/src/i18n/TranslationBuilder/notifications/translators.ts b/src/i18n/TranslationBuilder/notifications/translators.ts index c138371222..f22f48d063 100644 --- a/src/i18n/TranslationBuilder/notifications/translators.ts +++ b/src/i18n/TranslationBuilder/notifications/translators.ts @@ -1,5 +1,10 @@ +import { + CORE_NOTIFICATION_TYPE, + ScheduledMessageCompositionEndReason, +} from 'stream-chat'; import type { Notification } from 'stream-chat'; +import { translateScheduledMessageError } from '../../../components/ScheduledMessages/utils'; import type { NotificationTranslatorOptions } from './types'; import type { Translator } from '../../index'; @@ -94,3 +99,34 @@ export const translateCommandDisabled: Translator return t('notification.commandDisabled', 'Command not available'); }; + +/** A failed request to schedule or edit a scheduled message, both emitted by the composer. */ +export const translateScheduledMessageRequestFailed: Translator< + NotificationTranslatorOptions +> = ({ options: { notification }, t }) => { + const specific = translateScheduledMessageError(t, notification?.originalError); + if (specific) return specific; + switch (notification?.type) { + case CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed: + return t( + 'scheduledMessages.couldntScheduleMessageTryAgain', + "Couldn't schedule message. Try again", + ); + default: + return t( + 'scheduledMessages.notification.updateFailed', + "Couldn't update the scheduled message. Try again", + ); + } +}; + +/** A scheduled message open in the composer was sent, deleted or failed meanwhile. */ +export const translateScheduledMessageCompositionEnded: Translator< + NotificationTranslatorOptions +> = ({ options: { notification }, t }) => + notification?.metadata?.reason === ScheduledMessageCompositionEndReason.Sent + ? t('scheduledMessages.notification.alreadySentEdit', 'This message was already sent') + : t( + 'scheduledMessages.notification.endedEdit', + 'This scheduled message can no longer be edited', + ); diff --git a/src/i18n/TranslationBuilder/notifications/translatorsByNotificationType.ts b/src/i18n/TranslationBuilder/notifications/translatorsByNotificationType.ts index a713b7fa91..8195e22380 100644 --- a/src/i18n/TranslationBuilder/notifications/translatorsByNotificationType.ts +++ b/src/i18n/TranslationBuilder/notifications/translatorsByNotificationType.ts @@ -9,6 +9,8 @@ import { translateCommandDisabled, translatePollCreateFailed, translatePollEndFailed, + translateScheduledMessageCompositionEnded, + translateScheduledMessageRequestFailed, } from './translators'; import type { Translator } from '../../index'; @@ -51,6 +53,15 @@ const coreNotificationTranslators: Record
)} ); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index 2a07176636..fbe51ab5d7 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -21,6 +21,7 @@ import { ChatProvider, DialogManagerProvider, TranslationProvider, + useChatContext, } from '../../../context'; import { WithComponents } from '../../../context/WithComponents'; import { Streami18n } from '../../../i18n'; @@ -31,12 +32,22 @@ import { hydrateScheduledMessages, mockChatContext, } from '../../../mock-builders'; -import { SCHEDULED_MESSAGE_NOTIFICATION_TYPE } from '../utils'; +import { getChannelByCid, SCHEDULED_MESSAGE_NOTIFICATION_TYPE } from '../utils'; import { ScheduledMessageList } from '../ScheduledMessageList'; import type { EditScheduledMessage } from '../types'; const cid = 'messaging:general'; +const ChannelScheduledMessageList = ({ onEdit }: { onEdit?: EditScheduledMessage }) => { + const { client } = useChatContext(); + return ( + + ); +}; + const getChannel = (client: StreamChat) => client.channel('messaging', 'general'); const WEDNESDAY_MORNING = new Date(2026, 9, 28, 10, 30); @@ -78,7 +89,7 @@ const renderActions = async ({ - + diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx index cbcb776ec3..f3cbe216eb 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useEffect } from 'react'; import { act, cleanup, @@ -16,6 +16,7 @@ import { ChatProvider, DialogManagerProvider, TranslationProvider, + useChatContext, } from '../../../context'; import { WithComponents } from '../../../context/WithComponents'; import { Streami18n } from '../../../i18n'; @@ -28,6 +29,10 @@ import { hydrateScheduledMessages, mockChatContext, } from '../../../mock-builders'; +import type { ScheduledMessageSearchFilter } from '../hooks'; +import { useScheduledMessagesSearch } from '../hooks'; +import { getChannelByCid } from '../utils'; +import type { ScheduledMessageListProps } from '../ScheduledMessageList'; import { ScheduledMessageList } from '../ScheduledMessageList'; import type { EditScheduledMessage, ScheduledMessageItemProps } from '../types'; @@ -42,13 +47,37 @@ type RenderListOptions = { client?: StreamChat; components?: Parameters[0]['overrides']; onEdit?: EditScheduledMessage; + filter?: ScheduledMessageSearchFilter; + listProps?: Partial; scheduledMessages?: ScheduledMessageResponse[]; searchQuery?: string; }; +/** The list as the dialog renders it: searched with `useScheduledMessagesSearch`. */ +const SearchedList = ({ + filter, + listProps, + onEdit, + searchQuery = '', +}: Pick) => { + const { client } = useChatContext(); + const { filter: searchFilter, setSearchQuery } = useScheduledMessagesSearch({ filter }); + useEffect(() => setSearchQuery(searchQuery), [searchQuery, setSearchQuery]); + return ( + + ); +}; + const renderList = async ({ client: clientArg, components = {}, + filter, + listProps, onEdit, scheduledMessages = [], searchQuery, @@ -63,7 +92,12 @@ const renderList = async ({ - + @@ -280,19 +314,61 @@ describe('ScheduledMessageList', () => { expect(query).toHaveBeenCalledTimes(1); }); - it('renders the list states through the list-state slots', async () => { + // a list-state key overridden for the channel list (`EmptyListIndicator` takes no props) must not + // turn up here + it('renders the list states passed as props, not the shared list-state keys', async () => { const { client } = await renderList({ components: { - EmptyListIndicator: () =>
Nothing here
, - FirstPageLoadingIndicator: () =>
Loading here
, + EmptyListIndicator: () =>
No channels
, + FirstPageLoadingIndicator: () =>
Loading channels
, + }, + listProps: { + EmptyListIndicator: () =>
Nothing scheduled
, + FirstPageLoadingIndicator: () =>
Loading scheduled
, }, }); - expect(screen.getByText('Nothing here')).toBeInTheDocument(); + expect(screen.getByText('Nothing scheduled')).toBeInTheDocument(); + expect(screen.queryByText('No channels')).not.toBeInTheDocument(); setPaginatorState(client, { isLoading: true, items: undefined }); - expect(screen.getByText('Loading here')).toBeInTheDocument(); + expect(screen.getByText('Loading scheduled')).toBeInTheDocument(); + }); + + it('renders a custom empty search results indicator', async () => { + await renderList({ + listProps: { EmptySearchResultsIndicator: () =>
No match
}, + scheduledMessages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + searchQuery: 'friday', + }); + + expect(screen.getByText('No match')).toBeInTheDocument(); + }); + + it('searches with a custom filter, such as by date', async () => { + const onFriday: ScheduledMessageSearchFilter = ({ scheduled_at }) => + scheduled_at >= atLocalTime(30, 0) && scheduled_at < atLocalTime(31, 0); + await renderList({ + filter: onFriday, + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Thursday standup' }, + scheduled_at: atLocalTime(29, 9), + }), + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Friday demo' }, + scheduled_at: atLocalTime(30, 9), + }), + ], + }); + + expect(screen.getByText('Friday demo')).toBeInTheDocument(); + expect(screen.queryByText('Thursday standup')).not.toBeInTheDocument(); }); // a failed message failed at its send time, so ordering by time alone lists it first diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx index 9ee95b1aa0..8ba0175541 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -386,7 +386,10 @@ describe('ScheduledMessagesBanner', () => { expect(screen.getByTestId('custom-list')).toBeInTheDocument(); expect(ScheduledMessageListDialog).toHaveBeenLastCalledWith( - expect.objectContaining({ cid, open: true, parentId: undefined }), + expect.objectContaining({ + open: true, + scheduledMessages: channel.scheduledMessages, + }), undefined, ); diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts index 3a1076f133..a350254976 100644 --- a/src/components/ScheduledMessages/__tests__/utils.test.ts +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -10,7 +10,7 @@ import { getSchedulePresets, getScheduleTimeBounds, getScheduleTimeError, - searchScheduledMessages, + matchesScheduledMessageText, translateScheduledMessageFailureReason, } from '../utils'; @@ -32,8 +32,9 @@ describe('scheduled message utils', () => { }); const launch = generateScheduledMessage({ message: { custom: {}, text: 'Launch' } }); - expect(searchScheduledMessages([lunch, launch], ' LUNCH ')).toEqual([lunch]); - expect(searchScheduledMessages([lunch, launch], ' ')).toEqual([lunch, launch]); + expect(matchesScheduledMessageText(lunch, ' LUNCH ')).toBe(true); + expect(matchesScheduledMessageText(launch, ' LUNCH ')).toBe(false); + expect(matchesScheduledMessageText(launch, ' ')).toBe(true); }); describe('time bounds', () => { diff --git a/src/components/ScheduledMessages/hooks/index.ts b/src/components/ScheduledMessages/hooks/index.ts index 57ca671146..7c390e1153 100644 --- a/src/components/ScheduledMessages/hooks/index.ts +++ b/src/components/ScheduledMessages/hooks/index.ts @@ -1,2 +1,3 @@ export * from './useCanScheduleMessage'; export * from './useScheduledMessages'; +export * from './useScheduledMessagesSearch'; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts index 8b8d80dca4..7150a4c872 100644 --- a/src/components/ScheduledMessages/hooks/useScheduledMessages.ts +++ b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts @@ -1,88 +1,49 @@ import { useEffect, useMemo } from 'react'; -import { ScheduledMessagePaginator } from 'stream-chat'; -import type { PaginatorState, ScheduledMessageResponse, StreamChat } from 'stream-chat'; +import type { + PaginatorState, + ScheduledMessageResponse, + ScheduledMessagesView, + ScheduledMessagesViewState, +} from 'stream-chat'; -import { useChatContext } from '../../../context'; import { useStateStore } from '../../../store'; -import { getChannelByCid, scopeScheduledMessages } from '../utils'; - -const ALL_SCHEDULED_MESSAGES_PAGINATOR_ID = 'stream-chat-react-scheduled-messages'; - -const allScheduledMessagesPaginators = new WeakMap< - StreamChat, - ScheduledMessagePaginator ->(); - -/** One list of all the user's scheduled messages per client, shared by every component. */ -const getAllScheduledMessagesPaginator = (client: StreamChat) => { - const registered = client.scheduledMessagePaginators.getPaginatorById( - ALL_SCHEDULED_MESSAGES_PAGINATOR_ID, - ); - if (registered) return registered; - let paginator = allScheduledMessagesPaginators.get(client); - if (!paginator) { - paginator = new ScheduledMessagePaginator({ - client, - id: ALL_SCHEDULED_MESSAGES_PAGINATOR_ID, - }); - allScheduledMessagesPaginators.set(client, paginator); - } - return paginator; -}; const NO_SCHEDULED_MESSAGES: ScheduledMessageResponse[] = []; -const selectItems = ({ items }: PaginatorState) => ({ items }); +const selectItems = ({ items }: ScheduledMessagesViewState) => ({ items }); const createAwaitsFirstPageSelector = - (paginator: ScheduledMessagePaginator) => + (view: ScheduledMessagesView) => ({ isLoading, lastQueryError }: PaginatorState) => ({ - awaitsFirstPage: !paginator.hasLoadedPage && !isLoading && !lastQueryError, + awaitsFirstPage: !view.paginator.hasLoadedPage && !isLoading && !lastQueryError, }); -export type UseScheduledMessagesParams = { - /** The channel whose scheduled messages to list; all of them without it. */ - cid?: string; - /** The thread whose scheduled replies to list. */ - parentId?: string; -}; - /** - * The scheduled messages of a channel (its own list, filled by the channel query), a thread in it, - * or all of them (a list registered with the client, so events reach it). Loads the first page - * unless one is loaded, as `ChannelList` does. + * The messages of an SDK scheduled-message view: `channel.scheduledMessages`, + * `thread.scheduledMessages`, or a view of a list registered with + * `client.scheduledMessagePaginators`. Keeps the view following its paginator while mounted, and + * loads the first page unless one is loaded, as `ChannelList` does. */ -export const useScheduledMessages = ({ - cid, - parentId, -}: UseScheduledMessagesParams = {}) => { - const { client } = useChatContext(); - const paginator = cid - ? getChannelByCid(client, cid).scheduledMessagesPaginator - : getAllScheduledMessagesPaginator(client); - - // after render, as registering publishes the manager's state +export const useScheduledMessages = (view: ScheduledMessagesView) => { useEffect(() => { - const { scheduledMessagePaginators } = client; - if (cid || scheduledMessagePaginators.getPaginatorById(paginator.id)) return; - scheduledMessagePaginators.insertPaginator({ paginator }); - }, [cid, client, paginator]); + view.registerSubscriptions(); + return () => { + view.unregisterSubscriptions(); + }; + }, [view]); const awaitsFirstPageSelector = useMemo( - () => createAwaitsFirstPageSelector(paginator), - [paginator], + () => createAwaitsFirstPageSelector(view), + [view], ); - const { awaitsFirstPage } = useStateStore(paginator.state, awaitsFirstPageSelector); - useEffect(() => { - if (awaitsFirstPage) paginator.toTailDebounced(); - }, [awaitsFirstPage, paginator]); - - const { items } = useStateStore(paginator.state, selectItems); - const scheduledMessages = useMemo( - () => - items ? scopeScheduledMessages(items, { cid, parentId }) : NO_SCHEDULED_MESSAGES, - [cid, items, parentId], + const { awaitsFirstPage } = useStateStore( + view.paginator.state, + awaitsFirstPageSelector, ); + useEffect(() => { + if (awaitsFirstPage) view.toTailDebounced(); + }, [awaitsFirstPage, view]); - return { paginator, scheduledMessages }; + const { items } = useStateStore(view.state, selectItems); + return { scheduledMessages: items ?? NO_SCHEDULED_MESSAGES }; }; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessagesSearch.ts b/src/components/ScheduledMessages/hooks/useScheduledMessagesSearch.ts new file mode 100644 index 0000000000..86522cc621 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessagesSearch.ts @@ -0,0 +1,35 @@ +import { useCallback, useState } from 'react'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { matchesScheduledMessageText } from '../utils'; + +export { matchesScheduledMessageText }; + +/** Whether a scheduled message matches the search; `searchQuery` is the search field's value. */ +export type ScheduledMessageSearchFilter = ( + scheduledMessage: ScheduledMessageResponse, + searchQuery: string, +) => boolean; + +export type UseScheduledMessagesSearchParams = { + /** + * Replaces the default text search, for example to search by date. It receives the query, so it + * can still combine with `matchesScheduledMessageText`. Keep it stable, e.g. with `useCallback`. + */ + filter?: ScheduledMessageSearchFilter; +}; + +/** + * The search field's state, and the `filter` for `ScheduledMessageList` it makes of it. The list + * loads further pages while none of the loaded messages match, so the matches need not be loaded. + */ +export const useScheduledMessagesSearch = ({ + filter = matchesScheduledMessageText, +}: UseScheduledMessagesSearchParams = {}) => { + const [searchQuery, setSearchQuery] = useState(''); + const searchFilter = useCallback( + (scheduledMessage: ScheduledMessageResponse) => filter(scheduledMessage, searchQuery), + [filter, searchQuery], + ); + return { filter: searchFilter, searchQuery, setSearchQuery }; +}; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 53498262fc..99a4c63b2b 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -1,8 +1,6 @@ import { - getChannelLevelScheduledMessages, getScheduledMessageErrorReason, getScheduledMessageLimits, - getThreadScheduledMessages, isScheduledMessageNotFoundError, SCHEDULED_MESSAGE_FAILURE_REASON, SCHEDULED_MESSAGE_STATUS, @@ -52,23 +50,13 @@ export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) = status === SCHEDULED_MESSAGE_STATUS.Failed; /** A channel's list holds its replies too: a thread keeps its own, a channel its top-level ones. */ -export const scopeScheduledMessages = ( - scheduledMessages: ScheduledMessageResponse[], - { cid, parentId }: { cid?: string; parentId?: string }, -) => { - if (parentId) return getThreadScheduledMessages(scheduledMessages, parentId); - return cid ? getChannelLevelScheduledMessages(scheduledMessages) : scheduledMessages; -}; - -export const searchScheduledMessages = ( - scheduledMessages: ScheduledMessageResponse[], - searchQuery = '', +/** The default search: the text contains the query, ignoring case; a blank query matches all. */ +export const matchesScheduledMessageText = ( + { message }: ScheduledMessageResponse, + searchQuery: string, ) => { const query = searchQuery.trim().toLocaleLowerCase(); - if (!query) return scheduledMessages; - return scheduledMessages.filter(({ message }) => - message.text?.toLocaleLowerCase().includes(query), - ); + return !query || !!message.text?.toLocaleLowerCase().includes(query); }; export const toDateInputValue = (date: Date) => diff --git a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx index c4d695a027..69ce88f805 100644 --- a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx +++ b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useState } from 'react'; +import React, { useCallback } from 'react'; import type { ScheduledMessageResponse } from 'stream-chat'; import { @@ -10,6 +10,7 @@ import { Prompt } from '../../../../components/Dialog'; import { ScheduledMessageList as DefaultScheduledMessageList, useScheduledMessages, + useScheduledMessagesSearch, } from '../../../../components/ScheduledMessages'; import { ChannelDetailSearchInput } from '../../ChannelDetailSearchInput'; import { useChannelDetailContext } from '../../ChannelDetailContext'; @@ -21,9 +22,8 @@ export const ScheduledMessagesView = () => { const { close } = useModalContext(); const { channel } = useChannelDetailContext(); - const { scheduledMessages } = useScheduledMessages({ cid: channel.cid }); - - const [searchQuery, setSearchQuery] = useState(''); + const { scheduledMessages } = useScheduledMessages(channel.scheduledMessages); + const { filter, setSearchQuery } = useScheduledMessagesSearch(); const editScheduledMessage = useCallback( (scheduledMessage: ScheduledMessageResponse) => { @@ -44,9 +44,9 @@ export const ScheduledMessagesView = () => { )}
diff --git a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/__tests__/ScheduledMessagesView.test.tsx b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/__tests__/ScheduledMessagesView.test.tsx index 8794b44bcc..f5c61d82fe 100644 --- a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/__tests__/ScheduledMessagesView.test.tsx +++ b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/__tests__/ScheduledMessagesView.test.tsx @@ -22,6 +22,7 @@ import { import { defaultChannelDetailSections } from '../../../ChannelDetail'; import { ChannelDetailProvider } from '../../../ChannelDetailContext'; import { ScheduledMessagesView } from '../ScheduledMessagesView'; +import type { ScheduledMessageListProps } from '../../../../../components/ScheduledMessages'; const cid = 'messaging:general'; @@ -138,13 +139,17 @@ describe('ScheduledMessagesView', () => { }); it('renders the list through the ScheduledMessageList slot', async () => { - const CustomList = ({ cid: listCid }: { cid: string }) => ( -
{listCid}
+ const CustomList = ({ scheduledMessages }: ScheduledMessageListProps) => ( +
+ {scheduledMessages.scope.type}:{scheduledMessages.paginator.cid} +
); await renderView([], { ScheduledMessageList: CustomList }); - expect(screen.getByTestId('custom-scheduled-message-list')).toHaveTextContent(cid); + expect(screen.getByTestId('custom-scheduled-message-list')).toHaveTextContent( + `channel:${cid}`, + ); }); it('closes the channel detail modal from the header', async () => { From ccc40edf54dd91cead8cf63c7f16bcd31cc89c7e Mon Sep 17 00:00:00 2001 From: martincupela Date: Wed, 11 Nov 2026 17:09:53 +0100 Subject: [PATCH 04/35] fix(ScheduledMessages): keep the list dialog within narrow screens, at a fixed height - The modal's dialog wrapper sized to its content, so the dialog's max-width measured against its own 520px and overflowed screens narrower than that. The wrapper now leaves a 16px gutter. - The dialog grew and shrank with each search keystroke and page loaded. It now has ChannelDetail's fixed height, capped by the screen, and its list scrolls. Co-Authored-By: Claude Opus 5.5 --- .../styling/ScheduledMessageList.scss | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss index 7a1041dc74..ea47e07066 100644 --- a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss +++ b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss @@ -1,13 +1,25 @@ @use '../../../styling/utils'; +// The modal's dialog wrapper is a flex item sized to its content, so without a limit of its own the +// dialog's `max-width: 100%` measures against its own 520px and overflows a narrow screen. Top-level, +// as in `Modal.scss`: the modal is portaled and is itself the `.str-chat` element, with no such +// ancestor. +.str-chat__scheduled-message-list-modal > .str-chat__modal__dialog { + max-width: calc(100% - 2 * var(--str-chat__spacing-md)); +} + .str-chat { .str-chat__scheduled-message-list-dialog { width: 520px; max-width: 100%; + // A fixed height, as ChannelDetail's: sized to its content, the dialog would grow and shrink + // with every search keystroke and page loaded. + height: min(640px, calc(100dvh - 2 * var(--str-chat__spacing-md))); // the list scrolls, so reaching its end loads the next page .str-chat__scheduled-message-list-dialog__body { display: flex; + flex: 1; flex-direction: column; min-height: 0; overflow: hidden; From 023ee176362573989082b177db4ed1c7a0d2dae4 Mon Sep 17 00:00:00 2001 From: martincupela Date: Thu, 12 Nov 2026 12:31:36 +0100 Subject: [PATCH 05/35] fix(ScheduledMessages): load lists only when needed and keep schedule limits current - Split the list hooks: useScheduledMessages only reads a view, useChannelScheduledMessages loads a channel's list only when the channel was queried without it and the user can schedule there, and useScheduledMessageList loads the first page of a list the app registers. The banner no longer queries scheduled messages in every channel. - useCanScheduleMessage recomputes the block reason when any store the rule reads changes, instead of caching it per store. - ScheduleTimeDialog recomputes its time limits every minute and checks the time again on submit, so a time that passed meanwhile is not sent at once. It takes DateInput and TimeInput component props and is a ComponentContext slot (ScheduleTimeDialog). - Conflict reloads moved out of the UI; the channel's lists and the events keep them current. --- .../hooks/useMessageComposerSubmitFn.ts | 21 +-- .../ScheduleMessageButton.tsx | 9 +- .../ScheduledMessages/ScheduleTimeDialog.tsx | 137 +++++++++++++----- .../ScheduledMessageItem.tsx | 20 +-- .../ScheduledMessageListDialog.tsx | 4 +- .../ScheduledMessagesBanner.tsx | 4 +- .../__tests__/ScheduleMessageButton.test.tsx | 75 ++++++++++ .../ScheduledMessagesBanner.test.tsx | 26 +++- .../ScheduledMessages/hooks/index.ts | 2 + .../hooks/useCanScheduleMessage.ts | 50 +++++-- .../hooks/useChannelScheduledMessages.ts | 43 ++++++ .../hooks/useScheduledMessageList.ts | 37 +++++ .../hooks/useScheduledMessages.ts | 27 +--- src/components/ScheduledMessages/utils.ts | 18 --- src/context/ComponentContext.tsx | 6 + .../ScheduledMessagesView.tsx | 4 +- 16 files changed, 346 insertions(+), 137 deletions(-) create mode 100644 src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts create mode 100644 src/components/ScheduledMessages/hooks/useScheduledMessageList.ts diff --git a/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts b/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts index 0079de12a0..513039620a 100644 --- a/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts +++ b/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts @@ -1,10 +1,6 @@ import { useCallback } from 'react'; -import { useChatContext } from '../../../context'; -import { - isFailedScheduledMessage, - reloadOnScheduledMessageConflict, -} from '../../ScheduledMessages/utils'; +import { isFailedScheduledMessage } from '../../ScheduledMessages/utils'; import { useMessageComposerController } from './useMessageComposerController'; /** @@ -15,25 +11,16 @@ import { useMessageComposerController } from './useMessageComposerController'; * @returns Submit callback, stable while the composer is the same. */ export const useMessageComposerSubmitFn = () => { - const { client } = useChatContext(); const messageComposer = useMessageComposerController(); - return useCallback(async () => { + return useCallback(() => { // a failed one open in the composer is sent or scheduled again instead const { editedScheduledMessage } = messageComposer; if (editedScheduledMessage && !isFailedScheduledMessage(editedScheduledMessage)) { - const result = await messageComposer.updateScheduledMessage(); - if (result.status === 'failed') { - reloadOnScheduledMessageConflict( - client, - messageComposer.channel.cid, - result.error, - ); - } - return result; + return messageComposer.updateScheduledMessage(); } return messageComposer.editedMessage ? messageComposer.update() : messageComposer.send(); - }, [client, messageComposer]); + }, [messageComposer]); }; diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx index bec0c417f4..d8a7a0e6cd 100644 --- a/src/components/ScheduledMessages/ScheduleMessageButton.tsx +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -26,7 +26,7 @@ import { useMessageComposerHasSendableData } from '../MessageComposer/hooks'; import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; import { GlobalModal } from '../Modal'; import { Portal } from '../Portal/Portal'; -import { ScheduleTimeDialog } from './ScheduleTimeDialog'; +import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { getSchedulePresets, getScheduleTimeBounds } from './utils'; const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); @@ -48,8 +48,11 @@ export const ScheduleMessageButton = () => { const { t } = useTranslationContext(); const { client } = useChatContext(); const { IconChevronUp, IconClock } = useComponentContextIcons(); - const { ContextMenu: ContextMenuComponent = ContextMenu, Modal = GlobalModal } = - useComponentContext(); + const { + ContextMenu: ContextMenuComponent = ContextMenu, + Modal = GlobalModal, + ScheduleTimeDialog = DefaultScheduleTimeDialog, + } = useComponentContext(); const messageComposer = useMessageComposerController(); const hasSendableData = useMessageComposerHasSendableData(); diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx index e87ab6495f..b27a8b26ac 100644 --- a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -1,4 +1,4 @@ -import React, { type MouseEvent, useState } from 'react'; +import React, { type ComponentType, type MouseEvent, useEffect, useState } from 'react'; import type { Channel, LocalMessage } from 'stream-chat'; import { useComponentContextIcons, useTranslationContext } from '../../context'; @@ -20,6 +20,24 @@ import { translateScheduledMessageError, } from './utils'; +/** The date field of `ScheduleTimeDialog`; values are `YYYY-MM-DD`, as `` takes. */ +export type ScheduleDateInputProps = { + label: string; + /** The earliest date allowed. */ + min: string; + onChange: (value: string) => void; + value: string; + /** The latest date allowed, when there is a limit. */ + max?: string; +}; + +/** The time field of `ScheduleTimeDialog`; values are `HH:mm`, as `` takes. */ +export type ScheduleTimeInputProps = { + label: string; + onChange: (value: string) => void; + value: string; +}; + export type ScheduleTimeDialogProps = { channel: Channel; close: () => void; @@ -29,14 +47,79 @@ export type ScheduleTimeDialogProps = { /** Closes the dialog once it resolves. */ submit: (scheduledAt: Date) => Promise; title: string; + /** Replaces the date field. */ + DateInput?: ComponentType; initialScheduledAt?: Date; /** Above the preview; "Message to {{ name }}" by default. */ previewLabel?: string; submitLabel?: string; + /** Replaces the time field. */ + TimeInput?: ComponentType; /** Why an earlier time is refused; "Choose a later time" by default. */ tooSoonMessage?: string; }; +const BOUNDS_REFRESH_INTERVAL_MS = 60 * 1000; + +/** The current time, updated every minute, so time limits computed from it do not go stale. */ +const useMinuteClock = () => { + const [now, setNow] = useState(() => new Date()); + useEffect(() => { + const interval = setInterval(() => setNow(new Date()), BOUNDS_REFRESH_INTERVAL_MS); + return () => clearInterval(interval); + }, []); + return [now, setNow] as const; +}; + +const DefaultScheduleDateInput = ({ + label, + max, + min, + onChange, + value, +}: ScheduleDateInputProps) => { + const { t } = useTranslationContext(); + const { IconCalendar, IconCaretDown } = useComponentContextIcons(); + const selectedDate = fromInputValues(value); + return ( + + + + {selectedDate && t('timestamp.ScheduleDate', { timestamp: selectedDate })} + + + } + max={max} + min={min} + onChange={({ target }) => onChange(target.value)} + required + trailing={} + type='date' + value={value} + /> + ); +}; + +const DefaultScheduleTimeInput = ({ label, onChange, value }: ScheduleTimeInputProps) => { + const { IconCaretDown, IconClock } = useComponentContextIcons(); + return ( + } + onChange={({ target }) => onChange(target.value)} + required + trailing={} + type='time' + value={value} + /> + ); +}; + /** A click anywhere in a field, its icons included, opens the field's picker. */ const openNativePicker = ({ target }: MouseEvent) => { const input = (target as Element) @@ -53,38 +136,45 @@ const openNativePicker = ({ target }: MouseEvent) => { export const ScheduleTimeDialog = ({ channel, close, + DateInput = DefaultScheduleDateInput, errorMessage, initialScheduledAt, previewLabel, previewMessage, submit, submitLabel, + TimeInput = DefaultScheduleTimeInput, title, tooSoonMessage, }: ScheduleTimeDialogProps) => { const { t } = useTranslationContext(); - const { IconCalendar, IconCaretDown, IconClock } = useComponentContextIcons(); const channelDisplayName = useChannelDisplayName(channel); const isOnline = useWSConnectionState()?.isHealthy ?? false; const isMounted = useIsMounted(); - const [bounds] = useState(() => getScheduleTimeBounds(channel)); - const [dateValue, setDateValue] = useState(() => - toDateInputValue(initialScheduledAt ?? getDefaultScheduledAt(bounds)), - ); - const [timeValue, setTimeValue] = useState(() => - toTimeInputValue(initialScheduledAt ?? getDefaultScheduledAt(bounds)), + // the limits move with the clock: a time allowed when the dialog opened may be too soon later + const [now, setNow] = useMinuteClock(); + const bounds = getScheduleTimeBounds(channel, now); + const [initialValue] = useState( + () => initialScheduledAt ?? getDefaultScheduledAt(bounds), ); + const [dateValue, setDateValue] = useState(() => toDateInputValue(initialValue)); + const [timeValue, setTimeValue] = useState(() => toTimeInputValue(initialValue)); const [status, setStatus] = useState<'failed' | 'idle' | 'submitting'>('idle'); const [submitError, setSubmitError] = useState(); const scheduledAt = fromInputValues(dateValue, timeValue); const timeError = scheduledAt && getScheduleTimeError(scheduledAt, bounds); - const selectedDate = fromInputValues(dateValue); const canSubmit = !!scheduledAt && !timeError && isOnline && status !== 'submitting'; const submitScheduledAt = async () => { if (!scheduledAt) return; + // checked again against the limits as of now; a time already passed would be sent at once + const submittedAt = new Date(); + if (getScheduleTimeError(scheduledAt, getScheduleTimeBounds(channel, submittedAt))) { + setNow(submittedAt); + return; + } setStatus('submitting'); try { await submit(scheduledAt); @@ -132,37 +222,16 @@ export const ScheduleTimeDialog = ({ className='str-chat__schedule-message-dialog__fields' onClick={openNativePicker} > - - - - {selectedDate && - t('timestamp.ScheduleDate', { timestamp: selectedDate })} - - - } max={bounds.latest && toDateInputValue(bounds.latest)} min={toDateInputValue(bounds.earliest)} - onChange={({ target }) => setDateValue(target.value)} - required - trailing={} - type='date' + onChange={setDateValue} value={dateValue} /> - } - onChange={({ target }) => setTimeValue(target.value)} - required - trailing={} - type='time' + onChange={setTimeValue} value={timeValue} />
diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index 5057c4f09a..066c6a7c6b 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -28,12 +28,11 @@ import { useStableId } from '../UtilityComponents/useStableId'; import { VisuallyHidden } from '../VisuallyHidden'; import { SCHEDULE_MESSAGE_CAPABILITY } from './hooks'; import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; -import { ScheduleTimeDialog } from './ScheduleTimeDialog'; +import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { getChannelByCid, getScheduledMessageActions, isFailedScheduledMessage, - reloadOnScheduledMessageConflict, SCHEDULED_MESSAGE_NOTIFICATION_TYPE, SCHEDULED_MESSAGES_EMITTER, translateScheduledMessageError, @@ -71,8 +70,11 @@ export const ScheduledMessageItem = ({ IconMore, IconSend, } = useComponentContextIcons(); - const { ContextMenu: ContextMenuComponent = ContextMenu, Modal = GlobalModal } = - useComponentContext(); + const { + ContextMenu: ContextMenuComponent = ContextMenu, + Modal = GlobalModal, + ScheduleTimeDialog = DefaultScheduleTimeDialog, + } = useComponentContext(); const { addNotification } = useNotificationApi(); const isMounted = useIsMounted(); @@ -136,7 +138,6 @@ export const ScheduledMessageItem = ({ }); } } catch (error) { - reloadOnScheduledMessageConflict(client, cid, error); addNotification({ emitter: SCHEDULED_MESSAGES_EMITTER, error: error as Error, @@ -202,14 +203,9 @@ export const ScheduledMessageItem = ({ 'scheduledMessages.couldntRescheduleTheMessageTryAgain', "Couldn't reschedule the message. Try again", ); + // a failure keeps the dialog open, showing it const reschedule = async (scheduledAt: Date) => { - try { - await getChannel().updateScheduledMessage(id, { scheduled_at: scheduledAt }); - } catch (error) { - reloadOnScheduledMessageConflict(client, cid, error); - // the dialog stays open and shows the failure - throw error; - } + await getChannel().updateScheduledMessage(id, { scheduled_at: scheduledAt }); }; const deleteScheduledMessage = () => { diff --git a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx index 0f577e5fa9..b13e26d0bc 100644 --- a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx @@ -12,7 +12,7 @@ import { Prompt } from '../Dialog'; import { TextInput } from '../Form'; import { GlobalModal } from '../Modal'; import { Portal } from '../Portal/Portal'; -import { useScheduledMessages, useScheduledMessagesSearch } from './hooks'; +import { useChannelScheduledMessages, useScheduledMessagesSearch } from './hooks'; import type { ScheduledMessagesView } from 'stream-chat'; import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; import { ScheduledMessageList as DefaultScheduledMessageList } from './ScheduledMessageList'; @@ -37,7 +37,7 @@ const ScheduledMessageListDialogBody = ({ const { t } = useTranslationContext(); const { IconSearch, IconXCircle } = useComponentContextIcons(); const { ScheduledMessageList = DefaultScheduledMessageList } = useComponentContext(); - const { scheduledMessages } = useScheduledMessages(view); + const { scheduledMessages } = useChannelScheduledMessages(view); const { filter, searchQuery, setSearchQuery } = useScheduledMessagesSearch(); const searchInputRef = useRef(null); diff --git a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx index b156a8beaa..36bbe7df3c 100644 --- a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx +++ b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx @@ -16,7 +16,7 @@ import { useStateStore } from '../../store'; import { useAriaLiveAnnouncer } from '../Accessibility'; import { useChannelCapabilities } from '../Channel/hooks/useChannelCapabilities'; import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; -import { SCHEDULE_MESSAGE_CAPABILITY, useScheduledMessages } from './hooks'; +import { SCHEDULE_MESSAGE_CAPABILITY, useChannelScheduledMessages } from './hooks'; import { ScheduledMessageListDialog as DefaultScheduledMessageListDialog } from './ScheduledMessageListDialog'; import { isFailedScheduledMessage } from './utils'; @@ -53,7 +53,7 @@ export const ScheduledMessagesBanner = () => { const canSchedule = useChannelCapabilities({ cid: channel.cid }).has( SCHEDULE_MESSAGE_CAPABILITY, ); - const { scheduledMessages } = useScheduledMessages(view); + const { scheduledMessages } = useChannelScheduledMessages(view); const { isLoaded } = useStateStore(view.paginator.state, selectIsLoaded); const { isEditing } = useStateStore(messageComposer.state, selectIsEditing); const announce = useAriaLiveAnnouncer(); diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx index 4695f96f24..02f56f7f49 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -23,6 +23,11 @@ import { Channel } from '../../Channel'; import { Chat } from '../../Chat'; import { WithComponents } from '../../../context/WithComponents'; import { MessageComposer } from '../../MessageComposer'; +import { ScheduleTimeDialog } from '../ScheduleTimeDialog'; +import type { + ScheduleDateInputProps, + ScheduleTimeInputProps, +} from '../ScheduleTimeDialog'; import { convertDateToTimestamp, erroredScheduledMessageApi, @@ -149,6 +154,21 @@ describe('ScheduleMessageButton', () => { expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); }); + it('comes back when the location that blocked scheduling is removed', async () => { + const { channel } = await renderComposer(); + const { locationComposer } = channel.messageComposer; + + await act(() => locationComposer.setData({ latitude: 50, longitude: 14 })); + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + // a change in another store the rule reads, while the location still blocks + await act(() => + channel.messageComposer.state.partialNext({ showReplyInChannel: true }), + ); + await act(() => locationComposer.initState()); + + expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); + }); + it('can be removed through ComponentContext', async () => { await renderComposer({ components: { ScheduleMessageButton: null } }); @@ -429,6 +449,61 @@ describe('ScheduleMessageButton', () => { expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); }); + it('checks the time again on submit, against the limits as of then', async () => { + const { channel } = await renderComposer(); + const schedule = mockSchedule(channel); + + await openDialog(); + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '10:35' } }); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); + // the dialog stayed open: 10:35 is now in the past and would be sent at once + vi.setSystemTime(new Date(2026, 9, 28, 10, 40)); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(schedule).not.toHaveBeenCalled(); + expect(screen.getByText('Choose a later time')).toBeInTheDocument(); + expect(screen.getByTestId('schedule-message-dialog')).toBeInTheDocument(); + }); + + it('takes custom date and time fields', async () => { + const DateInput = ({ onChange, value }: ScheduleDateInputProps) => ( + onChange(target.value)} + value={value} + /> + ); + const TimeInput = ({ onChange, value }: ScheduleTimeInputProps) => ( + onChange(target.value)} + value={value} + /> + ); + const { channel } = await renderComposer({ + components: { + ScheduleTimeDialog: (props) => ( + + ), + }, + }); + const schedule = mockSchedule(channel).mockResolvedValue( + scheduledResult(generateScheduledMessage({ cid: channel.cid })), + ); + + await openDialog(); + expect(screen.queryByLabelText('Date')).not.toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Custom date'), { + target: { value: '2026-11-03' }, + }); + fireEvent.change(screen.getByLabelText('Custom time'), { + target: { value: '16:45' }, + }); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(schedule).toHaveBeenCalledWith(new Date(2026, 10, 3, 16, 45)); + }); + it('closes without scheduling on Cancel', async () => { const { channel } = await renderComposer(); const schedule = mockSchedule(channel); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx index 8ba0175541..94315a6a22 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -257,25 +257,37 @@ describe('ScheduledMessagesBanner', () => { expect(queryBanner()).toHaveTextContent('2 scheduled replies'); }); - it('stays hidden without the schedule-message capability', async () => { - await renderComposer({ + /** Without the capability nothing is queried: the messages come with the channel query. */ + const renderWithoutCapability = async ( + scheduledMessages: ScheduledMessageResponse[], + ) => { + const { channel, client } = await renderComposer({ + awaitsScheduledMessages: false, canSchedule: false, - scheduledMessages: [generateScheduledMessage({ cid })], }); + act(() => channel.scheduledMessagesPaginator.hydrate(scheduledMessages)); + return { channel, client }; + }; + + it('stays hidden without the schedule-message capability', async () => { + await renderWithoutCapability([generateScheduledMessage({ cid })]); expect(queryBanner()).not.toBeInTheDocument(); }); it('shows failed scheduled messages without the schedule-message capability', async () => { - await renderComposer({ - canSchedule: false, - scheduledMessages: [generateScheduledMessage({ cid, status: 'failed' })], - }); + await renderWithoutCapability([generateScheduledMessage({ cid, status: 'failed' })]); expect(queryBanner()).toHaveTextContent('1 failed to send'); expect(queryBanner()).toHaveTextContent('View all'); }); + it('does not query scheduled messages without the schedule-message capability', async () => { + const { client } = await renderWithoutCapability([]); + + expect(client.queryScheduledMessages).not.toHaveBeenCalled(); + }); + it('updates when scheduled message events arrive', async () => { const { client } = await renderComposer(); const scheduledMessage = generateScheduledMessage({ cid }); diff --git a/src/components/ScheduledMessages/hooks/index.ts b/src/components/ScheduledMessages/hooks/index.ts index 7c390e1153..fa6f7df41c 100644 --- a/src/components/ScheduledMessages/hooks/index.ts +++ b/src/components/ScheduledMessages/hooks/index.ts @@ -1,3 +1,5 @@ export * from './useCanScheduleMessage'; +export * from './useChannelScheduledMessages'; +export * from './useScheduledMessageList'; export * from './useScheduledMessages'; export * from './useScheduledMessagesSearch'; diff --git a/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts index ad6f9122ff..0598894aa2 100644 --- a/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts +++ b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts @@ -1,5 +1,6 @@ -import { useMemo } from 'react'; +import { useEffect, useState } from 'react'; import type { + MessageComposer, MessageComposerState, ScheduledMessagePaginatorsManagerState, } from 'stream-chat'; @@ -20,37 +21,54 @@ const selectIsEditing = (state: MessageComposerState) => ({ isEditing: isComposerEditing(state), }); +/** + * `messageComposer.scheduleBlockReason`, kept current. The rule reads the composer, its text and + * location composers, and the channel's config and capabilities, so a change to any of them + * recomputes it. + */ +const useScheduleBlockReason = (messageComposer: MessageComposer) => { + const [blockReason, setBlockReason] = useState( + () => messageComposer.scheduleBlockReason, + ); + + useEffect(() => { + const { channel, locationComposer, textComposer } = messageComposer; + const update = () => setBlockReason(messageComposer.scheduleBlockReason); + const unsubscribes = [ + messageComposer.state, + textComposer.state, + locationComposer.state, + channel.state, + channel.configState, + ].map((store) => store.subscribe(update)); + return () => unsubscribes.forEach((unsubscribe) => unsubscribe()); + }, [messageComposer]); + + return blockReason; +}; + /** * Whether the composition can be scheduled: the channel allows it, the feature is on, nothing is - * being edited and the composition holds nothing that cannot be scheduled (a command, a poll, a - * location). `scheduleBlockReason` reads three stores, so each is subscribed to. + * being edited and the composition holds nothing that cannot be scheduled (a command or a location). */ export const useCanScheduleMessage = () => { const { client } = useChatContext(); const messageComposer = useMessageComposerController(); - const { channel, locationComposer, textComposer } = messageComposer; - const channelCapabilities = useChannelCapabilities({ cid: channel.cid }); - - const selectBlockReason = useMemo( - () => () => ({ scheduleBlockReason: messageComposer.scheduleBlockReason }), - [messageComposer], - ); + const channelCapabilities = useChannelCapabilities({ + cid: messageComposer.channel.cid, + }); const { isDisabled } = useStateStore( client.scheduledMessagePaginators.state, selectIsDisabled, ); const { isEditing } = useStateStore(messageComposer.state, selectIsEditing); - const blockReasons = [ - useStateStore(messageComposer.state, selectBlockReason).scheduleBlockReason, - useStateStore(textComposer.state, selectBlockReason).scheduleBlockReason, - useStateStore(locationComposer.state, selectBlockReason).scheduleBlockReason, - ]; + const blockReason = useScheduleBlockReason(messageComposer); return ( channelCapabilities.has(SCHEDULE_MESSAGE_CAPABILITY) && !isDisabled && !isEditing && - !blockReasons.some(Boolean) + !blockReason ); }; diff --git a/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts new file mode 100644 index 0000000000..0e20861929 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts @@ -0,0 +1,43 @@ +import { useEffect } from 'react'; +import type { ChannelConfig, ChannelStateData, ScheduledMessagesView } from 'stream-chat'; + +import { useChatContext } from '../../../context'; +import { useStateStore } from '../../../store'; +import { useScheduledMessages } from './useScheduledMessages'; + +const selectLoadConditions = ({ + initialized, + ownCapabilities, +}: Pick) => ({ + initialized, + ownCapabilities, +}); + +const selectIsEnabledByConfig = ({ scheduledMessages }: ChannelConfig) => ({ + isEnabledByConfig: scheduledMessages.enabled, +}); + +/** + * The messages of a channel's scheduled-message view: `channel.scheduledMessages` or + * `thread.scheduledMessages`. The channel query fills the channel's list; this loads it only for a + * channel queried without it (`queryChannels` leaves it out when the page's channels hold over 100) + * where the user can schedule messages. + */ +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, selectLoadConditions) ?? {}; + const { isEnabledByConfig } = + useStateStore(channel?.configState, selectIsEnabledByConfig) ?? {}; + + useEffect(() => { + if (!channel || !initialized) return; + const paginator = channel.scheduledMessagesPaginator; + if (paginator.hasLoadedPage || !channel.scheduledMessagesEnabled) return; + paginator.reload().catch(() => undefined); + }, [channel, initialized, isEnabledByConfig, ownCapabilities]); + + return useScheduledMessages(view); +}; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts b/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts new file mode 100644 index 0000000000..6592d520ff --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessageList.ts @@ -0,0 +1,37 @@ +import { useEffect, useMemo } from 'react'; +import type { + PaginatorState, + ScheduledMessageResponse, + ScheduledMessagesView, +} from 'stream-chat'; + +import { useStateStore } from '../../../store'; +import { useScheduledMessages } from './useScheduledMessages'; + +const createAwaitsFirstPageSelector = + (view: ScheduledMessagesView) => + ({ isLoading, lastQueryError }: PaginatorState) => ({ + awaitsFirstPage: !view.paginator.hasLoadedPage && !isLoading && !lastQueryError, + }); + +/** + * The messages of a view of a list registered with `client.scheduledMessagePaginators`, e.g. the + * user's scheduled messages in every channel. Nothing else loads such a list, so this loads its + * first page, as `ChannelList` does; not again after a failed load, which the UI retries. + */ +export const useScheduledMessageList = (view: ScheduledMessagesView) => { + const awaitsFirstPageSelector = useMemo( + () => createAwaitsFirstPageSelector(view), + [view], + ); + const { awaitsFirstPage } = useStateStore( + view.paginator.state, + awaitsFirstPageSelector, + ); + + useEffect(() => { + if (awaitsFirstPage) view.toTailDebounced(); + }, [awaitsFirstPage, view]); + + return useScheduledMessages(view); +}; diff --git a/src/components/ScheduledMessages/hooks/useScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts index 7150a4c872..975c8ad74b 100644 --- a/src/components/ScheduledMessages/hooks/useScheduledMessages.ts +++ b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts @@ -1,6 +1,5 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect } from 'react'; import type { - PaginatorState, ScheduledMessageResponse, ScheduledMessagesView, ScheduledMessagesViewState, @@ -12,17 +11,9 @@ const NO_SCHEDULED_MESSAGES: ScheduledMessageResponse[] = []; const selectItems = ({ items }: ScheduledMessagesViewState) => ({ items }); -const createAwaitsFirstPageSelector = - (view: ScheduledMessagesView) => - ({ isLoading, lastQueryError }: PaginatorState) => ({ - awaitsFirstPage: !view.paginator.hasLoadedPage && !isLoading && !lastQueryError, - }); - /** - * The messages of an SDK scheduled-message view: `channel.scheduledMessages`, - * `thread.scheduledMessages`, or a view of a list registered with - * `client.scheduledMessagePaginators`. Keeps the view following its paginator while mounted, and - * loads the first page unless one is loaded, as `ChannelList` does. + * The messages of an SDK 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(() => { @@ -32,18 +23,6 @@ export const useScheduledMessages = (view: ScheduledMessagesView) => { }; }, [view]); - const awaitsFirstPageSelector = useMemo( - () => createAwaitsFirstPageSelector(view), - [view], - ); - const { awaitsFirstPage } = useStateStore( - view.paginator.state, - awaitsFirstPageSelector, - ); - useEffect(() => { - if (awaitsFirstPage) view.toTailDebounced(); - }, [awaitsFirstPage, view]); - const { items } = useStateStore(view.state, selectItems); return { scheduledMessages: items ?? NO_SCHEDULED_MESSAGES }; }; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 99a4c63b2b..5a50b05bb2 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -158,24 +158,6 @@ export const isComposerEditing = ({ !!editedMessage || (!!editedScheduledMessage && !isFailedScheduledMessage(editedScheduledMessage)); -/** - * After a conflict (the message changed elsewhere), reloads the lists that may hold the stale copy: - * the channel's own and the ones registered with the client. - */ -export const reloadOnScheduledMessageConflict = ( - client: StreamChat, - cid: string, - error: unknown, -) => { - if (getScheduledMessageErrorReason(error) !== ScheduledMessageErrorReason.Conflict) - return; - const { scheduledMessagesPaginator } = getChannelByCid(client, cid); - if (scheduledMessagesPaginator.hasLoadedPage) { - scheduledMessagesPaginator.reload().catch(() => undefined); - } - void client.scheduledMessagePaginators.recover(); -}; - /** Why a scheduled message failed; `undefined` when the reason needs no explanation. */ export const translateScheduledMessageFailureReason = ( t: StreamTFunction, diff --git a/src/context/ComponentContext.tsx b/src/context/ComponentContext.tsx index 45ff125bf7..93ab6701a0 100644 --- a/src/context/ComponentContext.tsx +++ b/src/context/ComponentContext.tsx @@ -83,6 +83,7 @@ import type { ScheduledMessageListDialogProps, ScheduledMessageListProps, ScheduledMessagePreviewProps, + ScheduleTimeDialogProps, } from '../components/ScheduledMessages'; export type ComponentContextValue = { @@ -328,6 +329,11 @@ export type ComponentContextValue = { ScheduledMessagesBanner?: React.ComponentType | null; /** Schedule button next to the send button; `null` hides it. */ ScheduleMessageButton?: React.ComponentType | null; + /** + * The dialog for picking a custom time, opened by the schedule button and by rescheduling. To + * replace only its date or time field, render the default with `DateInput` or `TimeInput`. + */ + ScheduleTimeDialog?: React.ComponentType; /** Translation indicator, shown when the message has `i18n`. */ MessageTranslationIndicator?: React.ComponentType; /** diff --git a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx index 69ce88f805..f7081363d9 100644 --- a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx +++ b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx @@ -9,7 +9,7 @@ import { import { Prompt } from '../../../../components/Dialog'; import { ScheduledMessageList as DefaultScheduledMessageList, - useScheduledMessages, + useChannelScheduledMessages, useScheduledMessagesSearch, } from '../../../../components/ScheduledMessages'; import { ChannelDetailSearchInput } from '../../ChannelDetailSearchInput'; @@ -22,7 +22,7 @@ export const ScheduledMessagesView = () => { const { close } = useModalContext(); const { channel } = useChannelDetailContext(); - const { scheduledMessages } = useScheduledMessages(channel.scheduledMessages); + const { scheduledMessages } = useChannelScheduledMessages(channel.scheduledMessages); const { filter, setSearchQuery } = useScheduledMessagesSearch(); const editScheduledMessage = useCallback( From 886995dad173a5d28ad6186c3f045ed9a6badb14 Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 10:22:18 +0100 Subject: [PATCH 06/35] feat(ScheduledMessages): show the send time with Reschedule while editing a scheduled message - Editing a pending scheduled message shows "This message will be sent {time}" with a Reschedule button, as in the Figma edit frame, in place of the "Edit scheduled message" quote. Reschedule saves only the new time and keeps the edit open. A failed message keeps its "Schedule again" preview. - The reschedule settings of ScheduleTimeDialog come from one hook, useRescheduleDialogProps, shared by the list row and the composer preview. - The scheduled-message preview is first in the default preview set, and the quoted message shows while a scheduled message is edited, so its quote can be removed. Co-Authored-By: Claude Opus 5.5 --- .../MessageComposerPreviews.defaults.tsx | 16 +-- .../ScheduledMessageItem.tsx | 32 +----- .../ScheduledMessagePreview.tsx | 105 ++++++++++++++++-- .../__tests__/EditScheduledMessage.test.tsx | 89 ++++++++++++++- .../hooks/useRescheduleDialogProps.ts | 56 ++++++++++ .../styling/ScheduledMessagePreview.scss | 38 +++++++ .../ScheduledMessages/styling/index.scss | 1 + src/i18n/__tests__/catalog.fixture.json | 3 +- src/i18n/keys.ts | 3 +- 9 files changed, 290 insertions(+), 53 deletions(-) create mode 100644 src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts create mode 100644 src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss diff --git a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx index bbd1081490..a1b1ff1e4c 100644 --- a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx +++ b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx @@ -110,21 +110,21 @@ const DefaultMessageComposerPreviewComponents = { * extend it and pass the result as `messageComposerPreviewSet`. */ export const defaultMessageComposerPreviewSet: MessageComposerPreviewSetItem[] = [ - { - Component: DefaultMessageComposerPreviewComponents.EditedMessage, - isVisible: ({ editedMessage }) => !!editedMessage, - type: 'editedMessage', - }, { Component: DefaultMessageComposerPreviewComponents.ScheduledMessage, isVisible: ({ editedScheduledMessage }) => !!editedScheduledMessage, type: 'scheduledMessage', }, + { + Component: DefaultMessageComposerPreviewComponents.EditedMessage, + isVisible: ({ editedMessage }) => !!editedMessage, + type: 'editedMessage', + }, { Component: DefaultMessageComposerPreviewComponents.QuotedMessage, - // The edited message preview takes the quoted message's place while editing. - isVisible: ({ editedMessage, editedScheduledMessage, quotedMessage }) => - !editedMessage && !editedScheduledMessage && !!quotedMessage, + // The edited message preview takes the quoted message's place while editing. A scheduled + // message keeps its quote visible, so it can be removed before the message is sent. + isVisible: ({ editedMessage, quotedMessage }) => !editedMessage && !!quotedMessage, type: 'quotedMessage', }, { diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index 066c6a7c6b..c267961854 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -28,6 +28,7 @@ import { useStableId } from '../UtilityComponents/useStableId'; import { VisuallyHidden } from '../VisuallyHidden'; import { SCHEDULE_MESSAGE_CAPABILITY } from './hooks'; import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; +import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { getChannelByCid, @@ -91,6 +92,10 @@ export const ScheduledMessageItem = ({ const editUnavailableId = useStableId(); const getChannel = () => getChannelByCid(client, cid); const previewMessage = useScheduledMessagePreview(scheduledMessage); + const rescheduleDialogProps = useRescheduleDialogProps({ + previewMessage, + scheduledMessage, + }); const sendTime = nsToDate(scheduled_at); const isFailed = isFailedScheduledMessage(scheduledMessage); // a pending message is saved by scheduling it, a failed one is scheduled or sent again; a frozen @@ -199,15 +204,6 @@ export const ScheduledMessageItem = ({ }, }; - const rescheduleErrorMessage = t( - 'scheduledMessages.couldntRescheduleTheMessageTryAgain', - "Couldn't reschedule the message. Try again", - ); - // a failure keeps the dialog open, showing it - const reschedule = async (scheduledAt: Date) => { - await getChannel().updateScheduledMessage(id, { scheduled_at: scheduledAt }); - }; - const deleteScheduledMessage = () => { closeDialog(); void run(() => getChannel().deleteScheduledMessage(id), { @@ -366,23 +362,7 @@ export const ScheduledMessageItem = ({ )} diff --git a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx index 2a8ffabaa4..009e289997 100644 --- a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx +++ b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx @@ -1,9 +1,20 @@ -import React from 'react'; +import React, { useState } from 'react'; +import { nsToDate } from 'stream-chat'; import type { ScheduledMessageResponse } from 'stream-chat'; -import { useTranslationContext } from '../../context'; +import { + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { Button } from '../Button'; +import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; import { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; +import { RemoveAttachmentPreviewButton } from '../MessageComposer/RemoveAttachmentPreviewButton'; +import { GlobalModal } from '../Modal'; import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; +import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; +import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { isFailedScheduledMessage } from './utils'; export type ScheduledMessagePreviewProps = { @@ -11,22 +22,92 @@ export type ScheduledMessagePreviewProps = { scheduledMessage: ScheduledMessageResponse; }; -/** Above the composer while a scheduled message is edited, or a failed one scheduled again. */ +/** + * Above the composer while a scheduled message is edited: when it is sent, with a way to change + * that time. A failed one, scheduled again as a new message, is previewed as the message. + */ export const ScheduledMessagePreview = ({ onCancel, scheduledMessage, }: ScheduledMessagePreviewProps) => { const { t } = useTranslationContext(); + const { IconClock } = useComponentContextIcons(); + const { Modal = GlobalModal, ScheduleTimeDialog = DefaultScheduleTimeDialog } = + useComponentContext(); + const { channel } = useMessageComposerController(); const previewMessage = useScheduledMessagePreview(scheduledMessage); + const [isRescheduling, setIsRescheduling] = useState(false); + // the saved copy, until the composer's own copy catches up through the update event + const [rescheduled, setRescheduled] = useState(); + const current = + rescheduled?.id === scheduledMessage.id && + rescheduled.updated_at > scheduledMessage.updated_at + ? rescheduled + : scheduledMessage; + const rescheduleDialogProps = useRescheduleDialogProps({ + onRescheduled: setRescheduled, + previewMessage, + scheduledMessage: current, + }); + + if (isFailedScheduledMessage(scheduledMessage)) { + return ( + + ); + } + + const sendTime = nsToDate(current.scheduled_at); + const closeDialog = () => setIsRescheduling(false); + return ( - +
+ + + + + + {isRescheduling && ( + + )} + +
); }; diff --git a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx index 1da1337d63..19dc1a6276 100644 --- a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx +++ b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx @@ -1,18 +1,22 @@ import '../../..'; import React from 'react'; -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fromPartial } from '@total-typescript/shoehorn'; import { Channel } from '../../Channel'; import { Chat } from '../../Chat'; import { MessageComposer } from '../../MessageComposer'; import { + convertDateToTimestamp, + generateMessage, generateScheduledMessage, generateUser, initClientWithChannels, } from '../../../mock-builders'; const user = generateUser({ id: 'user-id' }); +const WEDNESDAY_MORNING = new Date(2026, 9, 28, 10, 30); +const SEND_TIME = new Date(2026, 9, 29, 9, 0); const renderComposer = async () => { const { @@ -44,6 +48,7 @@ const renderComposer = async () => { const scheduledMessage = generateScheduledMessage({ cid: channel.cid, message: { custom: {}, text: 'Launch moved to Monday' }, + scheduled_at: convertDateToTimestamp(SEND_TIME), }); const { messageComposer } = channel; @@ -72,20 +77,94 @@ const renderComposer = async () => { }; describe('editing a scheduled message in the composer', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] }); + vi.setSystemTime(WEDNESDAY_MORNING); + }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); + vi.useRealTimers(); }); - it('shows the scheduled edit preview and hides the schedule button', async () => { + it('shows when the message is sent and hides the schedule button', async () => { const { startEditing } = await renderComposer(); await startEditing(); - expect(screen.getByText('Edit scheduled message')).toBeInTheDocument(); + expect(screen.getByTestId('scheduled-message-preview')).toHaveTextContent( + 'This message will be sent Thu, Oct 29 at 09:00', + ); expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); }); + it('reschedules the message without saving the text being edited', async () => { + const { channel, messageComposer, scheduledMessage, startEditing } = + await renderComposer(); + const newSendTime = new Date(2026, 9, 29, 14, 30); + const updateScheduledMessage = vi + .spyOn(channel, 'updateScheduledMessage') + .mockResolvedValue({ + ...scheduledMessage, + scheduled_at: convertDateToTimestamp(newSendTime), + updated_at: scheduledMessage.updated_at + 1_000_000, + }); + + await startEditing(); + await act(() => messageComposer.textComposer.setText('Launch moved to Tuesday')); + await act(() => + fireEvent.click(screen.getByTestId('scheduled-message-preview-reschedule-button')), + ); + const dialog = await screen.findByTestId('schedule-message-dialog'); + expect(dialog).toHaveTextContent('Reschedule message'); + expect(screen.getByLabelText('Time')).toHaveValue('09:00'); + + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { + scheduled_at: newSendTime, + }); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + expect(screen.getByTestId('scheduled-message-preview')).toHaveTextContent( + 'This message will be sent Thu, Oct 29 at 14:30', + ); + expect(messageComposer.editedScheduledMessage?.id).toBe(scheduledMessage.id); + expect(messageComposer.textComposer.text).toBe('Launch moved to Tuesday'); + }); + + it('shows the quoted message below the send time, and lets it be removed', async () => { + const { channel, client, messageComposer } = await renderComposer(); + const quotedMessage = generateMessage({ text: 'Venue options for Saturday', user }); + client.messageStore.upsert(quotedMessage); + const quotingMessage = generateScheduledMessage({ + cid: channel.cid, + message: { custom: {}, quoted_message_id: quotedMessage.id, text: 'Booked it' }, + scheduled_at: convertDateToTimestamp(SEND_TIME), + }); + + await act(() => messageComposer.editScheduledMessage(quotingMessage)); + + const sendTimePreview = screen.getByTestId('scheduled-message-preview'); + const quotePreview = screen.getByTestId('quoted-message-preview'); + expect(quotePreview).toHaveTextContent('Venue options for Saturday'); + expect( + sendTimePreview.compareDocumentPosition(quotePreview) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + + await act(() => + fireEvent.click(screen.getByTestId('quoted-message-preview-dismiss-btn')), + ); + + expect(screen.queryByTestId('quoted-message-preview')).not.toBeInTheDocument(); + expect(messageComposer.quotedMessage).toBeNull(); + expect(screen.getByTestId('scheduled-message-preview')).toBeInTheDocument(); + }); + it('saves the edit with updateScheduledMessage instead of sending', async () => { const { channel, messageComposer, scheduledMessage, startEditing } = await renderComposer(); @@ -107,10 +186,10 @@ describe('editing a scheduled message in the composer', () => { await startEditing(); await act(() => - fireEvent.click(screen.getByRole('button', { name: /cancel|remove/i })), + fireEvent.click(screen.getByRole('button', { name: 'Cancel editing' })), ); - expect(screen.queryByText('Edit scheduled message')).not.toBeInTheDocument(); + expect(screen.queryByTestId('scheduled-message-preview')).not.toBeInTheDocument(); expect(messageComposer.textComposer.text).toBe('my unsent draft'); }); diff --git a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts new file mode 100644 index 0000000000..fc7a9bbf88 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts @@ -0,0 +1,56 @@ +import { nsToDate } from 'stream-chat'; +import type { LocalMessage, ScheduledMessageResponse } from 'stream-chat'; + +import { useChatContext, useTranslationContext } from '../../../context'; +import type { ScheduleTimeDialogProps } from '../ScheduleTimeDialog'; +import { getChannelByCid } from '../utils'; + +export type UseRescheduleDialogPropsParams = { + previewMessage: LocalMessage; + scheduledMessage: ScheduledMessageResponse; + /** Called with the server's copy once the new time is saved. */ + onRescheduled?: (scheduledMessage: ScheduledMessageResponse) => void; +}; + +/** + * `ScheduleTimeDialog` props that pick a new send time for a scheduled message and save only the + * time. The caller adds `channel` and `close`. + */ +export const useRescheduleDialogProps = ({ + onRescheduled, + previewMessage, + scheduledMessage, +}: UseRescheduleDialogPropsParams): Omit< + ScheduleTimeDialogProps, + 'channel' | 'close' +> => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const sendTime = nsToDate(scheduledMessage.scheduled_at); + + return { + errorMessage: t( + 'scheduledMessages.couldntRescheduleTheMessageTryAgain', + "Couldn't reschedule the message. Try again", + ), + initialScheduledAt: sendTime, + previewLabel: t('scheduledMessages.scheduledForTime', 'Scheduled for {{ time }}', { + time: t('timestamp.ScheduledMessageSendTime', { timestamp: sendTime }), + }), + previewMessage, + // a failure keeps the dialog open, showing it + submit: async (scheduledAt: Date) => { + const updated = await getChannelByCid( + client, + scheduledMessage.cid, + ).updateScheduledMessage(scheduledMessage.id, { scheduled_at: scheduledAt }); + onRescheduled?.(updated); + }, + submitLabel: t('scheduledMessages.save', 'Save'), + title: t('scheduledMessages.rescheduleMessage', 'Reschedule message'), + tooSoonMessage: t( + 'scheduledMessages.pickALaterTimeEditingCantSend', + "Pick a later time. Editing can't send a message right away.", + ), + }; +}; diff --git a/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss b/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss new file mode 100644 index 0000000000..a631941da1 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss @@ -0,0 +1,38 @@ +@use '../../../styling/utils'; + +.str-chat { + // above the composer while a scheduled message is edited + .str-chat__scheduled-message-preview { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-xs); + position: relative; + margin: var(--str-chat__spacing-xxs); + padding-block: var(--str-chat__spacing-xs); + padding-inline: var(--str-chat__spacing-sm) var(--str-chat__spacing-xxs); + border-radius: var(--str-chat__message-bubble-radius-attachment); + background-color: color-mix(in srgb, var(--str-chat__accent-primary) 5%, transparent); + color: var(--str-chat__text-primary); + + .str-chat__scheduled-message-preview__icon { + flex-shrink: 0; + height: var(--str-chat__icon-size-md); + width: var(--str-chat__icon-size-md); + color: var(--str-chat__accent-primary); + } + + .str-chat__scheduled-message-preview__label { + @include utils.ellipsis-text(); + flex: 1; + min-width: 0; + font: var(--str-chat__font-metadata-emphasis); + } + + // 24px tall, as the design's compact text button + .str-chat__scheduled-message-preview__reschedule-button { + flex-shrink: 0; + padding-block: var(--str-chat__spacing-xxxs); + font: var(--str-chat__font-caption-emphasis); + } + } +} diff --git a/src/components/ScheduledMessages/styling/index.scss b/src/components/ScheduledMessages/styling/index.scss index 6e20b67fea..446614f1a9 100644 --- a/src/components/ScheduledMessages/styling/index.scss +++ b/src/components/ScheduledMessages/styling/index.scss @@ -1,5 +1,6 @@ @use 'ScheduledMessageActions'; @use 'ScheduledMessageList'; +@use 'ScheduledMessagePreview'; @use 'ScheduledMessagesBanner'; @use 'ScheduledMessagesNotice'; @use 'ScheduleMessageButton'; diff --git a/src/i18n/__tests__/catalog.fixture.json b/src/i18n/__tests__/catalog.fixture.json index 194ccfdd2d..32e6780b74 100644 --- a/src/i18n/__tests__/catalog.fixture.json +++ b/src/i18n/__tests__/catalog.fixture.json @@ -604,6 +604,7 @@ "scheduledMessages.banner.scheduledReplies_other": "{{ count }} scheduled replies", "scheduledMessages.blockedByModeration": "Blocked by moderation", "scheduledMessages.cancel": "Cancel", + "scheduledMessages.cancelEditing.ariaLabel": "Cancel editing", "scheduledMessages.cantSendInThisChannel": "Unavailable: you can't send messages in this channel", "scheduledMessages.channelFrozenNotice": "This channel is frozen. Scheduled messages won't be sent", "scheduledMessages.chooseALaterTime": "Choose a later time", @@ -622,7 +623,6 @@ "scheduledMessages.deleteScheduledMessage": "Delete scheduled message?", "scheduledMessages.edit": "Edit", "scheduledMessages.editReschedule": "Edit & reschedule", - "scheduledMessages.editScheduledMessage": "Edit scheduled message", "scheduledMessages.loaded": "Scheduled messages loaded", "scheduledMessages.loadingScheduledMessages": "Loading scheduled messages", "scheduledMessages.messageToName": "Message to {{ name }}", @@ -668,6 +668,7 @@ "scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain": "This channel now needs approval. Schedule it again", "scheduledMessages.thisChannelWasDeleted": "This channel was deleted", "scheduledMessages.thisMessageToNameWontBeSentThis": "This message to {{ name }} won't be sent. This can't be undone.", + "scheduledMessages.thisMessageWillBeSentTime": "This message will be sent {{ time }}", "scheduledMessages.thisMessageWontBeSentThisCantBe": "This message won't be sent. This can't be undone.", "scheduledMessages.time": "Time", "scheduledMessages.view": "View", diff --git a/src/i18n/keys.ts b/src/i18n/keys.ts index 70a8ce2cb1..59e9727d20 100644 --- a/src/i18n/keys.ts +++ b/src/i18n/keys.ts @@ -615,6 +615,7 @@ export type TranslationCatalog = { 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} scheduled replies'; 'scheduledMessages.blockedByModeration': 'Blocked by moderation'; 'scheduledMessages.cancel': 'Cancel'; + 'scheduledMessages.cancelEditing.ariaLabel': 'Cancel editing'; 'scheduledMessages.cantSendInThisChannel': "Unavailable: you can't send messages in this channel"; 'scheduledMessages.channelFrozenNotice': "This channel is frozen. Scheduled messages won't be sent"; 'scheduledMessages.chooseALaterTime': 'Choose a later time'; @@ -633,7 +634,6 @@ export type TranslationCatalog = { 'scheduledMessages.deleteScheduledMessage': 'Delete scheduled message?'; 'scheduledMessages.edit': 'Edit'; 'scheduledMessages.editReschedule': 'Edit & reschedule'; - 'scheduledMessages.editScheduledMessage': 'Edit scheduled message'; 'scheduledMessages.loaded': 'Scheduled messages loaded'; 'scheduledMessages.loadingScheduledMessages': 'Loading scheduled messages'; 'scheduledMessages.messageToName': 'Message to {{ name }}'; @@ -679,6 +679,7 @@ export type TranslationCatalog = { 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain': 'This channel now needs approval. Schedule it again'; 'scheduledMessages.thisChannelWasDeleted': 'This channel was deleted'; 'scheduledMessages.thisMessageToNameWontBeSentThis': "This message to {{ name }} won't be sent. This can't be undone."; + 'scheduledMessages.thisMessageWillBeSentTime': 'This message will be sent {{ time }}'; 'scheduledMessages.thisMessageWontBeSentThisCantBe': "This message won't be sent. This can't be undone."; 'scheduledMessages.time': 'Time'; 'scheduledMessages.view': 'View'; From 497472da694b137101086ec0f8cec4cc7fd53a87 Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 10:22:23 +0100 Subject: [PATCH 07/35] fix(ScheduledMessages): stop treating a shared location as blocking scheduling The SDK no longer blocks scheduling a message with a shared location, so the schedule availability hook stops watching the location composer. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/ScheduleMessageButton.test.tsx | 21 ++++++++++++------- .../hooks/useCanScheduleMessage.ts | 10 ++++----- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx index 02f56f7f49..84000d223e 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -154,17 +154,24 @@ describe('ScheduleMessageButton', () => { expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); }); - it('comes back when the location that blocked scheduling is removed', async () => { - const { channel } = await renderComposer(); - const { locationComposer } = channel.messageComposer; + it('comes back when the command that blocked scheduling is removed', async () => { + const { channel } = await renderComposer({ text: '/giphy hello' }); + const { messageComposer } = channel; - await act(() => locationComposer.setData({ latitude: 50, longitude: 14 })); expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); - // a change in another store the rule reads, while the location still blocks + // a change in another store the rule reads, while the command still blocks + await act(() => messageComposer.state.partialNext({ showReplyInChannel: true })); + await act(() => messageComposer.textComposer.setText('hello')); + + expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); + }); + + it('stays with a shared location', async () => { + const { channel } = await renderComposer(); + await act(() => - channel.messageComposer.state.partialNext({ showReplyInChannel: true }), + channel.messageComposer.locationComposer.setData({ latitude: 50, longitude: 14 }), ); - await act(() => locationComposer.initState()); expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); }); diff --git a/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts index 0598894aa2..d4d6ffa087 100644 --- a/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts +++ b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts @@ -22,9 +22,8 @@ const selectIsEditing = (state: MessageComposerState) => ({ }); /** - * `messageComposer.scheduleBlockReason`, kept current. The rule reads the composer, its text and - * location composers, and the channel's config and capabilities, so a change to any of them - * recomputes it. + * `messageComposer.scheduleBlockReason`, kept current. The rule reads the composer, its text + * composer, and the channel's config and capabilities, so a change to any of them recomputes it. */ const useScheduleBlockReason = (messageComposer: MessageComposer) => { const [blockReason, setBlockReason] = useState( @@ -32,12 +31,11 @@ const useScheduleBlockReason = (messageComposer: MessageComposer) => { ); useEffect(() => { - const { channel, locationComposer, textComposer } = messageComposer; + const { channel, textComposer } = messageComposer; const update = () => setBlockReason(messageComposer.scheduleBlockReason); const unsubscribes = [ messageComposer.state, textComposer.state, - locationComposer.state, channel.state, channel.configState, ].map((store) => store.subscribe(update)); @@ -49,7 +47,7 @@ const useScheduleBlockReason = (messageComposer: MessageComposer) => { /** * Whether the composition can be scheduled: the channel allows it, the feature is on, nothing is - * being edited and the composition holds nothing that cannot be scheduled (a command or a location). + * being edited and the composition holds nothing that cannot be scheduled (a command). */ export const useCanScheduleMessage = () => { const { client } = useChatContext(); From 062d24308353bd972508cbcf22c9668e9063b41c Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 11:05:08 +0100 Subject: [PATCH 08/35] fix(ScheduledMessages): address review findings on the list and time dialog - ScheduleTimeDialog keeps the initial instant while neither field changes, so saving an unchanged reschedule no longer drops seconds, and clears a failed submission once another date or time is picked. - The default time falls back to the first whole minute allowed when the next full hour is past the latest allowed time. - ScheduledMessageList shows the load error with a retry when nothing matches and a further page failed, instead of "No messages found". - InfiniteScrollPaginator also observes its content, so content shrinking in a root of fixed size (a narrowed search) re-checks the bottom. - "Copy text" reports a missing clipboard or a rejected write. - The schedule dialog drops only the composer's scheduling notifications. - Tests import ScheduledMessageItemProps from its module; ../types did not exist. Co-Authored-By: Claude Opus 5.5 --- .../InfiniteScrollPaginator.tsx | 3 + .../InfiniteScrollPaginator.test.tsx | 8 +++ .../ScheduleMessageButton.tsx | 14 ++++- .../ScheduledMessages/ScheduleTimeDialog.tsx | 17 ++++- .../ScheduledMessageItem.tsx | 17 ++++- .../ScheduledMessageList.tsx | 18 +++++- .../__tests__/ScheduleMessageButton.test.tsx | 24 ++++++- .../ScheduledMessageActions.test.tsx | 63 ++++++++++++++++++- .../__tests__/ScheduledMessageList.test.tsx | 19 +++++- .../ScheduledMessages/__tests__/utils.test.ts | 9 +++ src/components/ScheduledMessages/utils.ts | 19 ++++-- src/i18n/__tests__/catalog.fixture.json | 1 + src/i18n/keys.ts | 1 + 13 files changed, 193 insertions(+), 20 deletions(-) diff --git a/src/components/InfiniteScrollPaginator/InfiniteScrollPaginator.tsx b/src/components/InfiniteScrollPaginator/InfiniteScrollPaginator.tsx index 1aabd9aa32..dfe9a14aab 100644 --- a/src/components/InfiniteScrollPaginator/InfiniteScrollPaginator.tsx +++ b/src/components/InfiniteScrollPaginator/InfiniteScrollPaginator.tsx @@ -194,6 +194,9 @@ export const InfiniteScrollPaginator = forwardRef(function InfiniteScrollPaginat }); }); observer.observe(root as Element); + // content can shrink inside a root of fixed size (a narrowed search, say), which leaves the + // root's size unchanged but may bring the bottom within the threshold + if (childRef.current) observer.observe(childRef.current); return () => { observer.disconnect(); diff --git a/src/components/InfiniteScrollPaginator/__tests__/InfiniteScrollPaginator.test.tsx b/src/components/InfiniteScrollPaginator/__tests__/InfiniteScrollPaginator.test.tsx index 38c6317028..6bfdfaa968 100644 --- a/src/components/InfiniteScrollPaginator/__tests__/InfiniteScrollPaginator.test.tsx +++ b/src/components/InfiniteScrollPaginator/__tests__/InfiniteScrollPaginator.test.tsx @@ -208,6 +208,14 @@ describe('InfiniteScrollPaginator', () => { expect(listenToScroll).toHaveBeenCalledTimes(1); }); + it('observes the content as well as the root', () => { + const { root } = renderPaginator(); + + const observer = ResizeObserverMock.observers.at(-1); + expect(observer?.observe).toHaveBeenCalledWith(root); + expect(observer?.observe).toHaveBeenCalledWith(root.firstElementChild); + }); + it('drops a pending check when the observer is replaced', () => { const { listenToScroll, replaceThreshold, root } = renderPaginator(); root.scrollTop = 0; diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx index d8a7a0e6cd..6acbcce16b 100644 --- a/src/components/ScheduledMessages/ScheduleMessageButton.tsx +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -1,5 +1,6 @@ import React, { useCallback, useRef, useState } from 'react'; import { + CORE_NOTIFICATION_TYPE, dateToNs, getScheduledMessageErrorReason, ScheduledMessageErrorReason, @@ -31,6 +32,12 @@ import { getSchedulePresets, getScheduleTimeBounds } from './utils'; const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); +/** The composer's notifications of a failed schedule, which the dialog reports itself. */ +const SCHEDULING_FAILURE_NOTIFICATION_TYPES: ReadonlySet = new Set([ + CORE_NOTIFICATION_TYPE.scheduledMessageBlocked, + CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed, +]); + const ScheduleMessageMenuHeader = () => { const { t } = useTranslationContext(); return ( @@ -86,8 +93,11 @@ export const ScheduleMessageButton = () => { } catch (error) { notifications.notifications .filter( - ({ id, origin }) => - !shownBefore.has(id) && origin.context?.composer === messageComposer, + ({ id, origin, type }) => + !shownBefore.has(id) && + origin.context?.composer === messageComposer && + !!type && + SCHEDULING_FAILURE_NOTIFICATION_TYPES.has(type), ) .forEach(({ id }) => notifications.remove(id)); throw error; diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx index b27a8b26ac..ad89d50865 100644 --- a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -163,7 +163,18 @@ export const ScheduleTimeDialog = ({ const [status, setStatus] = useState<'failed' | 'idle' | 'submitting'>('idle'); const [submitError, setSubmitError] = useState(); - const scheduledAt = fromInputValues(dateValue, timeValue); + // the fields hold minutes only: unchanged, they stand for the initial instant itself + const isUnchanged = + dateValue === toDateInputValue(initialValue) && + timeValue === toTimeInputValue(initialValue); + const scheduledAt = isUnchanged ? initialValue : fromInputValues(dateValue, timeValue); + + // a failure describes the time it was for, not a newly picked one + const changeField = (setValue: (value: string) => void) => (value: string) => { + setValue(value); + setStatus((current) => (current === 'failed' ? 'idle' : current)); + setSubmitError(undefined); + }; const timeError = scheduledAt && getScheduleTimeError(scheduledAt, bounds); const canSubmit = !!scheduledAt && !timeError && isOnline && status !== 'submitting'; @@ -226,12 +237,12 @@ export const ScheduleTimeDialog = ({ label={t('scheduledMessages.date', 'Date')} max={bounds.latest && toDateInputValue(bounds.latest)} min={toDateInputValue(bounds.earliest)} - onChange={setDateValue} + onChange={changeField(setDateValue)} value={dateValue} /> diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index c267961854..1233bec0e1 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -162,8 +162,21 @@ export const ScheduledMessageItem = ({ copy: { Icon: IconCopy, label: t('scheduledMessages.copyText', 'Copy text'), - select: () => - navigator.clipboard?.writeText(message.text ?? '').catch(() => undefined), + select: () => { + // reported, as copying may be the only way to keep the text of a message that can't be sent + const copied = navigator.clipboard + ? navigator.clipboard.writeText(message.text ?? '') + : Promise.reject(new Error('The clipboard is not available')); + copied.catch((error: unknown) => + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + error: error instanceof Error ? error : new Error(String(error)), + message: t('scheduledMessages.couldntCopyTheText', "Couldn't copy the text"), + severity: 'error', + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.copyFailed, + }), + ); + }, }, delete: { Icon: IconDelete, diff --git a/src/components/ScheduledMessages/ScheduledMessageList.tsx b/src/components/ScheduledMessages/ScheduledMessageList.tsx index ebba645fd4..7c13d7e9ca 100644 --- a/src/components/ScheduledMessages/ScheduledMessageList.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -54,7 +54,7 @@ const selectLoadState = (state: PaginatorState) => ({ hasMoreTail: state.hasMoreTail, isFirstPageLoading: state.items === undefined && !state.lastQueryError, isLoading: state.isLoading, - lastQueryFailed: !!state.lastQueryError, + lastQueryError: state.lastQueryError, }); const DefaultListLoadErrorIndicator = (props: ListLoadErrorIndicatorProps) => ( @@ -160,7 +160,7 @@ export const ScheduledMessageList = ({ hasMoreTail, isFirstPageLoading, isLoading, - lastQueryFailed, + lastQueryError, } = useStateStore(paginator.state, selectLoadState); const firstPageLoadRetry = useFirstPageLoadRetry({ firstPageLoadError, @@ -170,7 +170,10 @@ export const ScheduledMessageList = ({ }); const showsNothing = !isFirstPageLoading && !shownMessages.length; // stops at a failed page instead of retrying it - const loadsFurther = showsNothing && hasMoreTail && !lastQueryFailed; + const loadsFurther = showsNothing && hasMoreTail && !lastQueryError; + // nothing matches so far, and the page that might have was not loaded + const furtherPageLoadError = + showsNothing && hasMoreTail && lastQueryError ? lastQueryError : undefined; useEffect(() => { if (loadsFurther && !isLoading) view.toTail(); @@ -188,6 +191,15 @@ export const ScheduledMessageList = ({ } if (isFirstPageLoading) return ; if (loadsFurther) return ; + if (furtherPageLoadError) { + return ( + + ); + } if (showsNothing) { // some are scheduled, but the filter accepts none of them return scheduledMessages.length ? ( diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx index 84000d223e..34ce615054 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -10,7 +10,7 @@ import { within, } from '@testing-library/react'; import { fromPartial } from '@total-typescript/shoehorn'; -import { ScheduledMessageErrorReason } from 'stream-chat'; +import { CORE_NOTIFICATION_TYPE, ScheduledMessageErrorReason } from 'stream-chat'; import type { Channel as ChannelType, ScheduledMessageResponse, @@ -390,6 +390,7 @@ describe('ScheduleMessageButton', () => { const error = new Error('failed'); client.notifications.addError({ message: 'Failed to schedule the message', + options: { type: CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed }, origin: { context: { composer: messageComposer }, emitter: 'MessageComposer' }, }); return Promise.resolve({ error, status: 'failed' }); @@ -404,6 +405,27 @@ describe('ScheduleMessageButton', () => { expect(getNotifications(client)).toEqual([]); }); + it("keeps the composer's other notifications raised meanwhile", async () => { + const { channel, client } = await renderComposer(); + const { messageComposer } = channel; + mockSchedule(channel).mockImplementation(() => { + client.notifications.addError({ + message: 'Failed to upload the file', + options: { type: CORE_NOTIFICATION_TYPE.attachmentUploadFailed }, + origin: { context: { composer: messageComposer }, emitter: 'MessageComposer' }, + }); + return Promise.resolve({ error: new Error('failed'), status: 'failed' }); + }); + + const dialog = await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + await within(dialog).findByRole('alert'); + expect(getNotifications(client)).toEqual([ + expect.objectContaining({ message: 'Failed to upload the file' }), + ]); + }); + it.each(['blocked', 'nothing-to-send'] as const)( 'keeps the dialog open when the message is %s', async (status) => { diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index fbe51ab5d7..6268e283d5 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -34,7 +34,9 @@ import { } from '../../../mock-builders'; import { getChannelByCid, SCHEDULED_MESSAGE_NOTIFICATION_TYPE } from '../utils'; import { ScheduledMessageList } from '../ScheduledMessageList'; -import type { EditScheduledMessage } from '../types'; +import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; + +type EditScheduledMessage = NonNullable; const cid = 'messaging:general'; @@ -345,6 +347,42 @@ describe('ScheduledMessageActions', () => { expect(getNotificationTypes(client)).toEqual([]); }); + it('clears a reschedule failure once another time is picked', async () => { + const { client } = await renderActions(); + vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( + notFoundError, + ); + + await selectAction('reschedule'); + await screen.findByTestId('schedule-message-dialog'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + expect(await screen.findByText('Already sent')).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); + + expect(screen.queryByText('Already sent')).not.toBeInTheDocument(); + }); + + it('saves the exact send time when neither field changes', async () => { + const sendTime = new Date(2026, 9, 29, 9, 0, 45, 500); + const scheduledMessage = generateScheduledMessage({ + cid, + scheduled_at: convertDateToTimestamp(sendTime), + }); + const { client } = await renderActions({ scheduledMessage }); + const updateScheduledMessage = vi + .spyOn(getChannel(client), 'updateScheduledMessage') + .mockResolvedValue(scheduledMessage); + + await selectAction('reschedule'); + await screen.findByTestId('schedule-message-dialog'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { + scheduled_at: sendTime, + }); + }); + it('reports a reschedule failure without a specific reason generically', async () => { const { client } = await renderActions(); vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( @@ -395,6 +433,29 @@ describe('ScheduledMessageActions', () => { expect(writeText).toHaveBeenCalledWith('Launch moved to Monday'); }); + it('reports a copy that fails', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }); + const { client } = await renderActions({ + scheduledMessage: generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + message: { custom: {}, text: 'Launch moved to Monday' }, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + }); + + await selectAction('copy'); + + await waitFor(() => + expect(getNotificationTypes(client)).toEqual([ + SCHEDULED_MESSAGE_NOTIFICATION_TYPE.copyFailed, + ]), + ); + }); + it('has no accessibility violations with the menu open', async () => { const { container } = await renderActions({ onEdit: vi.fn() }); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx index f3cbe216eb..8aaeedbfcf 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -34,7 +34,9 @@ import { useScheduledMessagesSearch } from '../hooks'; import { getChannelByCid } from '../utils'; import type { ScheduledMessageListProps } from '../ScheduledMessageList'; import { ScheduledMessageList } from '../ScheduledMessageList'; -import type { EditScheduledMessage, ScheduledMessageItemProps } from '../types'; +import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; + +type EditScheduledMessage = NonNullable; const cid = 'messaging:general'; @@ -297,7 +299,7 @@ describe('ScheduledMessageList', () => { expect(query).toHaveBeenCalledTimes(1); }); - it('stops loading further pages when one fails', async () => { + it('stops at a further page that fails, and offers to load it again', async () => { const { client } = await renderList({ scheduledMessages: [ generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), @@ -310,8 +312,19 @@ describe('ScheduledMessageList', () => { setNextCursor(client); - expect(await screen.findByText('No messages found')).toBeInTheDocument(); + const retry = await screen.findByRole('button', { name: 'Try again' }); + expect(screen.queryByText('No messages found')).not.toBeInTheDocument(); expect(query).toHaveBeenCalledTimes(1); + + query.mockResolvedValue({ + duration: '', + scheduled_messages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Friday demo' } }), + ], + } as never); + await act(() => fireEvent.click(retry)); + + expect(await screen.findByText('Friday demo')).toBeInTheDocument(); }); // a list-state key overridden for the channel list (`EmptyListIndicator` takes no props) must not diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts index a350254976..5f36e46116 100644 --- a/src/components/ScheduledMessages/__tests__/utils.test.ts +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -64,6 +64,15 @@ describe('scheduled message utils', () => { at(28, 11), ); }); + + it('picks the first whole minute allowed when the next full hour is too late', () => { + expect( + getDefaultScheduledAt({ + earliest: new Date(2026, 9, 28, 10, 25, 30), + latest: new Date(2026, 9, 28, 10, 50), + }), + ).toEqual(new Date(2026, 9, 28, 10, 26)); + }); }); describe('presets', () => { diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 5a50b05bb2..439ecf859b 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -25,6 +25,7 @@ const AFTERNOON_HOUR = 13; /** Notifications the UI emits; the composer's own come from `CORE_NOTIFICATION_TYPE`. */ export const SCHEDULED_MESSAGE_NOTIFICATION_TYPE = { + copyFailed: 'browser:scheduled-message:copy:failed', deleteFailed: 'api:scheduled-message:delete:failed', sendNowFailed: 'api:scheduled-message:send-now:failed', sendNowSucceeded: 'api:scheduled-message:send-now:success', @@ -98,11 +99,19 @@ export const getScheduleTimeError = ( return undefined; }; -/** The next full hour after the earliest allowed time. */ -export const getDefaultScheduledAt = ({ earliest }: ScheduleTimeBounds) => { - const scheduledAt = new Date(earliest); - scheduledAt.setHours(scheduledAt.getHours() + 1, 0, 0, 0); - return scheduledAt; +/** + * The next full hour after the earliest allowed time, or, when that is past the latest one, the + * first whole minute allowed (the fields pick minutes). + */ +export const getDefaultScheduledAt = ({ earliest, latest }: ScheduleTimeBounds) => { + const nextFullHour = new Date(earliest); + nextFullHour.setHours(nextFullHour.getHours() + 1, 0, 0, 0); + if (!latest || nextFullHour <= latest) return nextFullHour; + const firstWholeMinute = new Date(earliest); + if (firstWholeMinute.getSeconds() || firstWholeMinute.getMilliseconds()) { + firstWholeMinute.setMinutes(firstWholeMinute.getMinutes() + 1, 0, 0); + } + return firstWholeMinute; }; const atLocalHour = (date: Date, dayOffset: number, hour: number) => { diff --git a/src/i18n/__tests__/catalog.fixture.json b/src/i18n/__tests__/catalog.fixture.json index 32e6780b74..42bc14aa35 100644 --- a/src/i18n/__tests__/catalog.fixture.json +++ b/src/i18n/__tests__/catalog.fixture.json @@ -611,6 +611,7 @@ "scheduledMessages.chooseAnEarlierTime": "Choose an earlier time", "scheduledMessages.clickTheArrowNextToTheSendButton": "Click the arrow next to the send button in a channel to schedule a message.", "scheduledMessages.copyText": "Copy text", + "scheduledMessages.couldntCopyTheText": "Couldn't copy the text", "scheduledMessages.couldntDeleteTheScheduledMessageTryAgain": "Couldn't delete the scheduled message. Try again", "scheduledMessages.couldntLoadScheduledMessages": "Couldn't load scheduled messages", "scheduledMessages.couldntRescheduleTheMessageTryAgain": "Couldn't reschedule the message. Try again", diff --git a/src/i18n/keys.ts b/src/i18n/keys.ts index 59e9727d20..0e9b35f40a 100644 --- a/src/i18n/keys.ts +++ b/src/i18n/keys.ts @@ -622,6 +622,7 @@ export type TranslationCatalog = { 'scheduledMessages.chooseAnEarlierTime': 'Choose an earlier time'; 'scheduledMessages.clickTheArrowNextToTheSendButton': 'Click the arrow next to the send button in a channel to schedule a message.'; 'scheduledMessages.copyText': 'Copy text'; + 'scheduledMessages.couldntCopyTheText': "Couldn't copy the text"; 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain': "Couldn't delete the scheduled message. Try again"; 'scheduledMessages.couldntLoadScheduledMessages': "Couldn't load scheduled messages"; 'scheduledMessages.couldntRescheduleTheMessageTryAgain': "Couldn't reschedule the message. Try again"; From 826dd6fea4f98a70cbe2eff710d79eb4bb3700f3 Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 11:05:14 +0100 Subject: [PATCH 09/35] fix(examples): guard the freeze switch and detach a poll from a failed schedule - The freeze switch sends one request at a time and, on failure, shows the channel's last confirmed state. - Closing the time picker after a failed poll schedule detaches the poll that attempt created, so a later send cannot carry it. Co-Authored-By: Claude Opus 5.5 --- .../src/ChatLayout/ChannelFreezeAction.tsx | 10 +++++++- ...ConfigurablePollCreationDialogControls.tsx | 24 +++++++++++++++---- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx index 536b015c4a..96dd6d5475 100644 --- a/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx +++ b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx @@ -38,6 +38,8 @@ const ChannelFreezeAction = () => { const { t } = useTranslationContext(); const { canFreeze } = useStateStore(channel.state, selectCanFreeze); const [frozen, setFrozen] = useState(!!channel.data?.frozen); + // one request at a time, so failures cannot roll the switch back out of order + const [isUpdating, setIsUpdating] = useState(false); // follows a freeze made elsewhere, such as in the dashboard useEffect(() => { @@ -58,12 +60,15 @@ const ChannelFreezeAction = () => { if (!canFreeze) return null; const toggleFrozen = async () => { + if (isUpdating) return; const nextFrozen = !frozen; + setIsUpdating(true); setFrozen(nextFrozen); try { await channel.updatePartial({ set: { frozen: nextFrozen } }); } catch (error) { - setFrozen(!nextFrozen); + // back to what the channel last confirmed + setFrozen(!!channel.data?.frozen); addNotification({ context: { channel }, emitter: 'ChannelFreezeAction', @@ -80,6 +85,8 @@ const ChannelFreezeAction = () => { severity: 'error', type: 'api:channel:freeze:failed', }); + } finally { + setIsUpdating(false); } }; @@ -91,6 +98,7 @@ const ChannelFreezeAction = () => { 'aria-pressed': frozen, className: 'str-chat__form__switch-field str-chat__channel-management-view-action', + disabled: isUpdating, onClick: toggleFrozen, }} title={t(asDynamicKey('viteExample.channelFreeze.title'), 'Freeze channel')} diff --git a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx index e5425e1812..26258f266e 100644 --- a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx +++ b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; import { dateToNs, type LocalMessage, toScheduledMessagePreview } from 'stream-chat'; import { @@ -57,6 +57,8 @@ const AttachPollControls = ({ close }: PollCreationDialogControlsProps) => { const canSchedule = useCanScheduleMessage(); const [isPickingTime, setIsPickingTime] = useState(false); const previewMessage = usePollMessagePreview(); + // the poll a failed schedule created, kept for a retry; a poll attached before is not it + const pollCreatedForScheduleRef = useRef(null); // As in the default controls: close and focus the composer synchronously, so focus does not // blip through the attachment selector's trigger. @@ -68,16 +70,30 @@ const AttachPollControls = ({ close }: PollCreationDialogControlsProps) => { // rejects to keep the time dialog open, which then says the scheduling failed const schedulePoll = async (scheduledAt: Date) => { // a poll made by an earlier, failed attempt is reused - if (!messageComposer.pollId) await messageComposer.createPoll(); + if (!messageComposer.pollId) { + await messageComposer.createPoll(); + pollCreatedForScheduleRef.current = messageComposer.pollId; + } if (!messageComposer.pollId) throw new Error('The poll was not created'); const { error, status } = await messageComposer.schedule(scheduledAt); if (status !== 'scheduled' && status !== 'sent') { throw error ?? new Error(`The poll was not scheduled: ${status}`); } + pollCreatedForScheduleRef.current = null; setIsPickingTime(false); closeAndFocusComposer(); }; + // giving up on a failed schedule detaches the poll it created, which the user never attached + const closeTimePicker = () => { + const createdPollId = pollCreatedForScheduleRef.current; + pollCreatedForScheduleRef.current = null; + if (createdPollId && messageComposer.pollId === createdPollId) { + messageComposer.state.partialNext({ pollId: null }); + } + setIsPickingTime(false); + }; + return ( <> @@ -127,13 +143,13 @@ const AttachPollControls = ({ close }: PollCreationDialogControlsProps) => { setIsPickingTime(false)} + onClose={closeTimePicker} open={isPickingTime} > {isPickingTime && ( setIsPickingTime(false)} + close={closeTimePicker} errorMessage={t( asDynamicKey('viteExample.pollCreationDialog.schedulePollFailed.text'), "Couldn't schedule the poll. Try again", From 91c33b29c2798737bc4b0df9934544eec77acf66 Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 11:05:18 +0100 Subject: [PATCH 10/35] docs: restore master's guidance for showing header content beside the list The branch had reverted the migration guide and breaking-changes entry to an older per-list example. The scheduled-message formatter keys stay listed. Co-Authored-By: Claude Opus 5.5 --- ai-docs/ai-migration-v14-v15.md | 25 ++++++++++++------------- ai-docs/v15-breaking-changes.md | 4 ++-- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/ai-docs/ai-migration-v14-v15.md b/ai-docs/ai-migration-v14-v15.md index 52892e0967..767a1b71de 100644 --- a/ai-docs/ai-migration-v14-v15.md +++ b/ai-docs/ai-migration-v14-v15.md @@ -1692,7 +1692,12 @@ Where you pass the props depends on who renders the header: Both headers are exported. -To keep the v14 behavior of showing the content only next to an open channel or thread (a sidebar toggle, for example), make the content return `null` otherwise: read `openChannels` / `openThreads` from `useWorkspaceNavigation()`. `ChatView` (or your own `WorkspaceNavigationProvider`, [section 4](#4-selecting-channels-and-opening-threads-workspace-navigation)) fills these lists; without one they stay empty, so gate on your own selection state instead. +To keep showing the content only while something is open beside the list (a sidebar toggle, for example), make it return `null` otherwise. Read the workspace from `useWorkspaceNavigation()`: + +- `openChannels` / `openThreads` list the channels and threads that the workspace's panels were opened with. Something opened over another item in the same panel (stacked) is not in them. In a workspace whose panels open with channels and threads only, a stacked item always sits over one that is in the lists, so "something is open" is either list being non-empty; `openThreads` alone misses a thread stacked over a channel. +- A panel opened with another kind, such as a `userProfile` panel, is in neither list, even with a channel stacked over it. If your layout opens such panels, check the layout instead: `useLayoutViewState()` from `stream-chat-react/slot-layout` returns each slot's binding (`slotBindings`) and stacked layers (`slotLayers`). +- To ask whether a given channel or thread is on screen, use `isChannelActive(cid)` / `isThreadActive(threadId)`, which follow what each panel shows. +- `ChatView` (or your own `WorkspaceNavigationProvider`, [section 4](#4-selecting-channels-and-opening-threads-workspace-navigation)) fills all of these. Without one the lists stay empty, so gate on your own selection state instead. ```tsx // v14 @@ -1710,24 +1715,18 @@ import { // `SidebarToggle` stands for a control of your own. const SidebarToggle = () => ; -// Shown only while a channel is open, as in v14. -const SidebarToggleWhileChannelOpen = () => { - const { openChannels } = useWorkspaceNavigation(); - return openChannels.length > 0 ? : null; -}; - -// Shown only while a thread is open, as in v14. -const SidebarToggleWhileThreadOpen = () => { - const { openThreads } = useWorkspaceNavigation(); - return openThreads.length > 0 ? : null; +// Shown only while a channel or thread is open beside the list. +const SidebarToggleWhileContentOpen = () => { + const { openChannels, openThreads } = useWorkspaceNavigation(); + return openChannels.length > 0 || openThreads.length > 0 ? : null; }; const ChannelListHeaderWithToggle = () => ( - + ); const ThreadListHeaderWithToggle = () => ( - + ); // Declared once, so WithComponents gets the same object on every render. diff --git a/ai-docs/v15-breaking-changes.md b/ai-docs/v15-breaking-changes.md index 5ffe36ef95..b2203893a9 100644 --- a/ai-docs/v15-breaking-changes.md +++ b/ai-docs/v15-breaking-changes.md @@ -2315,12 +2315,12 @@ const CustomThreadHeader = () => { - `ChannelListHeader` and `ThreadListHeader` take `StartContent` (before the title) and `EndContent` (after the title), as `ChannelHeader` / `ThreadHeader` do. Neither has a default. Types: `ChannelListHeaderProps`, `ThreadListHeaderProps`. - where the SDK renders the header, the props go through the header's override key: register a component that renders the default header with them. `ChannelListHeader` is read by `ChannelNavigation`; `ThreadListHeader` is a new key, read by `ThreadList`. `ThreadListHeader` is now exported. - where the app renders the header itself (for example `ChannelListHeader` above a standalone `ChannelList`), it passes the props directly; the override key does not reach that header. - - to keep the v14 gate, read `useWorkspaceNavigation().openChannels` / `.openThreads` in the content component and return `null` while it is empty. `ChatView` or an app's own `WorkspaceNavigationProvider` fills these lists; without one they stay empty, so an app without either gates on its own selection state. + - to show the content only while something is open beside the list, read `useWorkspaceNavigation()` in the content component and return `null` while both `openChannels` and `openThreads` are empty. The lists hold the channels and threads the workspace's panels were opened with: an item stacked over another one in a panel is not in them. Where panels open with channels and threads only, a stacked item always sits over one that is, so checking one list alone misses it (a thread stacked over a channel is not in `openThreads`). A panel opened with another kind (a `userProfile` panel, even with a channel stacked over it) is in neither list; such layouts check `useLayoutViewState()` (`slotBindings`, `slotLayers`) from `stream-chat-react/slot-layout` instead. Whether a given channel or thread is on screen is `isChannelActive(cid)` / `isThreadActive(threadId)`. `ChatView` or an app's own `WorkspaceNavigationProvider` fills these; without one the lists stay empty, so an app without either gates on its own selection state. - Evidence: - `release-v14:src/components/ChannelList/ChannelListHeader.tsx:15` `{channel && HeaderEndContent && }`; `release-v14:src/components/Threads/ThreadList/ThreadListHeader.tsx:12` `{activeThread && HeaderEndContent && }`; `release-v14:src/context/ComponentContext.tsx:303` - `master:src/components/ChannelList/ChannelListHeader.tsx` and `master:src/components/Threads/ThreadList/ThreadListHeader.tsx` (`StartContent` / `EndContent` props); `master:src/components/Threads/ThreadList/ThreadList.tsx` reads `ThreadListHeader` from `useComponentContext()`; `master:src/context/ComponentContext.tsx` `ThreadListHeader?` - ticket: REACT-1449 - - examples: `examples/vite/src/ChatLayout/SwitchableChannelNavigation.tsx` passes `EndContent={SidebarToggleWhileChannelOpen}` to `ChannelListHeader`; `examples/vite/src/App.tsx` registers `ThreadListHeaderWithSidebarToggle` (`examples/vite/src/Sidebar/HeaderContent.tsx`) as `ThreadListHeader` + - examples: `examples/vite/src/ChatLayout/SwitchableChannelNavigation.tsx` passes `EndContent={SidebarToggleWhileContentOpen}` to `ChannelListHeader`; `examples/vite/src/App.tsx` registers `ThreadListHeaderWithSidebarToggle` (`examples/vite/src/Sidebar/HeaderContent.tsx`) as `ThreadListHeader` - Docs impact: - `03-ui/03-components/01-channel-list-ui.md`, `03-ui/03-components/08-thread-list-ui.md`, `03-ui/03-components/12-overriding-components.md`, `06-component-reference/02-channel/04-componentcontext.md`, `06-component-reference/07-thread-list/01-threadlist.md`, `05-ui-cookbooks/10-layout/04-collapsible-sidebar.md`, `05-ui-cookbooks/03-search/03-mentions-inbox.md`, `08-release-guides/01-upgrade-to-v15.md` - Example needed: yes (the guide section has one) From f8e05e5dee89ae0ebb68dcb5936ae85ada1a63af Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 11:12:25 +0100 Subject: [PATCH 11/35] fix(ScheduledMessageList): load on past a page that adds nothing to show A page whose messages the filter rejects changes nothing on screen, so no scroll or resize asks for the next one, and later matches stayed out of reach whenever some were already shown. The list now loads the next page itself after such a page, until one shows something or none is left. Co-Authored-By: Claude Opus 5.5 --- .../ScheduledMessageList.tsx | 23 +++++++++++- .../__tests__/ScheduledMessageList.test.tsx | 35 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/components/ScheduledMessages/ScheduledMessageList.tsx b/src/components/ScheduledMessages/ScheduledMessageList.tsx index 7c13d7e9ca..4af0fbfb8f 100644 --- a/src/components/ScheduledMessages/ScheduledMessageList.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo } from 'react'; +import React, { useEffect, useMemo, useRef } from 'react'; import type { ComponentType } from 'react'; import type { ChannelDataState, @@ -179,6 +179,27 @@ export const ScheduledMessageList = ({ if (loadsFurther && !isLoading) view.toTail(); }, [isLoading, loadsFurther, view]); + // A page that adds nothing to show changes nothing on screen, so no scroll or resize asks for + // the next one: it is loaded here instead, until a page shows something or none is left. + const shownCountAtLoadStartRef = useRef(undefined); + useEffect(() => { + if (isLoading) { + shownCountAtLoadStartRef.current ??= shownMessages.length; + return; + } + const shownCountAtLoadStart = shownCountAtLoadStartRef.current; + shownCountAtLoadStartRef.current = undefined; + if ( + shownCountAtLoadStart !== undefined && + !showsNothing && + shownMessages.length === shownCountAtLoadStart && + hasMoreTail && + !lastQueryError + ) { + view.toTail(); + } + }, [hasMoreTail, isLoading, lastQueryError, shownMessages.length, showsNothing, view]); + const renderContent = () => { if (firstPageLoadRetry.error) { return ( diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx index 8aaeedbfcf..268fbd970c 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -299,6 +299,41 @@ describe('ScheduledMessageList', () => { expect(query).toHaveBeenCalledTimes(1); }); + // a page with no matches changes nothing on screen, so no scroll or resize asks for the next one + it('loads on past a page that adds no match while some are shown', async () => { + const { client } = await renderList({ + scheduledMessages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Friday plan' } }), + ], + searchQuery: 'friday', + }); + const query = vi + .spyOn(client, 'queryScheduledMessages') + .mockResolvedValueOnce({ + duration: '', + next: 'page-3', + scheduled_messages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Lunch at noon' }, + }), + ], + } as never) + .mockResolvedValueOnce({ + duration: '', + scheduled_messages: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Friday demo' } }), + ], + } as never); + setNextCursor(client); + + // as a scroll to the bottom would + await act(() => getChannelByCid(client, cid).scheduledMessages.toTail()); + + expect(await screen.findByText('Friday demo')).toBeInTheDocument(); + expect(query).toHaveBeenCalledTimes(2); + }); + it('stops at a further page that fails, and offers to load it again', async () => { const { client } = await renderList({ scheduledMessages: [ From 7be01ac6443bb3c86ca3856f3c156e665332292a Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 12:45:44 +0100 Subject: [PATCH 12/35] refactor(ScheduledMessages): build the row actions as an action set The row's actions follow the shape of the SDK's other action sets: defaultScheduledMessageActionSet lists { Component, placement, type, isVisible } items with quick, dropdown and quick-dropdown-toggle placements, and ScheduledMessageItem takes a scheduledMessageActionSet prop to filter, reorder or extend it. - useBaseScheduledMessageActionSetFilter applies the status rules that getScheduledMessageActions held (none while sending; edit, reschedule, send now and delete while waiting; edit or copy, and delete, once failed; edit needs openInComposer). Actions of other types pass them; each item's isVisible can only hide. - Copy text is hidden without text or without navigator.clipboard. - Action components read the message and the item's handlers from useScheduledMessageActionsContext(). - Types are camelCase like the other sets: copy is copyMessageText and send_now is sendNow. While a message is being sent the row shows no action buttons, as other sets render nothing without actions. - onEdit is renamed openInComposer on the item, list, list dialog and context: it hands the message to the composer, which edits a waiting one and sends or schedules a failed one again. - getChannelByCid is replaced by splitCid(cid), used as client.channel(...splitCid(cid)), which already returns the stored channel. --- .../ConfigurableScheduledMessageItem.tsx | 6 +- .../ScheduledMessageActions.tsx | 463 ++++++++++++++++++ .../ScheduledMessageItem.tsx | 324 +++++------- .../ScheduledMessageList.tsx | 16 +- .../ScheduledMessageListDialog.tsx | 16 +- .../ScheduledMessagesBanner.tsx | 2 +- .../ScheduledMessageActionSet.test.tsx | 154 ++++++ .../ScheduledMessageActions.test.tsx | 97 +++- .../__tests__/ScheduledMessageList.test.tsx | 23 +- .../ScheduledMessagesBanner.test.tsx | 4 +- .../ScheduledMessages/__tests__/utils.test.ts | 30 -- .../hooks/useRescheduleDialogProps.ts | 9 +- src/components/ScheduledMessages/index.ts | 1 + src/components/ScheduledMessages/utils.ts | 28 +- .../ScheduledMessagesView.tsx | 2 +- 15 files changed, 870 insertions(+), 305 deletions(-) create mode 100644 src/components/ScheduledMessages/ScheduledMessageActions.tsx create mode 100644 src/components/ScheduledMessages/__tests__/ScheduledMessageActionSet.test.tsx diff --git a/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx index 4f270b5a20..3ead1359ed 100644 --- a/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx +++ b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx @@ -7,7 +7,7 @@ import { useAppSettingsSelector } from '../AppSettings'; * cancel a scheduled message opened in it, so the list offers no Edit or Retry. */ export const ConfigurableScheduledMessageItem = ({ - onEdit, + openInComposer, ...props }: ScheduledMessageItemProps) => { const { disabledPreviewSections } = useAppSettingsSelector((state) => state.composer); @@ -15,7 +15,9 @@ export const ConfigurableScheduledMessageItem = ({ return ( ); }; diff --git a/src/components/ScheduledMessages/ScheduledMessageActions.tsx b/src/components/ScheduledMessages/ScheduledMessageActions.tsx new file mode 100644 index 0000000000..e0b212515b --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageActions.tsx @@ -0,0 +1,463 @@ +import React, { + type ComponentPropsWithoutRef, + createContext, + forwardRef, + type PropsWithChildren, + useContext, + useMemo, +} from 'react'; +import { SCHEDULED_MESSAGE_FAILURE_REASON, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { + useChatContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { Button } from '../Button'; +import { ContextMenuButton, useContextMenuContext } from '../Dialog'; +import { useNotificationApi } from '../Notifications'; +import { + isFailedScheduledMessage, + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, + splitCid, +} from './utils'; + +export type DefaultScheduledMessageActionType = + | 'copyMessageText' + | 'delete' + | 'edit' + | 'reschedule' + | 'sendNow'; + +/** A dialog a scheduled message's action opens: the Delete confirmation or the time picker. */ +export type ScheduledMessageItemDialog = 'delete' | 'reschedule'; + +/** A notification an action raises: its text and type. */ +export type ScheduledMessageActionNotification = { message: string; type: string }; + +/** What the actions of one scheduled message read; provided by `ScheduledMessageItem`. */ +export type ScheduledMessageActionsContextValue = { + /** + * Whether the message's channel lets the user schedule it (or send a failed one again). Unknown + * for a channel that is not loaded, and then `true`. The default edit actions stay focusable but + * do nothing while it is `false`, described by `editUnavailableDescriptionId`. + */ + canEdit: boolean; + /** The ID of the element that says why editing is unavailable. */ + editUnavailableDescriptionId: string; + /** A request of this message's actions is running. */ + isPending: boolean; + /** Opens one of the item's dialogs. */ + openDialog: (dialog: ScheduledMessageItemDialog) => void; + /** + * Runs a request for the message, marked pending meanwhile. A failure is reported as an error + * notification, translated from the error where possible; a success only when given. + */ + runRequest: ( + request: () => Promise, + failure: ScheduledMessageActionNotification, + success?: ScheduledMessageActionNotification, + ) => Promise; + scheduledMessage: ScheduledMessageResponse; + /** Opens the message in the composer; without it no edit action is offered. */ + openInComposer?: (scheduledMessage: ScheduledMessageResponse) => void; +}; + +const ScheduledMessageActionsContext = createContext< + ScheduledMessageActionsContextValue | undefined +>(undefined); + +export const ScheduledMessageActionsContextProvider = ({ + children, + value, +}: PropsWithChildren<{ value: ScheduledMessageActionsContextValue }>) => ( + + {children} + +); + +export const useScheduledMessageActionsContext = () => { + const value = useContext(ScheduledMessageActionsContext); + if (!value) { + throw new Error( + 'useScheduledMessageActionsContext must be used within ScheduledMessageItem', + ); + } + return value; +}; + +/** What an action's `isVisible` rule is checked against. */ +export type ScheduledMessageActionVisibilityFilterParams = { + scheduledMessage: ScheduledMessageResponse; +}; + +type BaseScheduledMessageActionSetItem = { + /** + * Hides the action for a message, e.g. `copyMessageText` without a clipboard. Cannot show an + * action the base filter removes (by the message's status, or `edit` without `openInComposer`). Shown + * when omitted. + */ + isVisible?: (state: ScheduledMessageActionVisibilityFilterParams) => boolean; + type: DefaultScheduledMessageActionType | (string & {}); +}; + +/** Rendered as a button beside the actions menu's toggle. */ +export type QuickScheduledMessageActionSetItem = BaseScheduledMessageActionSetItem & { + Component: React.ComponentType; + placement: 'quick'; +}; + +/** + * Rendered inside the actions menu, so the component can close it with `closeMenu` from + * `useContextMenuContext()`. + */ +export type DropdownScheduledMessageActionSetItem = BaseScheduledMessageActionSetItem & { + Component: React.ComponentType; + placement: 'dropdown'; +}; + +/** + * The button that opens the actions menu, rendered while at least one `dropdown` item passes the + * filter. A `forwardRef` component that spreads the props it gets onto its button: the menu anchors + * to the ref and the props open it. + */ +export type QuickDropdownToggleScheduledMessageActionSetItem = { + Component: React.ForwardRefExoticComponent< + ComponentPropsWithoutRef<'button'> & React.RefAttributes + >; + placement: 'quick-dropdown-toggle'; +}; + +export type ScheduledMessageActionSetItem = + | QuickScheduledMessageActionSetItem + | DropdownScheduledMessageActionSetItem + | QuickDropdownToggleScheduledMessageActionSetItem; + +/** The built-in action types each status allows; a type of another name is not restricted. */ +const getAllowedDefaultActionTypes = ({ + failure_reason, + status, +}: ScheduledMessageResponse): DefaultScheduledMessageActionType[] => { + if (status === SCHEDULED_MESSAGE_STATUS.Sending) return []; + if (status !== SCHEDULED_MESSAGE_STATUS.Failed) { + return ['edit', 'reschedule', 'sendNow', 'delete']; + } + // a message to a deleted channel can only be copied before it goes + return failure_reason === SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted + ? ['copyMessageText', 'delete'] + : ['edit', 'delete']; +}; + +const DEFAULT_ACTION_TYPES: ReadonlySet = + new Set([ + 'copyMessageText', + 'delete', + 'edit', + 'reschedule', + 'sendNow', + ]); + +/** + * Drops the actions a scheduled message's status rules out: none while it is sending; edit, + * reschedule, send now and delete while it waits; edit and delete once it failed, or copy and + * delete once its channel was deleted. `edit` also needs `openInComposer`. An action of another type passes + * these rules. An action they allow still shows only while its own `isVisible` holds. The menu + * toggle is always kept. Reads the message from `useScheduledMessageActionsContext()`. + * + * @param scheduledMessageActionSet - Actions to filter. + * @returns The actions to show. + */ +export const useBaseScheduledMessageActionSetFilter = ( + scheduledMessageActionSet: ScheduledMessageActionSetItem[], +) => { + const { openInComposer, scheduledMessage } = useScheduledMessageActionsContext(); + const canOpenInComposer = !!openInComposer; + + return useMemo(() => { + const allowedTypes = getAllowedDefaultActionTypes(scheduledMessage); + const visibilityFilterParams: ScheduledMessageActionVisibilityFilterParams = { + scheduledMessage, + }; + + const passesBaseRule = ({ type }: { type: string }) => + !DEFAULT_ACTION_TYPES.has(type) || + (allowedTypes.includes(type as DefaultScheduledMessageActionType) && + (type !== 'edit' || canOpenInComposer)); + + return scheduledMessageActionSet.filter( + (action) => + action.placement === 'quick-dropdown-toggle' || + (passesBaseRule(action) && + (!action.isVisible || action.isVisible(visibilityFilterParams))), + ); + }, [canOpenInComposer, scheduledMessage, scheduledMessageActionSet]); +}; + +/** Keeps an unavailable edit action focusable, so the reason it is unavailable can be read. */ +const useEditActionProps = () => { + const { canEdit, editUnavailableDescriptionId, openInComposer, scheduledMessage } = + useScheduledMessageActionsContext(); + return { + edit: () => { + if (canEdit) openInComposer?.(scheduledMessage); + }, + unavailableProps: canEdit + ? undefined + : { + 'aria-describedby': editUnavailableDescriptionId, + 'aria-disabled': true as const, + }, + }; +}; + +const QuickDropdownToggle = forwardRef< + HTMLButtonElement, + ComponentPropsWithoutRef<'button'> +>(function QuickDropdownToggle(props, ref) { + const { t } = useTranslationContext(); + const { IconMore } = useComponentContextIcons(); + const { isPending } = useScheduledMessageActionsContext(); + return ( + + ); +}); + +const QuickEdit = () => { + const { t } = useTranslationContext(); + const { IconEdit } = useComponentContextIcons(); + const { isPending } = useScheduledMessageActionsContext(); + const { edit, unavailableProps } = useEditActionProps(); + return ( + + ); +}; + +const DropdownEdit = () => { + const { t } = useTranslationContext(); + const { IconEdit } = useComponentContextIcons(); + const { closeMenu } = useContextMenuContext(); + const { canEdit } = useScheduledMessageActionsContext(); + const { edit, unavailableProps } = useEditActionProps(); + return ( + { + if (!canEdit) return; + closeMenu(); + edit(); + }} + > + {t('scheduledMessages.editReschedule', 'Edit & reschedule')} + + ); +}; + +const DropdownReschedule = () => { + const { t } = useTranslationContext(); + const { IconClock } = useComponentContextIcons(); + const { closeMenu } = useContextMenuContext(); + const { openDialog } = useScheduledMessageActionsContext(); + return ( + { + closeMenu(); + openDialog('reschedule'); + }} + > + {t('scheduledMessages.reschedule', 'Reschedule')} + + ); +}; + +const DropdownSendNow = () => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const { IconSend } = useComponentContextIcons(); + const { closeMenu } = useContextMenuContext(); + const { runRequest, scheduledMessage } = useScheduledMessageActionsContext(); + return ( + { + closeMenu(); + void runRequest( + () => + client + .channel(...splitCid(scheduledMessage.cid)) + .sendScheduledMessageNow(scheduledMessage.id), + { + message: t( + 'scheduledMessages.couldntSendTheMessageTryAgain', + "Couldn't send the message. Try again", + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowFailed, + }, + { + message: t( + 'scheduledMessages.scheduledMessageSent', + 'Scheduled message sent', + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowSucceeded, + }, + ); + }} + > + {t('scheduledMessages.sendNow', 'Send now')} + + ); +}; + +const DropdownCopyMessageText = () => { + const { t } = useTranslationContext(); + const { IconCopy } = useComponentContextIcons(); + const { closeMenu } = useContextMenuContext(); + const { addNotification } = useNotificationApi(); + const { scheduledMessage } = useScheduledMessageActionsContext(); + return ( + { + closeMenu(); + // reported, as copying may be the only way to keep the text of a message that can't be sent + navigator.clipboard + .writeText(scheduledMessage.message.text ?? '') + .catch((error: unknown) => + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + error: error instanceof Error ? error : new Error(String(error)), + message: t( + 'scheduledMessages.couldntCopyTheText', + "Couldn't copy the text", + ), + severity: 'error', + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.copyFailed, + }), + ); + }} + > + {t('scheduledMessages.copyText', 'Copy text')} + + ); +}; + +const DropdownDelete = () => { + const { t } = useTranslationContext(); + const { IconDelete } = useComponentContextIcons(); + const { closeMenu } = useContextMenuContext(); + const { openDialog } = useScheduledMessageActionsContext(); + return ( + { + closeMenu(); + openDialog('delete'); + }} + variant='destructive' + > + {t('scheduledMessages.delete', 'Delete')} + + ); +}; + +export const DefaultScheduledMessageActionComponents = { + dropdown: { + CopyMessageText: DropdownCopyMessageText, + Delete: DropdownDelete, + Edit: DropdownEdit, + Reschedule: DropdownReschedule, + SendNow: DropdownSendNow, + }, + quick: { + DropdownToggle: QuickDropdownToggle, + Edit: QuickEdit, + }, +}; + +/** + * The actions `ScheduledMessageItem` renders by default. A waiting message is edited from its own + * button and the rest from the menu; a failed one is edited ("Edit & reschedule") from the menu. + * Each item's `isVisible` holds the action's own rule; the message's status is checked by + * `useBaseScheduledMessageActionSetFilter` and cannot be overridden. + */ +export const defaultScheduledMessageActionSet: ScheduledMessageActionSetItem[] = [ + { + Component: DefaultScheduledMessageActionComponents.quick.DropdownToggle, + placement: 'quick-dropdown-toggle', + }, + { + Component: DefaultScheduledMessageActionComponents.quick.Edit, + isVisible: ({ scheduledMessage }) => !isFailedScheduledMessage(scheduledMessage), + placement: 'quick', + type: 'edit', + }, + { + Component: DefaultScheduledMessageActionComponents.dropdown.Edit, + isVisible: ({ scheduledMessage }) => isFailedScheduledMessage(scheduledMessage), + placement: 'dropdown', + type: 'edit', + }, + { + Component: DefaultScheduledMessageActionComponents.dropdown.Reschedule, + placement: 'dropdown', + type: 'reschedule', + }, + { + Component: DefaultScheduledMessageActionComponents.dropdown.SendNow, + placement: 'dropdown', + type: 'sendNow', + }, + { + Component: DefaultScheduledMessageActionComponents.dropdown.CopyMessageText, + // nothing to copy, or nowhere to copy it to (an insecure page, or no Clipboard API) + isVisible: ({ scheduledMessage }) => + !!scheduledMessage.message.text && + typeof navigator !== 'undefined' && + !!navigator.clipboard, + placement: 'dropdown', + type: 'copyMessageText', + }, + { + Component: DefaultScheduledMessageActionComponents.dropdown.Delete, + placement: 'dropdown', + type: 'delete', + }, +]; diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index 1233bec0e1..94d769f6c5 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -1,5 +1,5 @@ import clsx from 'clsx'; -import React, { useRef, useState } from 'react'; +import React, { type RefObject, useCallback, useRef, useState } from 'react'; import { nsToDate, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; import type { OwnCapabilitiesState, ScheduledMessageResponse } from 'stream-chat'; @@ -16,10 +16,10 @@ import { useChannelPreviewInfo } from '../ChannelListItem/hooks/useChannelPrevie import { Alert, ContextMenu, - ContextMenuButton, useDialogIsOpen, useDialogOnNearestManager, } from '../Dialog'; +import { useSplitActionSet } from '../Chat/hooks/useSplitActionSet'; import { GlobalModal } from '../Modal'; import { useNotificationApi } from '../Notifications'; import { useStateStore } from '../../store'; @@ -31,24 +31,36 @@ import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { - getChannelByCid, - getScheduledMessageActions, + defaultScheduledMessageActionSet, + ScheduledMessageActionsContextProvider, + useBaseScheduledMessageActionSetFilter, + useScheduledMessageActionsContext, +} from './ScheduledMessageActions'; +import type { + ScheduledMessageActionsContextValue, + ScheduledMessageActionSetItem, + ScheduledMessageItemDialog, +} from './ScheduledMessageActions'; +import { isFailedScheduledMessage, SCHEDULED_MESSAGE_NOTIFICATION_TYPE, SCHEDULED_MESSAGES_EMITTER, + splitCid, translateScheduledMessageError, translateScheduledMessageFailureReason, } from './utils'; -import type { ScheduledMessageAction } from './utils'; export type ScheduledMessageItemProps = { scheduledMessage: ScheduledMessageResponse; /** Opens the message in the composer; without it the list offers no edit action. */ - onEdit?: (scheduledMessage: ScheduledMessageResponse) => void; + openInComposer?: (scheduledMessage: ScheduledMessageResponse) => void; + /** + * The message's actions, in render order. Defaults to `defaultScheduledMessageActionSet`; + * filter, reorder or extend it. Filtered by `useBaseScheduledMessageActionSetFilter`. + */ + scheduledMessageActionSet?: ScheduledMessageActionSetItem[]; }; -type OpenDialog = 'delete' | 'reschedule'; - const selectComposeCapabilities = ({ ownCapabilities }: OwnCapabilitiesState) => ({ canSchedule: !!ownCapabilities?.includes(SCHEDULE_MESSAGE_CAPABILITY), canSend: !!ownCapabilities?.includes('send-message'), @@ -56,30 +68,19 @@ const selectComposeCapabilities = ({ ownCapabilities }: OwnCapabilitiesState) => /** A scheduled message: when it is sent, where, its status and what can be done with it. */ export const ScheduledMessageItem = ({ - onEdit, + openInComposer, scheduledMessage, + scheduledMessageActionSet = defaultScheduledMessageActionSet, }: ScheduledMessageItemProps) => { const { t } = useTranslationContext(); const { client } = useChatContext(); - const { - IconClock, - IconCopy, - IconDelete, - IconEdit, - IconExclamationTriangleFill, - IconLoading, - IconMore, - IconSend, - } = useComponentContextIcons(); - const { - ContextMenu: ContextMenuComponent = ContextMenu, - Modal = GlobalModal, - ScheduleTimeDialog = DefaultScheduleTimeDialog, - } = useComponentContext(); + const { IconExclamationTriangleFill, IconLoading } = useComponentContextIcons(); + const { Modal = GlobalModal, ScheduleTimeDialog = DefaultScheduleTimeDialog } = + useComponentContext(); const { addNotification } = useNotificationApi(); const isMounted = useIsMounted(); - const { cid, failure_reason, id, message, scheduled_at, status } = scheduledMessage; + const { cid, failure_reason, id, scheduled_at, status } = scheduledMessage; // shown from a loaded channel only; an action creates the instance it needs const loadedChannel = client.channelManager.get(cid); const { displayImage, displayTitle, groupChannelDisplayInfo } = useChannelPreviewInfo({ @@ -90,7 +91,7 @@ export const ScheduledMessageItem = ({ selectComposeCapabilities, ); const editUnavailableId = useStableId(); - const getChannel = () => getChannelByCid(client, cid); + const getChannel = () => client.channel(...splitCid(cid)); const previewMessage = useScheduledMessagePreview(scheduledMessage); const rescheduleDialogProps = useRescheduleDialogProps({ previewMessage, @@ -104,33 +105,20 @@ export const ScheduledMessageItem = ({ !composeCapabilities || composeCapabilities.canSchedule || (isFailed && composeCapabilities.canSend); - const editUnavailableProps = canEdit - ? undefined - : { 'aria-describedby': editUnavailableId, 'aria-disabled': true }; - const menuId = `scheduled-message-actions-${id}`; - const { dialog: menu, dialogManager } = useDialogOnNearestManager({ id: menuId }); - const isMenuOpen = useDialogIsOpen(menuId, dialogManager?.id); - const menuButtonRef = useRef(null); - const [openDialog, setOpenDialog] = useState(); + const menuButtonRef = useRef(null); + const [openDialog, setOpenDialog] = useState(); const [isPending, setIsPending] = useState(false); - const actions = getScheduledMessageActions(scheduledMessage, !!onEdit); - // a pending message keeps "edit" as its own button, outside the menu - const hasEditButton = !isFailed && actions.includes('edit'); - const menuActions = hasEditButton - ? actions.filter((action) => action !== 'edit') - : actions; - const closeDialog = () => { setOpenDialog(undefined); requestAnimationFrame(() => menuButtonRef.current?.focus()); }; - const run = async ( - request: () => Promise, - failure: { message: string; type: string }, - success?: { message: string; type: string }, + const runRequest: ScheduledMessageActionsContextValue['runRequest'] = async ( + request, + failure, + success, ) => { setIsPending(true); try { @@ -155,71 +143,9 @@ export const ScheduledMessageItem = ({ } }; - const menuItems: Record< - ScheduledMessageAction, - { Icon: typeof IconClock; label: string; select: () => void } - > = { - copy: { - Icon: IconCopy, - label: t('scheduledMessages.copyText', 'Copy text'), - select: () => { - // reported, as copying may be the only way to keep the text of a message that can't be sent - const copied = navigator.clipboard - ? navigator.clipboard.writeText(message.text ?? '') - : Promise.reject(new Error('The clipboard is not available')); - copied.catch((error: unknown) => - addNotification({ - emitter: SCHEDULED_MESSAGES_EMITTER, - error: error instanceof Error ? error : new Error(String(error)), - message: t('scheduledMessages.couldntCopyTheText', "Couldn't copy the text"), - severity: 'error', - type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.copyFailed, - }), - ); - }, - }, - delete: { - Icon: IconDelete, - label: t('scheduledMessages.delete', 'Delete'), - select: () => setOpenDialog('delete'), - }, - edit: { - Icon: IconEdit, - label: t('scheduledMessages.editReschedule', 'Edit & reschedule'), - select: () => onEdit?.(scheduledMessage), - }, - reschedule: { - Icon: IconClock, - label: t('scheduledMessages.reschedule', 'Reschedule'), - select: () => setOpenDialog('reschedule'), - }, - send_now: { - Icon: IconSend, - label: t('scheduledMessages.sendNow', 'Send now'), - select: () => - run( - () => getChannel().sendScheduledMessageNow(id), - { - message: t( - 'scheduledMessages.couldntSendTheMessageTryAgain', - "Couldn't send the message. Try again", - ), - type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowFailed, - }, - { - message: t( - 'scheduledMessages.scheduledMessageSent', - 'Scheduled message sent', - ), - type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sendNowSucceeded, - }, - ), - }, - }; - const deleteScheduledMessage = () => { closeDialog(); - void run(() => getChannel().deleteScheduledMessage(id), { + void runRequest(() => getChannel().deleteScheduledMessage(id), { message: t( 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain', "Couldn't delete the scheduled message. Try again", @@ -243,91 +169,22 @@ export const ScheduledMessageItem = ({ time: t('timestamp.ScheduledMessageSendTime', { timestamp: sendTime }), })} -
- - {hasEditButton && ( - - )} - - {menuActions.map((action, index) => { - const { Icon, label, select } = menuItems[action]; - const isDelete = action === 'delete'; - return ( - - {/* Delete stands apart, unless it is the only action */} - {isDelete && index > 0 && ( -
- )} - { - if (action === 'edit' && !canEdit) return; - menu.close(); - select(); - }} - variant={isDelete ? 'destructive' : undefined} - > - {label} - - - ); - })} - -
+ + {!canEdit && ( {t( @@ -433,3 +290,86 @@ export const ScheduledMessageItem = ({
); }; + +/** + * The `quick` actions beside the `quick-dropdown-toggle` item and the `dropdown` actions in the menu + * it opens, with Delete set apart. Renders nothing when no quick or dropdown action passes the + * filter. + */ +const ScheduledMessageItemActions = ({ + menuButtonRef, + scheduledMessageActionSet, +}: { + menuButtonRef: RefObject; + scheduledMessageActionSet: ScheduledMessageActionSetItem[]; +}) => { + const { t } = useTranslationContext(); + const { ContextMenu: ContextMenuComponent = ContextMenu } = useComponentContext(); + const { scheduledMessage } = useScheduledMessageActionsContext(); + const actions = useBaseScheduledMessageActionSetFilter(scheduledMessageActionSet); + const { dropdownActionSet, quickActionSet, quickDropdownToggleAction } = + useSplitActionSet(actions); + const menuId = `scheduled-message-actions-${scheduledMessage.id}`; + const { dialog: menu, dialogManager } = useDialogOnNearestManager({ id: menuId }); + const isMenuOpen = useDialogIsOpen(menuId, dialogManager?.id); + const [referenceElement, setReferenceElement] = useState( + null, + ); + // the item returns focus to the toggle when one of its dialogs closes + const setToggle = useCallback( + (element: HTMLButtonElement | null) => { + menuButtonRef.current = element; + setReferenceElement(element); + }, + [menuButtonRef], + ); + const hasMenu = !!quickDropdownToggleAction && dropdownActionSet.length > 0; + + if (!quickActionSet.length && !hasMenu) return null; + + return ( +
+ {hasMenu && ( + menu.toggle()} + ref={setToggle} + /> + )} + {quickActionSet.map(({ Component, type }) => ( + + ))} + {hasMenu && ( + + {dropdownActionSet.map(({ Component, type }, index) => ( + + {/* Delete stands apart, unless it is the only action */} + {type === 'delete' && index > 0 && ( +
+ )} + + + ))} + + )} +
+ ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageList.tsx b/src/components/ScheduledMessages/ScheduledMessageList.tsx index 4af0fbfb8f..01019dec1b 100644 --- a/src/components/ScheduledMessages/ScheduledMessageList.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -28,9 +28,12 @@ import { SCHEDULE_MESSAGE_CAPABILITY, useScheduledMessages } from './hooks'; import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; import { ScheduledMessageItem as DefaultScheduledMessageItem } from './ScheduledMessageItem'; import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; -import { getChannelByCid } from './utils'; +import { splitCid } from './utils'; -export type ScheduledMessageListProps = Pick & { +export type ScheduledMessageListProps = Pick< + ScheduledMessageItemProps, + 'openInComposer' +> & { /** * What to list: `channel.scheduledMessages`, `thread.scheduledMessages`, or a view of a list * registered with `client.scheduledMessagePaginators`. Further pages load on scroll. When its @@ -112,7 +115,7 @@ const selectScheduling = ({ const SchedulingUnavailableNotice = ({ cid }: { cid: string }) => { const { t } = useTranslationContext(); const { client } = useChatContext(); - const channel = getChannelByCid(client, cid); + const channel = client.channel(...splitCid(cid)); const { canSchedule, frozen } = useStateStore(channel.state, selectScheduling); if (canSchedule) return null; return ( @@ -144,7 +147,7 @@ export const ScheduledMessageList = ({ FirstPageLoadingIndicator = DefaultFirstPageLoadingIndicator, ListLoadErrorIndicator = DefaultListLoadErrorIndicator, LoadingNextPageIndicator = DefaultLoadingNextPageIndicator, - onEdit, + openInComposer, scheduledMessages: view, }: ScheduledMessageListProps) => { const { ScheduledMessageItem = DefaultScheduledMessageItem } = useComponentContext(); @@ -241,7 +244,10 @@ export const ScheduledMessageList = ({ className='str-chat__scheduled-message-list__item' key={scheduledMessage.id} > - + ))} diff --git a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx index b13e26d0bc..f67b39f5fc 100644 --- a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx @@ -21,7 +21,7 @@ const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); export type ScheduledMessageListDialogProps = Pick< ScheduledMessageItemProps, - 'onEdit' + 'openInComposer' > & { close: () => void; open: boolean; @@ -31,9 +31,9 @@ export type ScheduledMessageListDialogProps = Pick< /** The dialog's content, mounted only while it is open: the search starts empty each time. */ const ScheduledMessageListDialogBody = ({ - onEdit, + openInComposer, scheduledMessages: view, -}: Pick) => { +}: Pick) => { const { t } = useTranslationContext(); const { IconSearch, IconXCircle } = useComponentContextIcons(); const { ScheduledMessageList = DefaultScheduledMessageList } = useComponentContext(); @@ -76,7 +76,11 @@ const ScheduledMessageListDialogBody = ({ value={searchQuery} /> )} - + ); }; @@ -88,8 +92,8 @@ const ScheduledMessageListDialogBody = ({ */ export const ScheduledMessageListDialog = ({ close, - onEdit, open, + openInComposer, scheduledMessages, }: ScheduledMessageListDialogProps) => { const { t } = useTranslationContext(); @@ -116,7 +120,7 @@ export const ScheduledMessageListDialog = ({ } /> diff --git a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx index 36bbe7df3c..d831705a20 100644 --- a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx +++ b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx @@ -141,8 +141,8 @@ export const ScheduledMessagesBanner = () => { )} diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActionSet.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActionSet.test.tsx new file mode 100644 index 0000000000..5be8ce4abe --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActionSet.test.tsx @@ -0,0 +1,154 @@ +import React, { type PropsWithChildren } from 'react'; +import { renderHook } from '@testing-library/react'; +import { SCHEDULED_MESSAGE_FAILURE_REASON } from 'stream-chat'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { generateScheduledMessage } from '../../../mock-builders'; +import { + defaultScheduledMessageActionSet, + ScheduledMessageActionsContextProvider, + useBaseScheduledMessageActionSetFilter, +} from '../ScheduledMessageActions'; +import type { ScheduledMessageActionSetItem } from '../ScheduledMessageActions'; + +const Noop = () => null; + +const filterActions = ({ + actionSet = defaultScheduledMessageActionSet, + canOpenInComposer = true, + scheduledMessage = generateScheduledMessage({ message: { custom: {}, text: 'Hi' } }), +}: { + actionSet?: ScheduledMessageActionSetItem[]; + canOpenInComposer?: boolean; + scheduledMessage?: ScheduledMessageResponse; +} = {}) => { + const wrapper = ({ children }: PropsWithChildren) => ( + + {children} + + ); + const { result } = renderHook(() => useBaseScheduledMessageActionSetFilter(actionSet), { + wrapper, + }); + return result.current.map((action) => + action.placement === 'quick-dropdown-toggle' + ? 'toggle' + : `${action.placement}:${action.type}`, + ); +}; + +describe('useBaseScheduledMessageActionSetFilter', () => { + beforeEach(() => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn() }, + }); + }); + + it('offers a waiting message its own edit button and reschedule, send now and delete', () => { + expect(filterActions()).toEqual([ + 'toggle', + 'quick:edit', + 'dropdown:reschedule', + 'dropdown:sendNow', + 'dropdown:delete', + ]); + }); + + it('offers no edit without openInComposer', () => { + expect(filterActions({ canOpenInComposer: false })).not.toContain('quick:edit'); + }); + + it('offers nothing while the message is being sent', () => { + expect( + filterActions({ + scheduledMessage: generateScheduledMessage({ status: 'sending' }), + }), + ).toEqual(['toggle']); + }); + + it('offers a failed message edit and delete from the menu', () => { + expect( + filterActions({ + scheduledMessage: generateScheduledMessage({ + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + status: 'failed', + }), + }), + ).toEqual(['toggle', 'dropdown:edit', 'dropdown:delete']); + }); + + it('offers copy and delete for a message whose channel was deleted', () => { + const failed = generateScheduledMessage({ + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + message: { custom: {}, text: 'Launch moved' }, + status: 'failed', + }); + + expect(filterActions({ scheduledMessage: failed })).toEqual([ + 'toggle', + 'dropdown:copyMessageText', + 'dropdown:delete', + ]); + }); + + it('hides copy without a clipboard or without text', () => { + const failed = (text?: string) => + generateScheduledMessage({ + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + message: { custom: {}, text }, + status: 'failed', + }); + + expect(filterActions({ scheduledMessage: failed() })).not.toContain( + 'dropdown:copyMessageText', + ); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: undefined, + }); + expect(filterActions({ scheduledMessage: failed('Launch moved') })).not.toContain( + 'dropdown:copyMessageText', + ); + }); + + it('lets an action of another type through, subject to its own isVisible', () => { + const actionSet: ScheduledMessageActionSetItem[] = [ + ...defaultScheduledMessageActionSet, + { Component: Noop, placement: 'dropdown', type: 'copyLink' }, + { Component: Noop, isVisible: () => false, placement: 'dropdown', type: 'hidden' }, + ]; + + expect( + filterActions({ + actionSet, + scheduledMessage: generateScheduledMessage({ status: 'sending' }), + }), + ).toEqual(['toggle', 'dropdown:copyLink']); + }); + + it('cannot show an action the status rules out', () => { + const actionSet = defaultScheduledMessageActionSet.map((action) => + action.placement !== 'quick-dropdown-toggle' && action.type === 'sendNow' + ? { ...action, isVisible: () => true } + : action, + ); + + expect( + filterActions({ + actionSet, + scheduledMessage: generateScheduledMessage({ status: 'sending' }), + }), + ).toEqual(['toggle']); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index 6268e283d5..01211f4d3a 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -32,20 +32,27 @@ import { hydrateScheduledMessages, mockChatContext, } from '../../../mock-builders'; -import { getChannelByCid, SCHEDULED_MESSAGE_NOTIFICATION_TYPE } from '../utils'; +import { SCHEDULED_MESSAGE_NOTIFICATION_TYPE, splitCid } from '../utils'; import { ScheduledMessageList } from '../ScheduledMessageList'; +import { ScheduledMessageItem } from '../ScheduledMessageItem'; import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; +import { defaultScheduledMessageActionSet } from '../ScheduledMessageActions'; +import type { ScheduledMessageActionSetItem } from '../ScheduledMessageActions'; -type EditScheduledMessage = NonNullable; +type OpenInComposer = NonNullable; const cid = 'messaging:general'; -const ChannelScheduledMessageList = ({ onEdit }: { onEdit?: EditScheduledMessage }) => { +const ChannelScheduledMessageList = ({ + openInComposer, +}: { + openInComposer?: OpenInComposer; +}) => { const { client } = useChatContext(); return ( ); }; @@ -65,13 +72,13 @@ const notFoundError = new StreamAPIError('not found', { type RenderActionsOptions = { components?: Parameters[0]['overrides']; - onEdit?: EditScheduledMessage; + openInComposer?: OpenInComposer; scheduledMessage?: ScheduledMessageResponse; }; const renderActions = async ({ components = {}, - onEdit, + openInComposer, scheduledMessage = generateScheduledMessage({ cid, message: { custom: {}, text: 'Launch moved to Monday' }, @@ -91,7 +98,7 @@ const renderActions = async ({ - + @@ -135,7 +142,7 @@ describe('ScheduledMessageActions', () => { }); it('offers an Edit button and Reschedule, Send now and Delete for a scheduled message', async () => { - await renderActions({ onEdit: vi.fn() }); + await renderActions({ openInComposer: vi.fn() }); await openActionsMenu(); @@ -161,8 +168,8 @@ describe('ScheduledMessageActions', () => { ); it('disables Edit, keeping it focusable and saying why', async () => { - const onEdit = vi.fn(); - const { client } = await renderActions({ onEdit }); + const openInComposer = vi.fn(); + const { client } = await renderActions({ openInComposer }); removeComposeCapabilities(client); const edit = screen.getByTestId('scheduled-message-edit-button'); @@ -173,13 +180,13 @@ describe('ScheduledMessageActions', () => { expect(edit).toHaveAccessibleDescription( "Unavailable: you can't send messages in this channel", ); - expect(onEdit).not.toHaveBeenCalled(); + expect(openInComposer).not.toHaveBeenCalled(); }); it('disables Edit & reschedule of a failed message', async () => { - const onEdit = vi.fn(); + const openInComposer = vi.fn(); const { client } = await renderActions({ - onEdit, + openInComposer, scheduledMessage: generateScheduledMessage({ cid, failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, @@ -195,13 +202,13 @@ describe('ScheduledMessageActions', () => { expect(editAndReschedule).toHaveAccessibleDescription( "Unavailable: you can't send messages in this channel", ); - expect(onEdit).not.toHaveBeenCalled(); + expect(openInComposer).not.toHaveBeenCalled(); // the menu stays open on the unavailable item expect(screen.getByTestId('scheduled-message-actions-menu')).toBeInTheDocument(); }); }); - it('disables the actions while the message is being sent', async () => { + it('offers no actions while the message is being sent', async () => { await renderActions({ scheduledMessage: generateScheduledMessage({ cid, @@ -209,15 +216,23 @@ describe('ScheduledMessageActions', () => { }), }); - expect(screen.getByTestId('scheduled-message-actions-button')).toBeDisabled(); + expect( + screen.queryByTestId('scheduled-message-actions-button'), + ).not.toBeInTheDocument(); + expect(screen.queryByTestId('scheduled-message-edit-button')).not.toBeInTheDocument(); }); it('offers Copy and Delete for a message in a deleted channel', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn() }, + }); await renderActions({ - onEdit: vi.fn(), + openInComposer: vi.fn(), scheduledMessage: generateScheduledMessage({ cid, failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, + message: { custom: {}, text: 'Launch moved to Monday' }, status: SCHEDULED_MESSAGE_STATUS.Failed, }), }); @@ -230,12 +245,12 @@ describe('ScheduledMessageActions', () => { }); it('hands the scheduled message to the edit handler', async () => { - const onEdit = vi.fn(); - const { scheduledMessage } = await renderActions({ onEdit }); + const openInComposer = vi.fn(); + const { scheduledMessage } = await renderActions({ openInComposer }); await act(() => fireEvent.click(screen.getByTestId('scheduled-message-edit-button'))); - expect(onEdit).toHaveBeenCalledWith(scheduledMessage); + expect(openInComposer).toHaveBeenCalledWith(scheduledMessage); }); it('sends the message now and confirms it', async () => { @@ -244,7 +259,7 @@ describe('ScheduledMessageActions', () => { .spyOn(getChannel(client), 'sendScheduledMessageNow') .mockResolvedValue(scheduledMessage); - await selectAction('send_now'); + await selectAction('sendNow'); expect(sendNow).toHaveBeenCalledWith(scheduledMessage.id); await waitFor(() => @@ -260,7 +275,7 @@ describe('ScheduledMessageActions', () => { notFoundError, ); - await selectAction('send_now'); + await selectAction('sendNow'); await waitFor(() => expect(client.notifications.store.getLatestValue().notifications).toEqual([ @@ -428,7 +443,7 @@ describe('ScheduledMessageActions', () => { }), }); - await selectAction('copy'); + await selectAction('copyMessageText'); expect(writeText).toHaveBeenCalledWith('Launch moved to Monday'); }); @@ -447,7 +462,7 @@ describe('ScheduledMessageActions', () => { }), }); - await selectAction('copy'); + await selectAction('copyMessageText'); await waitFor(() => expect(getNotificationTypes(client)).toEqual([ @@ -456,8 +471,38 @@ describe('ScheduledMessageActions', () => { ); }); + it('takes its actions from scheduledMessageActionSet', async () => { + const copyLink = vi.fn(); + const CopyLink = () => ( + + ); + const scheduledMessageActionSet: ScheduledMessageActionSetItem[] = [ + ...defaultScheduledMessageActionSet.filter( + (action) => + action.placement === 'quick-dropdown-toggle' || action.type !== 'sendNow', + ), + { Component: CopyLink, placement: 'dropdown', type: 'copyLink' }, + ]; + await renderActions({ + components: { + ScheduledMessageItem: (props: ScheduledMessageItemProps) => ( + + ), + }, + }); + + await openActionsMenu(); + + expect(getMenuLabels()).toEqual(['Reschedule', 'Delete', 'Copy link']); + }); + it('has no accessibility violations with the menu open', async () => { - const { container } = await renderActions({ onEdit: vi.fn() }); + const { container } = await renderActions({ openInComposer: vi.fn() }); await openActionsMenu(); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx index 268fbd970c..0c4c90c78b 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -31,12 +31,12 @@ import { } from '../../../mock-builders'; import type { ScheduledMessageSearchFilter } from '../hooks'; import { useScheduledMessagesSearch } from '../hooks'; -import { getChannelByCid } from '../utils'; +import { splitCid } from '../utils'; import type { ScheduledMessageListProps } from '../ScheduledMessageList'; import { ScheduledMessageList } from '../ScheduledMessageList'; import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; -type EditScheduledMessage = NonNullable; +type OpenInComposer = NonNullable; const cid = 'messaging:general'; @@ -48,7 +48,7 @@ const atLocalTime = (day: number, hour: number) => type RenderListOptions = { client?: StreamChat; components?: Parameters[0]['overrides']; - onEdit?: EditScheduledMessage; + openInComposer?: OpenInComposer; filter?: ScheduledMessageSearchFilter; listProps?: Partial; scheduledMessages?: ScheduledMessageResponse[]; @@ -59,17 +59,20 @@ type RenderListOptions = { const SearchedList = ({ filter, listProps, - onEdit, + openInComposer, searchQuery = '', -}: Pick) => { +}: Pick< + RenderListOptions, + 'filter' | 'listProps' | 'openInComposer' | 'searchQuery' +>) => { const { client } = useChatContext(); const { filter: searchFilter, setSearchQuery } = useScheduledMessagesSearch({ filter }); useEffect(() => setSearchQuery(searchQuery), [searchQuery, setSearchQuery]); return ( ); @@ -80,7 +83,7 @@ const renderList = async ({ components = {}, filter, listProps, - onEdit, + openInComposer, scheduledMessages = [], searchQuery, }: RenderListOptions = {}) => { @@ -97,7 +100,7 @@ const renderList = async ({ @@ -328,7 +331,7 @@ describe('ScheduledMessageList', () => { setNextCursor(client); // as a scroll to the bottom would - await act(() => getChannelByCid(client, cid).scheduledMessages.toTail()); + await act(() => client.channel(...splitCid(cid)).scheduledMessages.toTail()); expect(await screen.findByText('Friday demo')).toBeInTheDocument(); expect(query).toHaveBeenCalledTimes(2); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx index 94315a6a22..f792bc6504 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -375,13 +375,13 @@ describe('ScheduledMessagesBanner', () => { it('opens what the ScheduledMessageListDialog slot renders', async () => { const scheduledMessage = generateScheduledMessage({ cid }); const ScheduledMessageListDialog = vi.fn( - ({ close, onEdit, open }: ScheduledMessageListDialogProps) => + ({ close, open, openInComposer }: ScheduledMessageListDialogProps) => open ? (
-
diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts index 5f36e46116..b248f766c8 100644 --- a/src/components/ScheduledMessages/__tests__/utils.test.ts +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -6,7 +6,6 @@ import { formatTimeZoneOffset, fromInputValues, getDefaultScheduledAt, - getScheduledMessageActions, getSchedulePresets, getScheduleTimeBounds, getScheduleTimeError, @@ -100,35 +99,6 @@ describe('scheduled message utils', () => { }); }); - describe('actions', () => { - it('offers every action for a pending message, without edit when it cannot open', () => { - const pending = generateScheduledMessage(); - - expect(getScheduledMessageActions(pending, true)).toEqual([ - 'edit', - 'reschedule', - 'send_now', - 'delete', - ]); - expect(getScheduledMessageActions(pending, false)).not.toContain('edit'); - }); - - it('offers nothing while the message is being sent', () => { - expect( - getScheduledMessageActions(generateScheduledMessage({ status: 'sending' }), true), - ).toEqual([]); - }); - - it('offers copy and delete for a message whose channel was deleted', () => { - const failed = generateScheduledMessage({ - failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted, - status: 'failed', - }); - - expect(getScheduledMessageActions(failed, true)).toEqual(['copy', 'delete']); - }); - }); - it('explains a failure, except when the user was deleted', () => { const t = ((_key: string, defaultValue: string) => defaultValue) as never; diff --git a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts index fc7a9bbf88..6980558c9d 100644 --- a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts +++ b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts @@ -3,7 +3,7 @@ import type { LocalMessage, ScheduledMessageResponse } from 'stream-chat'; import { useChatContext, useTranslationContext } from '../../../context'; import type { ScheduleTimeDialogProps } from '../ScheduleTimeDialog'; -import { getChannelByCid } from '../utils'; +import { splitCid } from '../utils'; export type UseRescheduleDialogPropsParams = { previewMessage: LocalMessage; @@ -40,10 +40,9 @@ export const useRescheduleDialogProps = ({ previewMessage, // a failure keeps the dialog open, showing it submit: async (scheduledAt: Date) => { - const updated = await getChannelByCid( - client, - scheduledMessage.cid, - ).updateScheduledMessage(scheduledMessage.id, { scheduled_at: scheduledAt }); + const updated = await client + .channel(...splitCid(scheduledMessage.cid)) + .updateScheduledMessage(scheduledMessage.id, { scheduled_at: scheduledAt }); onRescheduled?.(updated); }, submitLabel: t('scheduledMessages.save', 'Save'), diff --git a/src/components/ScheduledMessages/index.ts b/src/components/ScheduledMessages/index.ts index 44e5465a4a..b4ec7f6023 100644 --- a/src/components/ScheduledMessages/index.ts +++ b/src/components/ScheduledMessages/index.ts @@ -1,4 +1,5 @@ export * from './hooks'; +export * from './ScheduledMessageActions'; export * from './ScheduledMessageItem'; export * from './ScheduledMessageList'; export * from './ScheduledMessageListDialog'; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 439ecf859b..3929bd6473 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -12,7 +12,6 @@ import type { MessageComposerState, ScheduledMessageFailureReason, ScheduledMessageResponse, - StreamChat, } from 'stream-chat'; import type { StreamTFunction } from '../../i18n/types'; @@ -35,16 +34,10 @@ export const SCHEDULED_MESSAGES_EMITTER = 'ScheduledMessages'; export type ScheduleTimeBounds = { earliest: Date; latest?: Date }; -export type ScheduledMessageAction = - | 'copy' - | 'delete' - | 'edit' - | 'reschedule' - | 'send_now'; - -export const getChannelByCid = (client: StreamChat, cid: string) => { +/** A channel's type and ID, for `client.channel(...splitCid(cid))`. Channel IDs contain no `:`. */ +export const splitCid = (cid: string) => { const [type, id] = cid.split(':'); - return client.channelManager.get(cid) ?? client.channel(type, id); + return [type, id] as const; }; export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) => @@ -141,21 +134,6 @@ export const formatTimeZoneOffset = (date: Date) => { return `GMT${sign}${hours}${minutes ? `:${String(minutes).padStart(2, '0')}` : ''}`; }; -/** What the user may do with a scheduled message; `edit` only where the list can open it. */ -export const getScheduledMessageActions = ( - { failure_reason, status }: ScheduledMessageResponse, - canEdit: boolean, -): ScheduledMessageAction[] => { - if (status === SCHEDULED_MESSAGE_STATUS.Sending) return []; - const actions: ScheduledMessageAction[] = - status !== SCHEDULED_MESSAGE_STATUS.Failed - ? ['edit', 'reschedule', 'send_now', 'delete'] - : failure_reason === SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted - ? ['copy', 'delete'] - : ['edit', 'delete']; - return canEdit ? actions : actions.filter((action) => action !== 'edit'); -}; - /** * Whether the composer edits a message: a message, or a pending scheduled one. A failed scheduled * message open in it is not edited but sent or scheduled again, so the composer works as usual. diff --git a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx index f7081363d9..35e5a3c200 100644 --- a/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx +++ b/src/plugins/ChannelDetail/Views/ScheduledMessagesView/ScheduledMessagesView.tsx @@ -45,7 +45,7 @@ export const ScheduledMessagesView = () => { )} From 103d357e23975ddd666ab52b60984f4ec480d6e6 Mon Sep 17 00:00:00 2001 From: martincupela Date: Fri, 13 Nov 2026 12:51:09 +0100 Subject: [PATCH 13/35] fix(MessageComposer): scroll the composer previews past their height cap The previews are capped at 400px with overflow hidden, which assumed the attachment list absorbs any overflow. It is the only preview that shrinks: stacked quote, link, location, poll or scheduled-message previews taller than the cap were cut off with no way to reach them. The container now scrolls vertically once the attachment list cannot shrink further. --- src/components/MessageComposer/styling/MessageComposer.scss | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/components/MessageComposer/styling/MessageComposer.scss b/src/components/MessageComposer/styling/MessageComposer.scss index 66cb997bc3..584d96ba99 100644 --- a/src/components/MessageComposer/styling/MessageComposer.scss +++ b/src/components/MessageComposer/styling/MessageComposer.scss @@ -127,7 +127,10 @@ display: flex; flex-direction: column; max-height: 400px; - overflow: hidden; + // scrolls once the previews outgrow the cap: only the attachment list shrinks to fit, so + // stacked previews (quote, link, location, poll) would otherwise be cut off + overflow-x: hidden; + overflow-y: auto; width: 100%; padding: var(--str-chat__spacing-xs) var(--str-chat__spacing-xs) 0; gap: var(--str-chat__spacing-xxs); From 367d0150201f5ad38d53375910c60ca66b725020 Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Tue, 24 Nov 2026 16:45:50 +0100 Subject: [PATCH 14/35] fix(ScheduledMessages): follow the renamed LLC APIs and keep the time dialog open - Release the scheduled-message paginator subscriptions through the function registerSubscriptions() returns, and use scheduleMessage(), cancelScheduledMessageEdit() and channel.ensureScheduledMessagesLoaded(). - Give the custom time dialog an id (getScheduleTimeDialogId) and keep the recording button out of the composer actions while it is open, so the dialog stays mounted when the composer empties during a failed request. - Cover a schedule that waits for an attachment still uploading. --- ...ConfigurablePollCreationDialogControls.tsx | 2 +- src/components/Chat/hooks/useChat.ts | 5 +- .../MessageComposerActions.tsx | 16 +++- .../MessageComposerPreviews.defaults.tsx | 2 +- .../ScheduleMessageButton.tsx | 9 +- .../__tests__/ScheduleMessageButton.test.tsx | 95 ++++++++++++++++++- .../ScheduledMessages/__tests__/utils.test.ts | 16 +++- .../hooks/useChannelScheduledMessages.ts | 4 +- src/components/ScheduledMessages/utils.ts | 8 ++ 9 files changed, 141 insertions(+), 16 deletions(-) diff --git a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx index 26258f266e..9c0c251ed5 100644 --- a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx +++ b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx @@ -75,7 +75,7 @@ const AttachPollControls = ({ close }: PollCreationDialogControlsProps) => { pollCreatedForScheduleRef.current = messageComposer.pollId; } if (!messageComposer.pollId) throw new Error('The poll was not created'); - const { error, status } = await messageComposer.schedule(scheduledAt); + const { error, status } = await messageComposer.scheduleMessage(scheduledAt); if (status !== 'scheduled' && status !== 'sent') { throw error ?? new Error(`The poll was not scheduled: ${status}`); } diff --git a/src/components/Chat/hooks/useChat.ts b/src/components/Chat/hooks/useChat.ts index 5702e4e3e3..288ba1a140 100644 --- a/src/components/Chat/hooks/useChat.ts +++ b/src/components/Chat/hooks/useChat.ts @@ -43,7 +43,8 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.registerSubscriptions(); client.reminders.registerSubscriptions(); client.reminders.initTimers(); - client.scheduledMessagePaginators.registerSubscriptions(); + const releaseScheduledMessagePaginators = + client.scheduledMessagePaginators.registerSubscriptions(); return () => { releaseChannelManager(); @@ -51,7 +52,7 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.unregisterSubscriptions(); client.reminders.unregisterSubscriptions(); client.reminders.clearTimers(); - client.scheduledMessagePaginators.unregisterSubscriptions(); + releaseScheduledMessagePaginators(); }; }, [client]); diff --git a/src/components/MessageComposer/MessageComposerActions.tsx b/src/components/MessageComposer/MessageComposerActions.tsx index 2a5a3bd2e9..82a6c49fa4 100644 --- a/src/components/MessageComposer/MessageComposerActions.tsx +++ b/src/components/MessageComposer/MessageComposerActions.tsx @@ -22,7 +22,8 @@ import { useStateStore } from '../../store'; import { useInertWhenHidden } from '../Accessibility'; import { useCanScheduleMessage } from '../ScheduledMessages/hooks/useCanScheduleMessage'; import { ScheduleMessageButton as DefaultScheduleMessageButton } from '../ScheduledMessages/ScheduleMessageButton'; -import { isComposerEditing } from '../ScheduledMessages/utils'; +import { getScheduleTimeDialogId, isComposerEditing } from '../ScheduledMessages/utils'; +import { useModalDialogIsOpen } from '../Dialog'; // Typed as `AIState[]` because an inferred array of the literal-typed `AIStates` members would // reject the wide `AIState` that `useAIState` returns. @@ -50,6 +51,11 @@ export const MessageComposerActions = () => { } = useComponentContext(); const canScheduleMessage = useCanScheduleMessage(); + + const isScheduleTimeDialogOpen = useModalDialogIsOpen( + getScheduleTimeDialogId(messageComposer), + ); + const { isEditing } = useStateStore( messageComposer.state, messageComposerStateSelector, @@ -102,7 +108,13 @@ export const MessageComposerActions = () => { return null; } else if (isCooldownActive) { content = ; - } else if (contentIsEmpty && !isEditing && !command && recordingEnabled) { + } else if ( + contentIsEmpty && + !isEditing && + !command && + recordingEnabled && + !isScheduleTimeDialogOpen + ) { content = ; } else if (canScheduleMessage && ScheduleMessageButton) { content = ( diff --git a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx index a1b1ff1e4c..6bc1b245e6 100644 --- a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx +++ b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx @@ -62,7 +62,7 @@ const DefaultMessageComposerPreviewComponents = { return ( ); diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx index 6acbcce16b..d204062df8 100644 --- a/src/components/ScheduledMessages/ScheduleMessageButton.tsx +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -28,7 +28,11 @@ import { useMessageComposerController } from '../MessageComposer/hooks/useMessag import { GlobalModal } from '../Modal'; import { Portal } from '../Portal/Portal'; import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; -import { getSchedulePresets, getScheduleTimeBounds } from './utils'; +import { + getSchedulePresets, + getScheduleTimeBounds, + getScheduleTimeDialogId, +} from './utils'; const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); @@ -72,7 +76,7 @@ export const ScheduleMessageButton = () => { // the banner confirms a scheduled message, so success needs no notification const scheduleMessage = useCallback( async (scheduledAt: Date) => { - const { error, status } = await messageComposer.schedule(scheduledAt); + const { error, status } = await messageComposer.scheduleMessage(scheduledAt); if (status === 'scheduled' || status === 'sent') return; // the server keeps the ID of a message it scheduled; the next attempt needs a new one if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.IdTaken) { @@ -203,6 +207,7 @@ export const ScheduleMessageButton = () => { ({ }); type SetupOptions = { + audioRecordingEnabled?: boolean; canSchedule?: boolean; components?: Parameters[0]['overrides']; text?: string; }; const renderComposer = async ({ + audioRecordingEnabled = false, canSchedule = true, components = {}, text = 'Launch moved to Monday', }: SetupOptions = {}) => { const ownCapabilities = canSchedule - ? ['send-message', 'schedule-message'] - : ['send-message']; + ? ['send-message', 'schedule-message', 'upload-file'] + : ['send-message', 'upload-file']; const { channels: [channel], client, @@ -79,7 +82,7 @@ const renderComposer = async ({ - + , @@ -110,7 +113,7 @@ const getNotifications = (client: StreamChat) => client.notifications.store.getLatestValue().notifications; const mockSchedule = (channel: ChannelType) => - vi.spyOn(channel.messageComposer, 'schedule'); + vi.spyOn(channel.messageComposer, 'scheduleMessage'); const scheduledResult = ( scheduledMessage: ScheduledMessageResponse, @@ -264,6 +267,42 @@ describe('ScheduleMessageButton', () => { await waitFor(() => expect(channel.messageComposer.textComposer.text).toBe('')); }); + it('sends the scheduled message once an attachment still uploading has finished', async () => { + const { channel, client } = await renderComposer(); + const { attachmentManager } = channel.messageComposer; + let finishUpload: (value: { file: string }) => void = () => undefined; + channel.messageComposer.updateConfig({ + attachments: { pendingUploadsEnabled: true }, + }); + vi.spyOn(attachmentManager, 'isUploadEnabled', 'get').mockReturnValue(true); + attachmentManager.setCustomUploadFn( + () => + new Promise((resolve) => { + finishUpload = resolve; + }), + ); + useMockedApis(client, [ + sendScheduledMessageApi(generateScheduledMessage({ cid: channel.cid })), + ]); + const sendMessage = vi.spyOn(channel, 'sendMessage'); + + act(() => { + void attachmentManager.uploadFiles([ + new File(['launch plan'], 'launch-plan.pdf', { type: 'application/pdf' }), + ]); + }); + await waitFor(() => expect(attachmentManager.uploadsInProgressCount).toBe(1)); + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 13:00'))); + + expect(sendMessage).not.toHaveBeenCalled(); + await act(() => finishUpload({ file: 'https://cdn.example.com/launch-plan.pdf' })); + await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1)); + expect(sendMessage.mock.calls[0][0].message.attachments).toEqual([ + expect.objectContaining({ asset_url: 'https://cdn.example.com/launch-plan.pdf' }), + ]); + }); + it('refreshes the composer id when the server reports the id as taken', async () => { const { channel, client } = await renderComposer(); useMockedApis(client, [ @@ -552,4 +591,52 @@ describe('ScheduleMessageButton', () => { expect(await axe(dialog)).toHaveNoViolations(); }); }); + + describe('custom time dialog with audio recording enabled', () => { + beforeEach(() => { + window.MediaRecorder = MediaRecorderMock as unknown as typeof MediaRecorder; + Object.defineProperty(navigator, 'mediaDevices', { + configurable: true, + value: { getUserMedia: vi.fn().mockResolvedValue({}) }, + }); + }); + + afterEach(() => { + Object.defineProperty(navigator, 'mediaDevices', { + configurable: true, + value: undefined, + }); + }); + + it('stays open and shows the error when the composer empties during a failed request', async () => { + const { channel, client } = await renderComposer({ audioRecordingEnabled: true }); + useMockedApis(client, [ + erroredScheduledMessageApi(116, ScheduledMessageErrorReason.TooFar), + ]); + + const dialog = await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(await within(dialog).findByRole('alert')).toHaveTextContent( + 'Choose an earlier time', + ); + expect(screen.getByTestId('schedule-message-dialog')).toBe(dialog); + expect(channel.messageComposer.textComposer.text).toBe('Launch moved to Monday'); + }); + + it('closes and shows the recording button once the request succeeds', async () => { + const { channel, client } = await renderComposer({ audioRecordingEnabled: true }); + useMockedApis(client, [ + sendScheduledMessageApi(generateScheduledMessage({ cid: channel.cid })), + ]); + + await openDialog(); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + expect(screen.getByTestId('start-recording-audio-button')).toBeInTheDocument(); + }); + }); }); diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts index b248f766c8..2a3b3f4135 100644 --- a/src/components/ScheduledMessages/__tests__/utils.test.ts +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -1,5 +1,5 @@ import { SCHEDULED_MESSAGE_FAILURE_REASON } from 'stream-chat'; -import type { Channel } from 'stream-chat'; +import type { Channel, MessageComposer } from 'stream-chat'; import { generateScheduledMessage } from '../../../mock-builders'; import { @@ -8,6 +8,7 @@ import { getDefaultScheduledAt, getSchedulePresets, getScheduleTimeBounds, + getScheduleTimeDialogId, getScheduleTimeError, matchesScheduledMessageText, translateScheduledMessageFailureReason, @@ -142,4 +143,17 @@ describe('scheduled message utils', () => { expect(formatTimeZoneOffset(date)).toBe('GMT+5:30'); }); + + it('names the time dialog after the composer channel and thread', () => { + const channel = { cid: 'messaging:general' } as Channel; + const channelComposer = { channel, threadId: null } as MessageComposer; + const threadComposer = { channel, threadId: 'parent-id' } as MessageComposer; + + expect(getScheduleTimeDialogId(channelComposer)).toBe( + 'schedule-message-dialog-messaging:general', + ); + expect(getScheduleTimeDialogId(threadComposer)).toBe( + 'schedule-message-dialog-messaging:general-parent-id', + ); + }); }); diff --git a/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts index 0e20861929..64f635818d 100644 --- a/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts +++ b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts @@ -34,9 +34,7 @@ export const useChannelScheduledMessages = (view: ScheduledMessagesView) => { useEffect(() => { if (!channel || !initialized) return; - const paginator = channel.scheduledMessagesPaginator; - if (paginator.hasLoadedPage || !channel.scheduledMessagesEnabled) return; - paginator.reload().catch(() => undefined); + channel.ensureScheduledMessagesLoaded(); }, [channel, initialized, isEnabledByConfig, ownCapabilities]); return useScheduledMessages(view); diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 3929bd6473..75f0e2af85 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -9,6 +9,7 @@ import { } from 'stream-chat'; import type { Channel, + MessageComposer, MessageComposerState, ScheduledMessageFailureReason, ScheduledMessageResponse, @@ -21,6 +22,7 @@ const MS_IN_SECOND = 1000; const CLOCK_SKEW_BUFFER_MS = 60 * MS_IN_SECOND; const MORNING_HOUR = 9; const AFTERNOON_HOUR = 13; +const SCHEDULE_TIME_DIALOG_ID_PREFIX = 'schedule-message-dialog'; /** Notifications the UI emits; the composer's own come from `CORE_NOTIFICATION_TYPE`. */ export const SCHEDULED_MESSAGE_NOTIFICATION_TYPE = { @@ -40,6 +42,12 @@ export const splitCid = (cid: string) => { return [type, id] as const; }; +export const getScheduleTimeDialogId = ({ + channel, + threadId, +}: Pick) => + [SCHEDULE_TIME_DIALOG_ID_PREFIX, channel.cid, threadId].filter(Boolean).join('-'); + export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) => status === SCHEDULED_MESSAGE_STATUS.Failed; From 1ec9d755aa08e8e0956c0a9d04f6b50a24be9812 Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Tue, 24 Nov 2026 16:46:55 +0100 Subject: [PATCH 15/35] feat(ScheduledMessages): align the web UI with the Figma designs - Editing a scheduled message shows the "Edit scheduled message" preview with the original text and keeps the banner visible; the send time changes only through Reschedule in the list. - List rows show the message text at body size in the primary colour, without the "You:" prefix, and load with skeleton rows. - The delete confirmation is the compact alert with a muted description; a failed message's edit action uses the clock icon. - The time dialog drops its offline notice for the app's connection banner, and a message the server sends at once because its time has passed is announced. - Once a channel holds as many pending scheduled messages as it allows, thread replies included, the banner reads "N of N scheduled messages" and the schedule menu's times are disabled under "Limit reached". --- .../ScheduleMessageButton.tsx | 64 ++++++++- .../ScheduledMessages/ScheduleTimeDialog.tsx | 8 -- .../ScheduledMessageActions.tsx | 4 +- .../ScheduledMessageList.tsx | 24 +++- .../ScheduledMessagePreview.tsx | 102 ++------------- .../ScheduledMessagesBanner.tsx | 47 ++++--- .../__tests__/EditScheduledMessage.test.tsx | 69 +++------- .../__tests__/ScheduleMessageButton.test.tsx | 123 +++++++++++++----- .../ScheduledMessageActions.test.tsx | 13 +- .../__tests__/ScheduledMessageList.test.tsx | 7 +- .../ScheduledMessagesBanner.test.tsx | 34 ++++- .../__tests__/scheduleTimeFields.ts | 13 ++ .../ScheduledMessages/__tests__/utils.test.ts | 20 +++ .../hooks/useChannelScheduledMessageLimit.ts | 24 ++++ .../hooks/useRescheduleDialogProps.ts | 6 +- .../styling/ScheduledMessageList.scss | 97 +++++++++++++- .../styling/ScheduledMessagePreview.scss | 38 ------ .../ScheduledMessages/styling/index.scss | 1 - src/components/ScheduledMessages/utils.ts | 15 +++ src/i18n/__tests__/catalog.fixture.json | 8 +- src/i18n/keys.ts | 8 +- 21 files changed, 448 insertions(+), 277 deletions(-) create mode 100644 src/components/ScheduledMessages/__tests__/scheduleTimeFields.ts create mode 100644 src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts delete mode 100644 src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx index d204062df8..98031c2d11 100644 --- a/src/components/ScheduledMessages/ScheduleMessageButton.tsx +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -6,7 +6,7 @@ import { ScheduledMessageErrorReason, toScheduledMessagePreview, } from 'stream-chat'; -import type { LocalMessage, UserResponse } from 'stream-chat'; +import type { LocalMessage, MessageComposer, UserResponse } from 'stream-chat'; import { useChatContext, @@ -26,12 +26,16 @@ import { import { useMessageComposerHasSendableData } from '../MessageComposer/hooks'; import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; import { GlobalModal } from '../Modal'; +import { useNotificationApi } from '../Notifications'; import { Portal } from '../Portal/Portal'; +import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit'; import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { getSchedulePresets, getScheduleTimeBounds, getScheduleTimeDialogId, + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, } from './utils'; const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); @@ -42,11 +46,31 @@ const SCHEDULING_FAILURE_NOTIFICATION_TYPES: ReadonlySet = new Set([ CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed, ]); +const getScheduleMessageMenuId = ({ threadId }: Pick) => + `schedule-message-menu${threadId ? '-thread' : ''}`; + +const getScheduleMessageMenuHeaderId = ( + messageComposer: Pick, +) => `${getScheduleMessageMenuId(messageComposer)}-header`; + const ScheduleMessageMenuHeader = () => { const { t } = useTranslationContext(); + const messageComposer = useMessageComposerController(); + const { reachedLimit } = useChannelScheduledMessageLimit(messageComposer.channel); + + const title = + reachedLimit !== undefined + ? t('scheduledMessages.limitReachedMax', 'Limit reached ({{ max }} max)', { + max: reachedLimit, + }) + : t('scheduledMessages.scheduleMessage', 'Schedule message'); + return ( - - {t('scheduledMessages.scheduleMessage', 'Schedule message')} + + {title} ); }; @@ -64,10 +88,19 @@ export const ScheduleMessageButton = () => { Modal = GlobalModal, ScheduleTimeDialog = DefaultScheduleTimeDialog, } = useComponentContext(); + const { addNotification } = useNotificationApi(); const messageComposer = useMessageComposerController(); const hasSendableData = useMessageComposerHasSendableData(); - const menuId = `schedule-message-menu${messageComposer.threadId ? '-thread' : ''}`; + const { reachedLimit } = useChannelScheduledMessageLimit(messageComposer.channel); + const isLimitReached = reachedLimit !== undefined; + const menuId = getScheduleMessageMenuId(messageComposer); + const limitReachedProps = isLimitReached + ? { + 'aria-describedby': getScheduleMessageMenuHeaderId(messageComposer), + 'aria-disabled': true as const, + } + : undefined; const { dialog: menu, dialogManager } = useDialogOnNearestManager({ id: menuId }); const isMenuOpen = useDialogIsOpen(menuId, dialogManager?.id); const buttonRef = useRef(null); @@ -77,14 +110,26 @@ export const ScheduleMessageButton = () => { const scheduleMessage = useCallback( async (scheduledAt: Date) => { const { error, status } = await messageComposer.scheduleMessage(scheduledAt); - if (status === 'scheduled' || status === 'sent') return; + if (status === 'sent') { + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + message: t( + 'scheduledMessages.notification.sentNow', + 'Time passed. Message sent now', + ), + severity: 'success', + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sentNow, + }); + return; + } + if (status === 'scheduled') return; // the server keeps the ID of a message it scheduled; the next attempt needs a new one if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.IdTaken) { messageComposer.refreshId(); } throw error ?? new Error(`Message not scheduled: ${status}`); }, - [messageComposer], + [addNotification, messageComposer, t], ); // the dialog shows the failure itself, so the composer's notification of it is dropped @@ -185,7 +230,9 @@ export const ScheduleMessageButton = () => { className='str-chat__schedule-message-menu__preset' Icon={IconClock} key={scheduledAt.getTime()} + {...limitReachedProps} onClick={() => { + if (isLimitReached) return; menu.close(); scheduleMessage(scheduledAt).catch(() => undefined); }} @@ -199,7 +246,10 @@ export const ScheduleMessageButton = () => { className='str-chat__schedule-message-menu__custom-time' hasSubMenu Icon={IconClock} - onClick={openDialog} + {...limitReachedProps} + onClick={() => { + if (!isLimitReached) openDialog(); + }} > {t('scheduledMessages.customTime', 'Custom time')} diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx index ad89d50865..f2a00c3276 100644 --- a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -216,14 +216,6 @@ export const ScheduleTimeDialog = ({ className='str-chat__schedule-message-dialog__preview' quotedMessage={previewMessage} /> - {!isOnline && ( - - {t( - 'scheduledMessages.youreOfflineReconnectToScheduleThisMessage', - "You're offline. Reconnect to schedule this message.", - )} - - )} {status === 'failed' && ( {translateScheduledMessageError(t, submitError) ?? errorMessage} diff --git a/src/components/ScheduledMessages/ScheduledMessageActions.tsx b/src/components/ScheduledMessages/ScheduledMessageActions.tsx index e0b212515b..99b88ef8c5 100644 --- a/src/components/ScheduledMessages/ScheduledMessageActions.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageActions.tsx @@ -266,14 +266,14 @@ const QuickEdit = () => { const DropdownEdit = () => { const { t } = useTranslationContext(); - const { IconEdit } = useComponentContextIcons(); + const { IconClock } = useComponentContextIcons(); const { closeMenu } = useContextMenuContext(); const { canEdit } = useScheduledMessageActionsContext(); const { edit, unavailableProps } = useEditActionProps(); return ( { if (!canEdit) return; diff --git a/src/components/ScheduledMessages/ScheduledMessageList.tsx b/src/components/ScheduledMessages/ScheduledMessageList.tsx index e9198c932a..42bce60b48 100644 --- a/src/components/ScheduledMessages/ScheduledMessageList.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -95,6 +95,26 @@ const DefaultEmptyListIndicator = () => { ); }; +const FIRST_PAGE_LOADING_ROW_COUNT = 6; + +const loadingRowKeys = Array.from( + { length: FIRST_PAGE_LOADING_ROW_COUNT }, + (_, index) => `scheduled-message-loading-row-${index}`, +); + +const ScheduledMessageLoadingRow = () => ( +
+
+
+
+
+
+
+
+
+
+); + const DefaultFirstPageLoadingIndicator = () => { const { t } = useTranslationContext(); return ( @@ -106,7 +126,9 @@ const DefaultFirstPageLoadingIndicator = () => { className='str-chat__scheduled-message-list-loading' role='status' > - + {loadingRowKeys.map((key) => ( + + ))}
); }; diff --git a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx index 009e289997..14084841b1 100644 --- a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx +++ b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx @@ -1,20 +1,9 @@ -import React, { useState } from 'react'; -import { nsToDate } from 'stream-chat'; +import React from 'react'; import type { ScheduledMessageResponse } from 'stream-chat'; -import { - useComponentContext, - useComponentContextIcons, - useTranslationContext, -} from '../../context'; -import { Button } from '../Button'; -import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; +import { useTranslationContext } from '../../context'; import { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; -import { RemoveAttachmentPreviewButton } from '../MessageComposer/RemoveAttachmentPreviewButton'; -import { GlobalModal } from '../Modal'; import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; -import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; -import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { isFailedScheduledMessage } from './utils'; export type ScheduledMessagePreviewProps = { @@ -22,92 +11,23 @@ export type ScheduledMessagePreviewProps = { scheduledMessage: ScheduledMessageResponse; }; -/** - * Above the composer while a scheduled message is edited: when it is sent, with a way to change - * that time. A failed one, scheduled again as a new message, is previewed as the message. - */ export const ScheduledMessagePreview = ({ onCancel, scheduledMessage, }: ScheduledMessagePreviewProps) => { const { t } = useTranslationContext(); - const { IconClock } = useComponentContextIcons(); - const { Modal = GlobalModal, ScheduleTimeDialog = DefaultScheduleTimeDialog } = - useComponentContext(); - const { channel } = useMessageComposerController(); - const previewMessage = useScheduledMessagePreview(scheduledMessage); - const [isRescheduling, setIsRescheduling] = useState(false); - // the saved copy, until the composer's own copy catches up through the update event - const [rescheduled, setRescheduled] = useState(); - const current = - rescheduled?.id === scheduledMessage.id && - rescheduled.updated_at > scheduledMessage.updated_at - ? rescheduled - : scheduledMessage; - const rescheduleDialogProps = useRescheduleDialogProps({ - onRescheduled: setRescheduled, - previewMessage, - scheduledMessage: current, - }); - if (isFailedScheduledMessage(scheduledMessage)) { - return ( - - ); - } + const previewMessage = useScheduledMessagePreview(scheduledMessage); - const sendTime = nsToDate(current.scheduled_at); - const closeDialog = () => setIsRescheduling(false); + const authorLabel = isFailedScheduledMessage(scheduledMessage) + ? t('scheduledMessages.scheduleAgain', 'Schedule again') + : t('scheduledMessages.editScheduledMessage', 'Edit scheduled message'); return ( -
- - - - - - {isRescheduling && ( - - )} - -
+ ); }; diff --git a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx index d831705a20..3aa19a4fcb 100644 --- a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx +++ b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx @@ -18,24 +18,27 @@ import { useChannelCapabilities } from '../Channel/hooks/useChannelCapabilities' import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; import { SCHEDULE_MESSAGE_CAPABILITY, useChannelScheduledMessages } from './hooks'; import { ScheduledMessageListDialog as DefaultScheduledMessageListDialog } from './ScheduledMessageListDialog'; +import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit'; import { isFailedScheduledMessage } from './utils'; const selectIsLoaded = ({ items }: PaginatorState) => ({ isLoaded: items !== undefined, }); -// hidden for a failed scheduled message open in the composer too const selectIsEditing = ({ editedMessage, editedScheduledMessage, }: MessageComposerState) => ({ - isEditing: !!editedMessage || !!editedScheduledMessage, + isEditing: + !!editedMessage || + (!!editedScheduledMessage && isFailedScheduledMessage(editedScheduledMessage)), }); /** * Above the composer: when the only scheduled message in the channel (or thread) is sent, how many * are scheduled, or how many failed. "View all" opens the `ScheduledMessageListDialog` slot. Hidden - * while the composer edits a message; its changes are announced to screen readers. + * while the composer edits a sent message or a failed scheduled one; its changes are announced to + * screen readers. */ export const ScheduledMessagesBanner = () => { const { t } = useTranslationContext(); @@ -54,6 +57,7 @@ export const ScheduledMessagesBanner = () => { SCHEDULE_MESSAGE_CAPABILITY, ); const { scheduledMessages } = useChannelScheduledMessages(view); + const { pendingCount, reachedLimit } = useChannelScheduledMessageLimit(channel); const { isLoaded } = useStateStore(view.paginator.state, selectIsLoaded); const { isEditing } = useStateStore(messageComposer.state, selectIsEditing); const announce = useAriaLiveAnnouncer(); @@ -71,23 +75,30 @@ export const ScheduledMessagesBanner = () => { defaultValue_one: '{{ count }} failed to send', defaultValue_other: '{{ count }} failed to send', }) - : onlyScheduledMessage - ? t('scheduledMessages.banner.scheduledFor', 'Scheduled for {{ time }}', { - time: t('timestamp.ScheduledMessageConfirmation', { - timestamp: nsToDate(onlyScheduledMessage.scheduled_at), - }), + : reachedLimit !== undefined && !parentId + ? t('scheduledMessages.banner.limitReached', { + count: reachedLimit, + defaultValue_one: '{{ scheduled }} of {{ count }} scheduled message', + defaultValue_other: '{{ scheduled }} of {{ count }} scheduled messages', + scheduled: pendingCount, }) - : parentId - ? t('scheduledMessages.banner.scheduledReplies', { - count: scheduledMessages.length, - defaultValue_one: '{{ count }} scheduled reply', - defaultValue_other: '{{ count }} scheduled replies', + : onlyScheduledMessage + ? t('scheduledMessages.banner.scheduledFor', 'Scheduled for {{ time }}', { + time: t('timestamp.ScheduledMessageConfirmation', { + timestamp: nsToDate(onlyScheduledMessage.scheduled_at), + }), }) - : t('scheduledMessages.banner.scheduledMessages', { - count: scheduledMessages.length, - defaultValue_one: '{{ count }} scheduled message', - defaultValue_other: '{{ count }} scheduled messages', - }); + : parentId + ? t('scheduledMessages.banner.scheduledReplies', { + count: scheduledMessages.length, + defaultValue_one: '{{ count }} scheduled reply', + defaultValue_other: '{{ count }} scheduled replies', + }) + : t('scheduledMessages.banner.scheduledMessages', { + count: scheduledMessages.length, + defaultValue_one: '{{ count }} scheduled message', + defaultValue_other: '{{ count }} scheduled messages', + }); const announcedLabel = isVisible ? label : undefined; // a change, such as a message just scheduled or failed; not the banner the list loaded with diff --git a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx index 19dc1a6276..7220630eab 100644 --- a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx +++ b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx @@ -1,6 +1,6 @@ import '../../..'; import React from 'react'; -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { fromPartial } from '@total-typescript/shoehorn'; import { Channel } from '../../Channel'; @@ -88,55 +88,18 @@ describe('editing a scheduled message in the composer', () => { vi.useRealTimers(); }); - it('shows when the message is sent and hides the schedule button', async () => { + it('previews the message being edited and hides the schedule button', async () => { const { startEditing } = await renderComposer(); await startEditing(); - expect(screen.getByTestId('scheduled-message-preview')).toHaveTextContent( - 'This message will be sent Thu, Oct 29 at 09:00', - ); + const editPreview = screen.getByTestId('quoted-message-preview'); + expect(editPreview).toHaveTextContent('Edit scheduled message'); + expect(editPreview).toHaveTextContent('Launch moved to Monday'); expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); }); - it('reschedules the message without saving the text being edited', async () => { - const { channel, messageComposer, scheduledMessage, startEditing } = - await renderComposer(); - const newSendTime = new Date(2026, 9, 29, 14, 30); - const updateScheduledMessage = vi - .spyOn(channel, 'updateScheduledMessage') - .mockResolvedValue({ - ...scheduledMessage, - scheduled_at: convertDateToTimestamp(newSendTime), - updated_at: scheduledMessage.updated_at + 1_000_000, - }); - - await startEditing(); - await act(() => messageComposer.textComposer.setText('Launch moved to Tuesday')); - await act(() => - fireEvent.click(screen.getByTestId('scheduled-message-preview-reschedule-button')), - ); - const dialog = await screen.findByTestId('schedule-message-dialog'); - expect(dialog).toHaveTextContent('Reschedule message'); - expect(screen.getByLabelText('Time')).toHaveValue('09:00'); - - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); - await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); - - expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { - scheduled_at: newSendTime, - }); - await waitFor(() => - expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), - ); - expect(screen.getByTestId('scheduled-message-preview')).toHaveTextContent( - 'This message will be sent Thu, Oct 29 at 14:30', - ); - expect(messageComposer.editedScheduledMessage?.id).toBe(scheduledMessage.id); - expect(messageComposer.textComposer.text).toBe('Launch moved to Tuesday'); - }); - - it('shows the quoted message below the send time, and lets it be removed', async () => { + it('shows the quoted message below the edit preview, and lets it be removed', async () => { const { channel, client, messageComposer } = await renderComposer(); const quotedMessage = generateMessage({ text: 'Venue options for Saturday', user }); client.messageStore.upsert(quotedMessage); @@ -148,21 +111,19 @@ describe('editing a scheduled message in the composer', () => { await act(() => messageComposer.editScheduledMessage(quotingMessage)); - const sendTimePreview = screen.getByTestId('scheduled-message-preview'); - const quotePreview = screen.getByTestId('quoted-message-preview'); + const [editPreview, quotePreview] = screen.getAllByTestId('quoted-message-preview'); + expect(editPreview).toHaveTextContent('Edit scheduled message'); expect(quotePreview).toHaveTextContent('Venue options for Saturday'); - expect( - sendTimePreview.compareDocumentPosition(quotePreview) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); await act(() => - fireEvent.click(screen.getByTestId('quoted-message-preview-dismiss-btn')), + fireEvent.click( + within(quotePreview).getByTestId('quoted-message-preview-dismiss-btn'), + ), ); - expect(screen.queryByTestId('quoted-message-preview')).not.toBeInTheDocument(); + expect(screen.getAllByTestId('quoted-message-preview')).toHaveLength(1); expect(messageComposer.quotedMessage).toBeNull(); - expect(screen.getByTestId('scheduled-message-preview')).toBeInTheDocument(); + expect(screen.getByText('Edit scheduled message')).toBeInTheDocument(); }); it('saves the edit with updateScheduledMessage instead of sending', async () => { @@ -186,10 +147,10 @@ describe('editing a scheduled message in the composer', () => { await startEditing(); await act(() => - fireEvent.click(screen.getByRole('button', { name: 'Cancel editing' })), + fireEvent.click(screen.getByTestId('quoted-message-preview-dismiss-btn')), ); - expect(screen.queryByTestId('scheduled-message-preview')).not.toBeInTheDocument(); + expect(screen.queryByText('Edit scheduled message')).not.toBeInTheDocument(); expect(messageComposer.textComposer.text).toBe('my unsent draft'); }); diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx index 1daf9a6d3d..d37d6fdea3 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -24,6 +24,7 @@ import { Chat } from '../../Chat'; import { WithComponents } from '../../../context/WithComponents'; import { MessageComposer } from '../../MessageComposer'; import { ScheduleTimeDialog } from '../ScheduleTimeDialog'; +import { enterDate, enterTime, getDateField, getTimeField } from './scheduleTimeFields'; import type { ScheduleDateInputProps, ScheduleTimeInputProps, @@ -33,6 +34,7 @@ import { erroredScheduledMessageApi, generateScheduledMessage, generateUser, + hydrateScheduledMessages, initClientWithChannels, sendScheduledMessageApi, setWSConnectionStatus, @@ -250,6 +252,24 @@ describe('ScheduleMessageButton', () => { expect(getNotifications(client)).toEqual([]); }); + it('says so when the server sent the message at once, its time having passed', async () => { + const { channel, client } = await renderComposer(); + mockSchedule(channel).mockResolvedValue({ status: 'sent' }); + + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 09:00'))); + + await waitFor(() => + expect(getNotifications(client)).toEqual([ + expect.objectContaining({ + message: 'Time passed. Message sent now', + severity: 'success', + type: 'api:scheduled-message:create:sent-now', + }), + ]), + ); + }); + it('sends the composition with scheduled_at to the API', async () => { const { channel, client } = await renderComposer(); const scheduledMessage = generateScheduledMessage({ cid: channel.cid }); @@ -317,6 +337,51 @@ describe('ScheduleMessageButton', () => { expect(channel.messageComposer.textComposer.text).toBe('Launch moved to Monday'); }); + it('disables every time once the channel holds as many as it allows', async () => { + const { channel, client } = await renderComposer(); + const schedule = mockSchedule(channel); + await act(() => + hydrateScheduledMessages( + client, + channel.cid, + Array.from({ length: 10 }, () => + generateScheduledMessage({ cid: channel.cid }), + ), + ), + ); + + const menu = await openMenu(); + + expect(menu).toHaveTextContent('Limit reached (10 max)'); + const items = within(menu).getAllByRole('menuitem'); + expect(items).toHaveLength(4); + items.forEach((item) => expect(item).toHaveAttribute('aria-disabled', 'true')); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 09:00'))); + await act(() => fireEvent.click(screen.getByText('Custom time'))); + + expect(schedule).not.toHaveBeenCalled(); + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(); + }); + + it('does not count failed messages towards the limit', async () => { + const { channel, client } = await renderComposer(); + await act(() => + hydrateScheduledMessages(client, channel.cid, [ + ...Array.from({ length: 9 }, () => + generateScheduledMessage({ cid: channel.cid }), + ), + generateScheduledMessage({ cid: channel.cid, status: 'failed' }), + ]), + ); + + const menu = await openMenu(); + + expect(menu).toHaveTextContent('Schedule message'); + within(menu) + .getAllByRole('menuitem') + .forEach((item) => expect(item).not.toHaveAttribute('aria-disabled')); + }); + it('has no axe violations', async () => { await renderComposer(); @@ -334,8 +399,8 @@ describe('ScheduleMessageButton', () => { expect(dialog).toHaveTextContent('Schedule message'); expect(dialog).toHaveTextContent('Launch moved to Monday'); - expect(screen.getByLabelText('Date')).toHaveValue('2026-10-28'); - expect(screen.getByLabelText('Time')).toHaveValue('11:00'); + expect(getDateField()).toHaveValue('2026-10-28'); + expect(getTimeField()).toHaveValue('11:00'); expect(dialog).toHaveTextContent('Sent in your time zone (GMT)'); expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); }); @@ -344,9 +409,7 @@ describe('ScheduleMessageButton', () => { await renderComposer(); const dialog = await openDialog(); - fireEvent.change(screen.getByLabelText('Date'), { - target: { value: '2026-11-03' }, - }); + enterDate('2026-11-03'); expect( dialog.querySelector('.str-chat__schedule-message-dialog__date-value'), @@ -360,10 +423,8 @@ describe('ScheduleMessageButton', () => { ); await openDialog(); - fireEvent.change(screen.getByLabelText('Date'), { - target: { value: '2026-11-03' }, - }); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '16:45' } }); + enterDate('2026-11-03'); + enterTime('16:45'); await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); expect(schedule).toHaveBeenCalledWith(new Date(2026, 10, 3, 16, 45)); @@ -376,7 +437,7 @@ describe('ScheduleMessageButton', () => { await renderComposer(); await openDialog(); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '10:31' } }); + enterTime('10:31'); expect(screen.getByText('Choose a later time')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); @@ -386,14 +447,27 @@ describe('ScheduleMessageButton', () => { await renderComposer(); await openDialog(); - fireEvent.change(screen.getByLabelText('Date'), { - target: { value: '2027-06-01' }, - }); + enterDate('2027-06-01'); expect(screen.getByText('Choose an earlier time')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); }); + it('opens the picker from anywhere in the field, its icons included', async () => { + await renderComposer(); + + const dialog = await openDialog(); + const time = getTimeField() as HTMLInputElement; + const showPicker = vi.fn(); + time.showPicker = showPicker; + const caret = time + .closest('.str-chat__form-text-input__wrapper') + ?.querySelector('.str-chat__form-text-input__trailing'); + fireEvent.click(caret ?? dialog); + + expect(showPicker).toHaveBeenCalledTimes(1); + }); + it('keeps the dialog open and shows the error when scheduling fails', async () => { const { channel } = await renderComposer(); const schedule = mockSchedule(channel).mockResolvedValue({ @@ -483,37 +557,16 @@ describe('ScheduleMessageButton', () => { }, ); - it('opens the picker from anywhere in the field, its icons included', async () => { - await renderComposer(); - - const dialog = await openDialog(); - const time = screen.getByLabelText('Time') as HTMLInputElement; - const showPicker = vi.fn(); - time.showPicker = showPicker; - const caret = time - .closest('.str-chat__form-text-input__wrapper') - ?.querySelector('.str-chat__form-text-input__trailing'); - fireEvent.click(caret ?? dialog); - - expect(showPicker).toHaveBeenCalledTimes(1); - }); - it('disables Schedule while offline and enables it again on reconnect', async () => { const { client } = await renderComposer(); await openDialog(); await act(() => setWSConnectionStatus(client, false)); - expect( - screen.getByText("You're offline. Reconnect to schedule this message."), - ).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); await act(() => setWSConnectionStatus(client, true)); - expect( - screen.queryByText("You're offline. Reconnect to schedule this message."), - ).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); }); @@ -522,7 +575,7 @@ describe('ScheduleMessageButton', () => { const schedule = mockSchedule(channel); await openDialog(); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '10:35' } }); + enterTime('10:35'); expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); // the dialog stayed open: 10:35 is now in the past and would be sent at once vi.setSystemTime(new Date(2026, 9, 28, 10, 40)); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index 01211f4d3a..843591c03e 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -38,6 +38,7 @@ import { ScheduledMessageItem } from '../ScheduledMessageItem'; import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; import { defaultScheduledMessageActionSet } from '../ScheduledMessageActions'; import type { ScheduledMessageActionSetItem } from '../ScheduledMessageActions'; +import { enterDate, enterTime, getDateField, getTimeField } from './scheduleTimeFields'; type OpenInComposer = NonNullable; @@ -332,10 +333,10 @@ describe('ScheduledMessageActions', () => { expect(dialog).toHaveTextContent('Reschedule message'); expect(dialog).toHaveTextContent('Scheduled for Thu, Oct 29 at 09:00'); - expect(screen.getByLabelText('Date')).toHaveValue('2026-10-29'); - expect(screen.getByLabelText('Time')).toHaveValue('09:00'); + expect(getDateField()).toHaveValue('2026-10-29'); + expect(getTimeField()).toHaveValue('09:00'); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); + enterTime('14:30'); await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { @@ -373,7 +374,7 @@ describe('ScheduledMessageActions', () => { await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); expect(await screen.findByText('Already sent')).toBeInTheDocument(); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '14:30' } }); + enterTime('14:30'); expect(screen.queryByText('Already sent')).not.toBeInTheDocument(); }); @@ -418,8 +419,8 @@ describe('ScheduledMessageActions', () => { await selectAction('reschedule'); const dialog = await screen.findByTestId('schedule-message-dialog'); - fireEvent.change(screen.getByLabelText('Time'), { target: { value: '00:00' } }); - fireEvent.change(screen.getByLabelText('Date'), { target: { value: '2020-01-01' } }); + enterDate('2026-10-28'); + enterTime('00:00'); expect(within(dialog).getByRole('alert')).toHaveTextContent( "Pick a later time. Editing can't send a message right away.", diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx index 0c4c90c78b..9d3c92ea49 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -202,9 +202,12 @@ describe('ScheduledMessageList', () => { setPaginatorState(client, { isLoading: true, items: undefined }); expect(screen.queryByText('No scheduled messages')).not.toBeInTheDocument(); + const loadingState = screen.getByRole('status', { + name: 'Loading scheduled messages', + }); expect( - screen.getByRole('status', { name: 'Loading scheduled messages' }), - ).toBeInTheDocument(); + loadingState.querySelectorAll('.str-chat__scheduled-message-list-loading__row'), + ).toHaveLength(6); }); it('shows the empty state while a later reload runs', async () => { diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx index f792bc6504..621796a2e5 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -157,6 +157,29 @@ describe('ScheduledMessagesBanner', () => { expect(queryBanner()).toHaveTextContent('2 scheduled messages'); }); + it('shows the limit once the channel holds as many as it allows, replies included', async () => { + await renderComposer({ + scheduledMessages: [ + ...Array.from({ length: 9 }, () => generateScheduledMessage({ cid })), + threadReply(), + ], + }); + + expect(queryBanner()).toHaveTextContent('10 of 10 scheduled messages'); + }); + + it('keeps counting replies in a thread when the channel is at its limit', async () => { + await renderComposer({ + inThread: true, + scheduledMessages: [ + ...Array.from({ length: 9 }, () => generateScheduledMessage({ cid })), + threadReply(), + ], + }); + + expect(queryBanner()).toHaveTextContent('Scheduled for'); + }); + it('shows when the only scheduled message is sent, with View', async () => { await renderComposer({ scheduledMessages: [generateScheduledMessage({ cid, scheduled_at: ON_JANUARY_15 })], @@ -166,12 +189,21 @@ describe('ScheduledMessagesBanner', () => { expect(screen.getByRole('button', { name: 'View' })).toBeInTheDocument(); }); - it('is hidden while the composer edits a scheduled message', async () => { + it('stays while the composer edits a scheduled message', async () => { const scheduledMessage = generateScheduledMessage({ cid }); const { channel } = await renderComposer({ scheduledMessages: [scheduledMessage] }); await act(() => channel.messageComposer.editScheduledMessage(scheduledMessage)); + expect(queryBanner()).toBeInTheDocument(); + }); + + it('is hidden while the composer schedules a failed message again', async () => { + const failedMessage = generateScheduledMessage({ cid, status: 'failed' }); + const { channel } = await renderComposer({ scheduledMessages: [failedMessage] }); + + await act(() => channel.messageComposer.editScheduledMessage(failedMessage)); + expect(queryBanner()).not.toBeInTheDocument(); }); diff --git a/src/components/ScheduledMessages/__tests__/scheduleTimeFields.ts b/src/components/ScheduledMessages/__tests__/scheduleTimeFields.ts new file mode 100644 index 0000000000..1b5374945f --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/scheduleTimeFields.ts @@ -0,0 +1,13 @@ +import { fireEvent, screen } from '@testing-library/react'; + +export const getDateField = () => screen.getByLabelText('Date'); + +export const getTimeField = () => screen.getByLabelText('Time'); + +export const enterDate = (value: string) => { + fireEvent.change(getDateField(), { target: { value } }); +}; + +export const enterTime = (value: string) => { + fireEvent.change(getTimeField(), { target: { value } }); +}; diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts index 2a3b3f4135..d5562770d6 100644 --- a/src/components/ScheduledMessages/__tests__/utils.test.ts +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -3,6 +3,7 @@ import type { Channel, MessageComposer } from 'stream-chat'; import { generateScheduledMessage } from '../../../mock-builders'; import { + countPendingScheduledMessages, formatTimeZoneOffset, fromInputValues, getDefaultScheduledAt, @@ -10,6 +11,7 @@ import { getScheduleTimeBounds, getScheduleTimeDialogId, getScheduleTimeError, + isScheduledMessageLimitReached, matchesScheduledMessageText, translateScheduledMessageFailureReason, } from '../utils'; @@ -37,6 +39,24 @@ describe('scheduled message utils', () => { expect(matchesScheduledMessageText(launch, ' ')).toBe(true); }); + it('counts only the messages still waiting to be sent', () => { + const messages = [ + generateScheduledMessage({ status: 'scheduled' }), + generateScheduledMessage({ status: 'scheduled' }), + generateScheduledMessage({ status: 'failed' }), + generateScheduledMessage({ status: 'sending' }), + ]; + + expect(countPendingScheduledMessages(messages)).toBe(2); + expect(countPendingScheduledMessages()).toBe(0); + }); + + it('reaches the limit at the channel maximum, and never without one', () => { + expect(isScheduledMessageLimitReached(10, 10)).toBe(true); + expect(isScheduledMessageLimitReached(9, 10)).toBe(false); + expect(isScheduledMessageLimitReached(100)).toBe(false); + }); + describe('time bounds', () => { it('starts a minute after the minimum lead time and ends at the maximum', () => { const now = at(28, 10); diff --git a/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts b/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts new file mode 100644 index 0000000000..6d023a8724 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts @@ -0,0 +1,24 @@ +import { getScheduledMessageLimits } from 'stream-chat'; +import type { Channel, PaginatorState, ScheduledMessageResponse } from 'stream-chat'; + +import { useStateStore } from '../../../store'; +import { countPendingScheduledMessages, isScheduledMessageLimitReached } from '../utils'; + +const selectPendingCount = ({ items }: PaginatorState) => ({ + pendingCount: countPendingScheduledMessages(items), +}); + +export const useChannelScheduledMessageLimit = (channel: Channel) => { + const { pendingCount } = useStateStore( + channel.scheduledMessages.paginator.state, + selectPendingCount, + ); + + const maxPerChannel = getScheduledMessageLimits(channel)?.maxPerChannel; + const reachedLimit = isScheduledMessageLimitReached(pendingCount, maxPerChannel) + ? maxPerChannel + : undefined; + + const limit = { pendingCount, reachedLimit }; + return limit; +}; diff --git a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts index 6980558c9d..00f7cc05dc 100644 --- a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts +++ b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts @@ -8,8 +8,6 @@ import { splitCid } from '../utils'; export type UseRescheduleDialogPropsParams = { previewMessage: LocalMessage; scheduledMessage: ScheduledMessageResponse; - /** Called with the server's copy once the new time is saved. */ - onRescheduled?: (scheduledMessage: ScheduledMessageResponse) => void; }; /** @@ -17,7 +15,6 @@ export type UseRescheduleDialogPropsParams = { * time. The caller adds `channel` and `close`. */ export const useRescheduleDialogProps = ({ - onRescheduled, previewMessage, scheduledMessage, }: UseRescheduleDialogPropsParams): Omit< @@ -40,10 +37,9 @@ export const useRescheduleDialogProps = ({ previewMessage, // a failure keeps the dialog open, showing it submit: async (scheduledAt: Date) => { - const updated = await client + await client .channel(...splitCid(scheduledMessage.cid)) .updateScheduledMessage(scheduledMessage.id, { scheduled_at: scheduledAt }); - onRescheduled?.(updated); }, submitLabel: t('scheduledMessages.save', 'Save'), title: t('scheduledMessages.rescheduleMessage', 'Reschedule message'), diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss index ea47e07066..db64acb272 100644 --- a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss +++ b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss @@ -1,5 +1,18 @@ @use '../../../styling/utils'; +@mixin loading-shimmer { + background-color: var(--str-chat__background-core-surface-default); + background-image: linear-gradient( + 90deg, + var(--str-chat__skeleton-loading-base) 0%, + var(--str-chat__skeleton-loading-highlight) 50%, + var(--str-chat__skeleton-loading-base) 100% + ); + background-repeat: no-repeat; + background-size: 200% 100%; + animation: scheduled-message-list-loading-shimmer 1.2s linear infinite; +} + // The modal's dialog wrapper is a flex item sized to its content, so without a limit of its own the // dialog's `max-width: 100%` measures against its own 520px and overflows a narrow screen. Top-level, // as in `Modal.scss`: the modal is portaled and is itself the `.str-chat` element, with no such @@ -8,6 +21,14 @@ max-width: calc(100% - 2 * var(--str-chat__spacing-md)); } +.str-chat__delete-scheduled-message-alert { + max-width: 300px; + + .str-chat__alert-header__description { + color: var(--str-chat__text-secondary); + } +} + .str-chat { .str-chat__scheduled-message-list-dialog { width: 520px; @@ -102,6 +123,12 @@ .str-chat__summarized-message-preview { min-width: 0; + color: var(--str-chat__text-primary); + font: var(--str-chat__font-body-default); + + .str-chat__summarized-message-preview__sender { + display: none; + } } .str-chat__scheduled-message-item__status { @@ -156,8 +183,74 @@ } .str-chat__scheduled-message-list-loading { - @include utils.flex-row-center; + display: flex; flex: 1; - padding-block: var(--str-chat__spacing-3xl); + flex-direction: column; + min-height: 0; + overflow: hidden; + } + + .str-chat__scheduled-message-list-loading__row { + display: flex; + flex-direction: column; + gap: var(--str-chat__spacing-xs); + padding: var(--str-chat__spacing-md) var(--str-chat__spacing-xl); + } + + .str-chat__scheduled-message-list-loading__body { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-sm); + } + + .str-chat__scheduled-message-list-loading__lines { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--str-chat__spacing-xs); + min-width: 0; + } + + .str-chat__scheduled-message-list-loading__time, + .str-chat__scheduled-message-list-loading__avatar, + .str-chat__scheduled-message-list-loading__channel-name, + .str-chat__scheduled-message-list-loading__text { + @include loading-shimmer; + } + + .str-chat__scheduled-message-list-loading__time, + .str-chat__scheduled-message-list-loading__channel-name, + .str-chat__scheduled-message-list-loading__text { + height: var(--str-chat__size-16); + border-radius: var(--str-chat__radius-max); + } + + .str-chat__scheduled-message-list-loading__time { + width: min(40%, 160px); + } + + .str-chat__scheduled-message-list-loading__avatar { + flex-shrink: 0; + width: var(--str-chat__size-40); + height: var(--str-chat__size-40); + border-radius: var(--str-chat__radius-max); + } + + .str-chat__scheduled-message-list-loading__channel-name { + width: min(45%, 180px); + } + + .str-chat__scheduled-message-list-loading__text { + width: min(85%, 340px); + } +} + +@keyframes scheduled-message-list-loading-shimmer { + from { + background-position: 200% 0; + } + + to { + background-position: -200% 0; } } diff --git a/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss b/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss deleted file mode 100644 index a631941da1..0000000000 --- a/src/components/ScheduledMessages/styling/ScheduledMessagePreview.scss +++ /dev/null @@ -1,38 +0,0 @@ -@use '../../../styling/utils'; - -.str-chat { - // above the composer while a scheduled message is edited - .str-chat__scheduled-message-preview { - display: flex; - align-items: center; - gap: var(--str-chat__spacing-xs); - position: relative; - margin: var(--str-chat__spacing-xxs); - padding-block: var(--str-chat__spacing-xs); - padding-inline: var(--str-chat__spacing-sm) var(--str-chat__spacing-xxs); - border-radius: var(--str-chat__message-bubble-radius-attachment); - background-color: color-mix(in srgb, var(--str-chat__accent-primary) 5%, transparent); - color: var(--str-chat__text-primary); - - .str-chat__scheduled-message-preview__icon { - flex-shrink: 0; - height: var(--str-chat__icon-size-md); - width: var(--str-chat__icon-size-md); - color: var(--str-chat__accent-primary); - } - - .str-chat__scheduled-message-preview__label { - @include utils.ellipsis-text(); - flex: 1; - min-width: 0; - font: var(--str-chat__font-metadata-emphasis); - } - - // 24px tall, as the design's compact text button - .str-chat__scheduled-message-preview__reschedule-button { - flex-shrink: 0; - padding-block: var(--str-chat__spacing-xxxs); - font: var(--str-chat__font-caption-emphasis); - } - } -} diff --git a/src/components/ScheduledMessages/styling/index.scss b/src/components/ScheduledMessages/styling/index.scss index 446614f1a9..6e20b67fea 100644 --- a/src/components/ScheduledMessages/styling/index.scss +++ b/src/components/ScheduledMessages/styling/index.scss @@ -1,6 +1,5 @@ @use 'ScheduledMessageActions'; @use 'ScheduledMessageList'; -@use 'ScheduledMessagePreview'; @use 'ScheduledMessagesBanner'; @use 'ScheduledMessagesNotice'; @use 'ScheduleMessageButton'; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts index 75f0e2af85..cad96bcdd5 100644 --- a/src/components/ScheduledMessages/utils.ts +++ b/src/components/ScheduledMessages/utils.ts @@ -30,6 +30,7 @@ export const SCHEDULED_MESSAGE_NOTIFICATION_TYPE = { deleteFailed: 'api:scheduled-message:delete:failed', sendNowFailed: 'api:scheduled-message:send-now:failed', sendNowSucceeded: 'api:scheduled-message:send-now:success', + sentNow: 'api:scheduled-message:create:sent-now', } as const; export const SCHEDULED_MESSAGES_EMITTER = 'ScheduledMessages'; @@ -51,6 +52,20 @@ export const getScheduleTimeDialogId = ({ export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) => status === SCHEDULED_MESSAGE_STATUS.Failed; +export const countPendingScheduledMessages = ( + scheduledMessages: ScheduledMessageResponse[] = [], +) => { + const pendingCount = scheduledMessages.filter( + ({ status }) => status === SCHEDULED_MESSAGE_STATUS.Scheduled, + ).length; + return pendingCount; +}; + +export const isScheduledMessageLimitReached = ( + pendingCount: number, + maxPerChannel?: number, +) => maxPerChannel !== undefined && pendingCount >= maxPerChannel; + /** A channel's list holds its replies too: a thread keeps its own, a channel its top-level ones. */ /** The default search: the text contains the query, ignoring case; a blank query matches all. */ export const matchesScheduledMessageText = ( diff --git a/src/i18n/__tests__/catalog.fixture.json b/src/i18n/__tests__/catalog.fixture.json index a71067ce95..9b9b192ae3 100644 --- a/src/i18n/__tests__/catalog.fixture.json +++ b/src/i18n/__tests__/catalog.fixture.json @@ -614,6 +614,8 @@ "reactions.messageReactionsDetail.tapRemove.text": "Tap to remove", "scheduledMessages.banner.failedToSend_one": "{{ count }} failed to send", "scheduledMessages.banner.failedToSend_other": "{{ count }} failed to send", + "scheduledMessages.banner.limitReached_one": "{{ scheduled }} of {{ count }} scheduled message", + "scheduledMessages.banner.limitReached_other": "{{ scheduled }} of {{ count }} scheduled messages", "scheduledMessages.banner.scheduledFor": "Scheduled for {{ time }}", "scheduledMessages.banner.scheduledMessages_one": "{{ count }} scheduled message", "scheduledMessages.banner.scheduledMessages_other": "{{ count }} scheduled messages", @@ -621,7 +623,6 @@ "scheduledMessages.banner.scheduledReplies_other": "{{ count }} scheduled replies", "scheduledMessages.blockedByModeration": "Blocked by moderation", "scheduledMessages.cancel": "Cancel", - "scheduledMessages.cancelEditing.ariaLabel": "Cancel editing", "scheduledMessages.cantSendInThisChannel": "Unavailable: you can't send messages in this channel", "scheduledMessages.channelFrozenNotice": "This channel is frozen. Scheduled messages won't be sent", "scheduledMessages.chooseALaterTime": "Choose a later time", @@ -641,6 +642,8 @@ "scheduledMessages.deleteScheduledMessage": "Delete scheduled message?", "scheduledMessages.edit": "Edit", "scheduledMessages.editReschedule": "Edit & reschedule", + "scheduledMessages.editScheduledMessage": "Edit scheduled message", + "scheduledMessages.limitReachedMax": "Limit reached ({{ max }} max)", "scheduledMessages.loaded": "Scheduled messages loaded", "scheduledMessages.loadingScheduledMessages": "Loading scheduled messages", "scheduledMessages.messageToName": "Message to {{ name }}", @@ -657,6 +660,7 @@ "scheduledMessages.notification.forbidden": "You can't schedule messages here", "scheduledMessages.notification.notEditable": "Failed messages can't be edited", "scheduledMessages.notification.sending": "This message is being sent", + "scheduledMessages.notification.sentNow": "Time passed. Message sent now", "scheduledMessages.notification.updateFailed": "Couldn't update the scheduled message. Try again", "scheduledMessages.notification.userLimit": "You've reached the limit of scheduled messages", "scheduledMessages.openScheduleMessageMenu.ariaLabel": "Open schedule message menu", @@ -686,14 +690,12 @@ "scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain": "This channel now needs approval. Schedule it again", "scheduledMessages.thisChannelWasDeleted": "This channel was deleted", "scheduledMessages.thisMessageToNameWontBeSentThis": "This message to {{ name }} won't be sent. This can't be undone.", - "scheduledMessages.thisMessageWillBeSentTime": "This message will be sent {{ time }}", "scheduledMessages.thisMessageWontBeSentThisCantBe": "This message won't be sent. This can't be undone.", "scheduledMessages.time": "Time", "scheduledMessages.view": "View", "scheduledMessages.viewAll": "View all", "scheduledMessages.youCantSendMessagesInThisChannel": "You can't send messages in this channel", "scheduledMessages.youreNoLongerAllowedToPostHere": "You're no longer allowed to post here", - "scheduledMessages.youreOfflineReconnectToScheduleThisMessage": "You're offline. Reconnect to schedule this message.", "search.bar.clearSearch.ariaLabel": "Clear search", "search.bar.exitSearch.ariaLabel": "Exit search", "search.resultItem.selectUserChannel.ariaLabel": "Select User Channel: {{ name }}", diff --git a/src/i18n/keys.ts b/src/i18n/keys.ts index 16b2b40dd1..d4f668f356 100644 --- a/src/i18n/keys.ts +++ b/src/i18n/keys.ts @@ -625,6 +625,8 @@ export type TranslationCatalog = { 'reactions.messageReactionsDetail.tapRemove.text': 'Tap to remove'; 'scheduledMessages.banner.failedToSend_one': '{{ count }} failed to send'; 'scheduledMessages.banner.failedToSend_other': '{{ count }} failed to send'; + 'scheduledMessages.banner.limitReached_one': '{{ scheduled }} of {{ count }} scheduled message'; + 'scheduledMessages.banner.limitReached_other': '{{ scheduled }} of {{ count }} scheduled messages'; 'scheduledMessages.banner.scheduledFor': 'Scheduled for {{ time }}'; 'scheduledMessages.banner.scheduledMessages_one': '{{ count }} scheduled message'; 'scheduledMessages.banner.scheduledMessages_other': '{{ count }} scheduled messages'; @@ -632,7 +634,6 @@ export type TranslationCatalog = { 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} scheduled replies'; 'scheduledMessages.blockedByModeration': 'Blocked by moderation'; 'scheduledMessages.cancel': 'Cancel'; - 'scheduledMessages.cancelEditing.ariaLabel': 'Cancel editing'; 'scheduledMessages.cantSendInThisChannel': "Unavailable: you can't send messages in this channel"; 'scheduledMessages.channelFrozenNotice': "This channel is frozen. Scheduled messages won't be sent"; 'scheduledMessages.chooseALaterTime': 'Choose a later time'; @@ -652,6 +653,8 @@ export type TranslationCatalog = { 'scheduledMessages.deleteScheduledMessage': 'Delete scheduled message?'; 'scheduledMessages.edit': 'Edit'; 'scheduledMessages.editReschedule': 'Edit & reschedule'; + 'scheduledMessages.editScheduledMessage': 'Edit scheduled message'; + 'scheduledMessages.limitReachedMax': 'Limit reached ({{ max }} max)'; 'scheduledMessages.loaded': 'Scheduled messages loaded'; 'scheduledMessages.loadingScheduledMessages': 'Loading scheduled messages'; 'scheduledMessages.messageToName': 'Message to {{ name }}'; @@ -668,6 +671,7 @@ export type TranslationCatalog = { 'scheduledMessages.notification.forbidden': "You can't schedule messages here"; 'scheduledMessages.notification.notEditable': "Failed messages can't be edited"; 'scheduledMessages.notification.sending': 'This message is being sent'; + 'scheduledMessages.notification.sentNow': 'Time passed. Message sent now'; 'scheduledMessages.notification.updateFailed': "Couldn't update the scheduled message. Try again"; 'scheduledMessages.notification.userLimit': "You've reached the limit of scheduled messages"; 'scheduledMessages.openScheduleMessageMenu.ariaLabel': 'Open schedule message menu'; @@ -697,14 +701,12 @@ export type TranslationCatalog = { 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain': 'This channel now needs approval. Schedule it again'; 'scheduledMessages.thisChannelWasDeleted': 'This channel was deleted'; 'scheduledMessages.thisMessageToNameWontBeSentThis': "This message to {{ name }} won't be sent. This can't be undone."; - 'scheduledMessages.thisMessageWillBeSentTime': 'This message will be sent {{ time }}'; 'scheduledMessages.thisMessageWontBeSentThisCantBe': "This message won't be sent. This can't be undone."; 'scheduledMessages.time': 'Time'; 'scheduledMessages.view': 'View'; 'scheduledMessages.viewAll': 'View all'; 'scheduledMessages.youCantSendMessagesInThisChannel': "You can't send messages in this channel"; 'scheduledMessages.youreNoLongerAllowedToPostHere': "You're no longer allowed to post here"; - 'scheduledMessages.youreOfflineReconnectToScheduleThisMessage': "You're offline. Reconnect to schedule this message."; 'search.bar.clearSearch.ariaLabel': 'Clear search'; 'search.bar.exitSearch.ariaLabel': 'Exit search'; 'search.resultItem.selectUserChannel.ariaLabel': 'Select User Channel: {{ name }}'; From c1dea9e27e2439d408eea25be595ab5fca88d7e8 Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Tue, 24 Nov 2026 16:47:33 +0100 Subject: [PATCH 16/35] feat(ScheduledMessages): add date, time and delete-confirmation slots - ScheduleDateInput and ScheduleTimeInput replace the dialog's DateInput and TimeInput props: ComponentContext slots whose defaults are the browser's own date and time pickers. A click anywhere in a native field still opens its picker. - ScheduledMessageDeleteAlert lets an app replace the delete confirmation without replacing the whole list item; it receives the channel name, onDelete and onCancel. - The three defaults are exported. --- .../ScheduledMessages/ScheduleDateInput.tsx | 41 ++++++++++ .../ScheduledMessages/ScheduleTimeDialog.tsx | 75 ++++--------------- .../ScheduledMessages/ScheduleTimeInput.tsx | 22 ++++++ .../ScheduledMessageDeleteAlert.tsx | 58 ++++++++++++++ .../ScheduledMessageItem.tsx | 64 ++++------------ .../__tests__/ScheduleMessageButton.test.tsx | 9 +-- .../ScheduledMessageActions.test.tsx | 26 +++++++ src/components/ScheduledMessages/index.ts | 3 + src/context/ComponentContext.tsx | 13 +++- 9 files changed, 189 insertions(+), 122 deletions(-) create mode 100644 src/components/ScheduledMessages/ScheduleDateInput.tsx create mode 100644 src/components/ScheduledMessages/ScheduleTimeInput.tsx create mode 100644 src/components/ScheduledMessages/ScheduledMessageDeleteAlert.tsx diff --git a/src/components/ScheduledMessages/ScheduleDateInput.tsx b/src/components/ScheduledMessages/ScheduleDateInput.tsx new file mode 100644 index 0000000000..a076c377ba --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleDateInput.tsx @@ -0,0 +1,41 @@ +import React from 'react'; + +import { useComponentContextIcons, useTranslationContext } from '../../context'; +import { TextInput } from '../Form'; +import type { ScheduleDateInputProps } from './ScheduleTimeDialog'; +import { fromInputValues } from './utils'; + +export const ScheduleDateInput = ({ + label, + max, + min, + onChange, + value, +}: ScheduleDateInputProps) => { + const { t } = useTranslationContext(); + const { IconCalendar, IconCaretDown } = useComponentContextIcons(); + + const selectedDate = fromInputValues(value); + + return ( + + + + {selectedDate && t('timestamp.ScheduleDate', { timestamp: selectedDate })} + + + } + max={max} + min={min} + onChange={({ target }) => onChange(target.value)} + required + trailing={} + type='date' + value={value} + /> + ); +}; diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx index f2a00c3276..453ddb1f18 100644 --- a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -1,14 +1,15 @@ -import React, { type ComponentType, type MouseEvent, useEffect, useState } from 'react'; +import React, { type MouseEvent, useEffect, useState } from 'react'; import type { Channel, LocalMessage } from 'stream-chat'; -import { useComponentContextIcons, useTranslationContext } from '../../context'; +import { useComponentContext, useTranslationContext } from '../../context'; import { useIsMounted } from '../Channel/hooks/useIsMounted'; import { useWSConnectionState } from '../Chat/hooks/useWSConnectionState'; import { useChannelDisplayName } from '../ChannelListItem/hooks/useChannelDisplayName'; import { Prompt } from '../Dialog'; -import { TextInput } from '../Form'; import { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; +import { ScheduleDateInput as DefaultScheduleDateInput } from './ScheduleDateInput'; import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; +import { ScheduleTimeInput as DefaultScheduleTimeInput } from './ScheduleTimeInput'; import { formatTimeZoneOffset, fromInputValues, @@ -47,14 +48,10 @@ export type ScheduleTimeDialogProps = { /** Closes the dialog once it resolves. */ submit: (scheduledAt: Date) => Promise; title: string; - /** Replaces the date field. */ - DateInput?: ComponentType; initialScheduledAt?: Date; /** Above the preview; "Message to {{ name }}" by default. */ previewLabel?: string; submitLabel?: string; - /** Replaces the time field. */ - TimeInput?: ComponentType; /** Why an earlier time is refused; "Choose a later time" by default. */ tooSoonMessage?: string; }; @@ -71,64 +68,16 @@ const useMinuteClock = () => { return [now, setNow] as const; }; -const DefaultScheduleDateInput = ({ - label, - max, - min, - onChange, - value, -}: ScheduleDateInputProps) => { - const { t } = useTranslationContext(); - const { IconCalendar, IconCaretDown } = useComponentContextIcons(); - const selectedDate = fromInputValues(value); - return ( - - - - {selectedDate && t('timestamp.ScheduleDate', { timestamp: selectedDate })} - - - } - max={max} - min={min} - onChange={({ target }) => onChange(target.value)} - required - trailing={} - type='date' - value={value} - /> - ); -}; - -const DefaultScheduleTimeInput = ({ label, onChange, value }: ScheduleTimeInputProps) => { - const { IconCaretDown, IconClock } = useComponentContextIcons(); - return ( - } - onChange={({ target }) => onChange(target.value)} - required - trailing={} - type='time' - value={value} - /> - ); -}; +const NATIVE_PICKER_INPUT_SELECTOR = 'input[type="date"], input[type="time"]'; -/** A click anywhere in a field, its icons included, opens the field's picker. */ const openNativePicker = ({ target }: MouseEvent) => { const input = (target as Element) .closest('.str-chat__form-text-input__wrapper') - ?.querySelector('input'); + ?.querySelector(NATIVE_PICKER_INPUT_SELECTOR); try { input?.showPicker?.(); } catch { - // not allowed outside a user gesture in some browsers + return; } }; @@ -136,18 +85,20 @@ const openNativePicker = ({ target }: MouseEvent) => { export const ScheduleTimeDialog = ({ channel, close, - DateInput = DefaultScheduleDateInput, errorMessage, initialScheduledAt, previewLabel, previewMessage, submit, submitLabel, - TimeInput = DefaultScheduleTimeInput, title, tooSoonMessage, }: ScheduleTimeDialogProps) => { const { t } = useTranslationContext(); + const { + ScheduleDateInput = DefaultScheduleDateInput, + ScheduleTimeInput = DefaultScheduleTimeInput, + } = useComponentContext(); const channelDisplayName = useChannelDisplayName(channel); const isOnline = useWSConnectionState()?.isHealthy ?? false; const isMounted = useIsMounted(); @@ -225,14 +176,14 @@ export const ScheduleTimeDialog = ({ className='str-chat__schedule-message-dialog__fields' onClick={openNativePicker} > - - { + const { IconCaretDown, IconClock } = useComponentContextIcons(); + + return ( + } + onChange={({ target }) => onChange(target.value)} + required + trailing={} + type='time' + value={value} + /> + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageDeleteAlert.tsx b/src/components/ScheduledMessages/ScheduledMessageDeleteAlert.tsx new file mode 100644 index 0000000000..67f609b707 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageDeleteAlert.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { useTranslationContext } from '../../context'; +import { Button } from '../Button'; +import { Alert } from '../Dialog'; + +export type ScheduledMessageDeleteAlertProps = { + onCancel: () => void; + onDelete: () => void; + scheduledMessage: ScheduledMessageResponse; + channelName?: string; +}; + +export const ScheduledMessageDeleteAlert = ({ + channelName, + onCancel, + onDelete, +}: ScheduledMessageDeleteAlertProps) => { + const { t } = useTranslationContext(); + + const description = channelName + ? t( + 'scheduledMessages.thisMessageToNameWontBeSentThis', + "This message to {{ name }} won't be sent. This can't be undone.", + { name: channelName }, + ) + : t( + 'scheduledMessages.thisMessageWontBeSentThisCantBe', + "This message won't be sent. This can't be undone.", + ); + + return ( + + + + + + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index 94d769f6c5..ec4dcae8c3 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -10,15 +10,9 @@ import { useTranslationContext, } from '../../context'; import { ChannelAvatar } from '../Avatar'; -import { Button } from '../Button'; import { useIsMounted } from '../Channel/hooks/useIsMounted'; import { useChannelPreviewInfo } from '../ChannelListItem/hooks/useChannelPreviewInfo'; -import { - Alert, - ContextMenu, - useDialogIsOpen, - useDialogOnNearestManager, -} from '../Dialog'; +import { ContextMenu, useDialogIsOpen, useDialogOnNearestManager } from '../Dialog'; import { useSplitActionSet } from '../Chat/hooks/useSplitActionSet'; import { GlobalModal } from '../Modal'; import { useNotificationApi } from '../Notifications'; @@ -29,6 +23,7 @@ import { VisuallyHidden } from '../VisuallyHidden'; import { SCHEDULE_MESSAGE_CAPABILITY } from './hooks'; import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; +import { ScheduledMessageDeleteAlert as DefaultScheduledMessageDeleteAlert } from './ScheduledMessageDeleteAlert'; import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; import { defaultScheduledMessageActionSet, @@ -75,8 +70,11 @@ export const ScheduledMessageItem = ({ const { t } = useTranslationContext(); const { client } = useChatContext(); const { IconExclamationTriangleFill, IconLoading } = useComponentContextIcons(); - const { Modal = GlobalModal, ScheduleTimeDialog = DefaultScheduleTimeDialog } = - useComponentContext(); + const { + Modal = GlobalModal, + ScheduledMessageDeleteAlert = DefaultScheduledMessageDeleteAlert, + ScheduleTimeDialog = DefaultScheduleTimeDialog, + } = useComponentContext(); const { addNotification } = useNotificationApi(); const isMounted = useIsMounted(); @@ -243,48 +241,12 @@ export const ScheduledMessageItem = ({ role='alertdialog' > {openDialog === 'delete' && ( - - - - - - - + )}
diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx index d37d6fdea3..9f2d9589f3 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -23,7 +23,6 @@ import { Channel } from '../../Channel'; import { Chat } from '../../Chat'; import { WithComponents } from '../../../context/WithComponents'; import { MessageComposer } from '../../MessageComposer'; -import { ScheduleTimeDialog } from '../ScheduleTimeDialog'; import { enterDate, enterTime, getDateField, getTimeField } from './scheduleTimeFields'; import type { ScheduleDateInputProps, @@ -586,7 +585,7 @@ describe('ScheduleMessageButton', () => { expect(screen.getByTestId('schedule-message-dialog')).toBeInTheDocument(); }); - it('takes custom date and time fields', async () => { + it('takes date and time fields from their slots', async () => { const DateInput = ({ onChange, value }: ScheduleDateInputProps) => ( { /> ); const { channel } = await renderComposer({ - components: { - ScheduleTimeDialog: (props) => ( - - ), - }, + components: { ScheduleDateInput: DateInput, ScheduleTimeInput: TimeInput }, }); const schedule = mockSchedule(channel).mockResolvedValue( scheduledResult(generateScheduledMessage({ cid: channel.cid })), diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index 843591c03e..fe3e3dc7c8 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -38,6 +38,7 @@ import { ScheduledMessageItem } from '../ScheduledMessageItem'; import type { ScheduledMessageItemProps } from '../ScheduledMessageItem'; import { defaultScheduledMessageActionSet } from '../ScheduledMessageActions'; import type { ScheduledMessageActionSetItem } from '../ScheduledMessageActions'; +import type { ScheduledMessageDeleteAlertProps } from '../ScheduledMessageDeleteAlert'; import { enterDate, enterTime, getDateField, getTimeField } from './scheduleTimeFields'; type OpenInComposer = NonNullable; @@ -308,6 +309,31 @@ describe('ScheduledMessageActions', () => { expect(deleteScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id); }); + it('asks with the ScheduledMessageDeleteAlert slot', async () => { + const CustomDeleteAlert = ({ + channelName, + onDelete, + }: ScheduledMessageDeleteAlertProps) => ( + + ); + const { client, scheduledMessage } = await renderActions({ + components: { ScheduledMessageDeleteAlert: CustomDeleteAlert }, + }); + const deleteScheduledMessage = vi + .spyOn(getChannel(client), 'deleteScheduledMessage') + .mockResolvedValue(scheduledMessage); + + await selectAction('delete'); + await act(() => fireEvent.click(screen.getByRole('button', { name: /Remove from/ }))); + + expect( + screen.queryByTestId('delete-scheduled-message-alert'), + ).not.toBeInTheDocument(); + expect(deleteScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id); + }); + it('keeps the message when the deletion is cancelled', async () => { const { client } = await renderActions(); const deleteScheduledMessage = vi.spyOn(getChannel(client), 'deleteScheduledMessage'); diff --git a/src/components/ScheduledMessages/index.ts b/src/components/ScheduledMessages/index.ts index b4ec7f6023..de7334a955 100644 --- a/src/components/ScheduledMessages/index.ts +++ b/src/components/ScheduledMessages/index.ts @@ -1,9 +1,12 @@ export * from './hooks'; export * from './ScheduledMessageActions'; +export * from './ScheduledMessageDeleteAlert'; export * from './ScheduledMessageItem'; export * from './ScheduledMessageList'; export * from './ScheduledMessageListDialog'; export * from './ScheduledMessagePreview'; export * from './ScheduledMessagesBanner'; +export * from './ScheduleDateInput'; export * from './ScheduleMessageButton'; export * from './ScheduleTimeDialog'; +export * from './ScheduleTimeInput'; diff --git a/src/context/ComponentContext.tsx b/src/context/ComponentContext.tsx index 51d85ca080..c8fe3b2aa5 100644 --- a/src/context/ComponentContext.tsx +++ b/src/context/ComponentContext.tsx @@ -82,11 +82,14 @@ import type { TypingIndicatorProps } from '../components/TypingIndicator'; import type { AttachmentUploadProgressIndicatorProps } from '../components/Attachment/components/AttachmentUploadProgressIndicator'; import type { IconSlots } from '../components/Icons/slots'; import type { + ScheduleDateInputProps, + ScheduledMessageDeleteAlertProps, ScheduledMessageItemProps, ScheduledMessageListDialogProps, ScheduledMessageListProps, ScheduledMessagePreviewProps, ScheduleTimeDialogProps, + ScheduleTimeInputProps, } from '../components/ScheduledMessages'; export type ComponentContextValue = { @@ -382,6 +385,8 @@ export type ComponentContextValue = { RecordingPermissionDeniedNotification?: React.ComponentType; /** Message reminder information in the message UI. */ ReminderNotification?: React.ComponentType; + /** Asks before a scheduled message is deleted, from its list item. */ + ScheduledMessageDeleteAlert?: React.ComponentType; /** One item of `ScheduledMessageList`. */ ScheduledMessageItem?: React.ComponentType; /** Scheduled messages in the banner's dialog and the Channel Detail section. */ @@ -397,11 +402,15 @@ export type ComponentContextValue = { ScheduledMessagesBanner?: React.ComponentType | null; /** Schedule button next to the send button; `null` hides it. */ ScheduleMessageButton?: React.ComponentType | null; + /** The date field of `ScheduleTimeDialog`; the browser's date picker by default. */ + ScheduleDateInput?: React.ComponentType; /** - * The dialog for picking a custom time, opened by the schedule button and by rescheduling. To - * replace only its date or time field, render the default with `DateInput` or `TimeInput`. + * The dialog for picking a custom time, opened by the schedule button and by rescheduling. Its + * date and time fields are the `ScheduleDateInput` and `ScheduleTimeInput` slots. */ ScheduleTimeDialog?: React.ComponentType; + /** The time field of `ScheduleTimeDialog`; the browser's time picker by default. */ + ScheduleTimeInput?: React.ComponentType; /** Translation indicator, shown when the message has `i18n`. */ MessageTranslationIndicator?: React.ComponentType; /** From 1f224161fd42e1da87a7f9e2f9321958672069c2 Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Tue, 24 Nov 2026 16:48:03 +0100 Subject: [PATCH 17/35] feat(ChannelDetail): open the channel's scheduled messages from the banner ScheduledMessagesChannelDetailDialog can be registered as the ScheduledMessageListDialog slot: the banner's "View" / "View all" then opens the channel details at their Scheduled section, as in the Figma designs. A thread's scheduled replies keep the default list dialog. ChannelDetail can be replaced, so an app passes its configured one. --- .../ScheduledMessagesChannelDetailDialog.tsx | 61 +++++++++ ...eduledMessagesChannelDetailDialog.test.tsx | 118 ++++++++++++++++++ src/plugins/ChannelDetail/index.ts | 1 + 3 files changed, 180 insertions(+) create mode 100644 src/plugins/ChannelDetail/ScheduledMessagesChannelDetailDialog.tsx create mode 100644 src/plugins/ChannelDetail/__tests__/ScheduledMessagesChannelDetailDialog.test.tsx diff --git a/src/plugins/ChannelDetail/ScheduledMessagesChannelDetailDialog.tsx b/src/plugins/ChannelDetail/ScheduledMessagesChannelDetailDialog.tsx new file mode 100644 index 0000000000..1bee48f3f2 --- /dev/null +++ b/src/plugins/ChannelDetail/ScheduledMessagesChannelDetailDialog.tsx @@ -0,0 +1,61 @@ +import React from 'react'; +import type { ComponentType } from 'react'; + +import { useComponentContext, useTranslationContext } from '../../context'; +import { useMessageComposerController } from '../../components/MessageComposer/hooks/useMessageComposerController'; +import { GlobalModal } from '../../components/Modal'; +import { + ScheduledMessageListDialog, + type ScheduledMessageListDialogProps, +} from '../../components/ScheduledMessages'; +import { + type ChannelDetailProps, + ChannelDetail as DefaultChannelDetail, +} from './ChannelDetail'; +import type { SectionNavigatorRoute } from './SectionNavigator'; + +export type ScheduledMessagesChannelDetailDialogProps = + ScheduledMessageListDialogProps & { + ChannelDetail?: ComponentType; + }; + +const scheduledMessagesSectionHistory: SectionNavigatorRoute[] = [ + { id: 'scheduled-messages' }, +]; + +const channelDetailDialogRootProps = { + className: 'str-chat__channel-detail-modal', +}; + +export const ScheduledMessagesChannelDetailDialog = ({ + ChannelDetail = DefaultChannelDetail, + ...dialogProps +}: ScheduledMessagesChannelDetailDialogProps) => { + const { t } = useTranslationContext(); + const { Modal = GlobalModal } = useComponentContext(); + + const { channel } = useMessageComposerController(); + + const { close, open, scheduledMessages } = dialogProps; + + if (scheduledMessages.parentId) return ; + + return ( + + {open && ( + + )} + + ); +}; diff --git a/src/plugins/ChannelDetail/__tests__/ScheduledMessagesChannelDetailDialog.test.tsx b/src/plugins/ChannelDetail/__tests__/ScheduledMessagesChannelDetailDialog.test.tsx new file mode 100644 index 0000000000..e9cccbd320 --- /dev/null +++ b/src/plugins/ChannelDetail/__tests__/ScheduledMessagesChannelDetailDialog.test.tsx @@ -0,0 +1,118 @@ +import '../../..'; +import React from 'react'; +import type { PropsWithChildren } from 'react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { formatMessage, Thread } from 'stream-chat'; + +import { Channel } from '../../../components/Channel'; +import { Chat } from '../../../components/Chat'; +import { MessageComposer } from '../../../components/MessageComposer'; +import { ThreadProvider } from '../../../components/Threads'; +import { WithComponents } from '../../../context/WithComponents'; +import { + generateMessage, + generateScheduledMessage, + generateUser, + initClientWithChannels, +} from '../../../mock-builders'; +import type { ChannelDetailProps } from '../ChannelDetail'; +import { ScheduledMessagesChannelDetailDialog } from '../ScheduledMessagesChannelDetailDialog'; +import type { ScheduledMessageListDialogProps } from '../../../components/ScheduledMessages'; + +const cid = 'messaging:general'; +const parentId = 'parent-1'; + +const ChannelDetailStub = ({ channel, initialHistory }: ChannelDetailProps) => ( +
+ {channel.cid} {initialHistory?.map(({ id }) => id).join(',')} +
+); + +const ListDialog = (props: ScheduledMessageListDialogProps) => ( + +); + +const renderComposer = async ({ inThread = false } = {}) => { + const { + channels: [channel], + client, + } = await initClientWithChannels({ + channelsData: [ + { + channel: { + id: 'general', + own_capabilities: ['send-message', 'schedule-message'], + type: 'messaging', + }, + }, + ], + customUser: generateUser({ id: 'user-id' }), + }); + const scheduledMessage = generateScheduledMessage({ + cid, + message: inThread + ? { custom: {}, parent_id: parentId, text: 'reply' } + : { custom: {}, text: 'Launch moved to Monday' }, + }); + vi.spyOn(client, 'queryScheduledMessages').mockResolvedValue( + fromPartial({ duration: '', scheduled_messages: [scheduledMessage] }), + ); + const thread = inThread + ? new Thread({ + channel, + client, + parentMessage: formatMessage(generateMessage({ cid, id: parentId })), + }) + : undefined; + const ThreadScope = ({ children }: PropsWithChildren) => + thread ? {children} : children; + + await act(() => { + render( + + + + + + + + + , + ); + }); + + const viewButton = await screen.findByRole('button', { name: 'View' }); + return { viewButton }; +}; + +describe('ScheduledMessagesChannelDetailDialog', () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it('opens the channel details at the scheduled messages section', async () => { + const { viewButton } = await renderComposer(); + + expect(screen.queryByTestId('channel-detail')).not.toBeInTheDocument(); + await act(() => fireEvent.click(viewButton)); + + expect(await screen.findByTestId('channel-detail')).toHaveTextContent( + `${cid} scheduled-messages`, + ); + }); + + it("lists a thread's scheduled replies in the list dialog", async () => { + const { viewButton } = await renderComposer({ inThread: true }); + + await act(() => fireEvent.click(viewButton)); + + await waitFor(() => + expect(screen.getByTestId('scheduled-message-list-dialog')).toHaveTextContent( + 'Scheduled replies', + ), + ); + expect(screen.queryByTestId('channel-detail')).not.toBeInTheDocument(); + }); +}); diff --git a/src/plugins/ChannelDetail/index.ts b/src/plugins/ChannelDetail/index.ts index a5808f5d65..77055e470e 100644 --- a/src/plugins/ChannelDetail/index.ts +++ b/src/plugins/ChannelDetail/index.ts @@ -9,6 +9,7 @@ export { export * from './ListStates.deprecated'; export * from './ChannelDetailNavButton'; export * from './ChannelDetailSearchInput'; +export * from './ScheduledMessagesChannelDetailDialog'; export * from './SectionNavigator'; export * from './Views/ChannelManagementView/ChannelManagementView'; export * from './Views/ChannelManagementView/ChannelManagementActions.defaults'; From 3d36a66b6401afd9a02a0cc4ab17e42fdc13fffb Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Tue, 24 Nov 2026 16:48:25 +0100 Subject: [PATCH 18/35] chore(examples): show the Figma scheduled-message pickers in the vite example - The banner's "View all" opens the channel details at their Scheduled section (ScheduledMessagesChannelDetailDialog with the configured ChannelDetail). - ScheduledMessages/ registers the Figma pickers through the SDK slots: CalendarDateInput (type a date such as "Nov 4", or pick it from a calendar that starts on Monday), TimeComboboxInput (times every 15 minutes, narrowed as a time is typed) and ConfirmScheduledMessageDelete. - react-aria, react-stately and @internationalized/date are dependencies of the example only, pinned to the versions @react-aria/focus installs. - The German and Italian dictionaries cover the scheduled-message keys. --- examples/vite/package.json | 3 + examples/vite/src/App.tsx | 10 + .../ChatLayout/ConfiguredChannelDetail.tsx | 11 + .../ScheduledMessages/CalendarDateInput.tsx | 241 ++++++++++++++++++ .../ConfirmScheduledMessageDelete.tsx | 56 ++++ .../src/ScheduledMessages/DateCalendar.tsx | 219 ++++++++++++++++ .../ScheduledMessagePickers.scss | 148 +++++++++++ .../ScheduledMessages/TimeComboboxInput.tsx | 231 +++++++++++++++++ .../src/ScheduledMessages/dateTimeText.ts | 106 ++++++++ examples/vite/src/ScheduledMessages/index.ts | 3 + examples/vite/src/i18n/de.ts | 112 ++++++++ examples/vite/src/i18n/it.ts | 112 ++++++++ examples/vite/src/index.scss | 2 + yarn.lock | 3 + 14 files changed, 1257 insertions(+) create mode 100644 examples/vite/src/ScheduledMessages/CalendarDateInput.tsx create mode 100644 examples/vite/src/ScheduledMessages/ConfirmScheduledMessageDelete.tsx create mode 100644 examples/vite/src/ScheduledMessages/DateCalendar.tsx create mode 100644 examples/vite/src/ScheduledMessages/ScheduledMessagePickers.scss create mode 100644 examples/vite/src/ScheduledMessages/TimeComboboxInput.tsx create mode 100644 examples/vite/src/ScheduledMessages/dateTimeText.ts create mode 100644 examples/vite/src/ScheduledMessages/index.ts diff --git a/examples/vite/package.json b/examples/vite/package.json index 2cc3f660e1..5c022a5f35 100644 --- a/examples/vite/package.json +++ b/examples/vite/package.json @@ -10,6 +10,7 @@ }, "dependencies": { "@emoji-mart/data": "^1.2.1", + "@internationalized/date": "^3.12.1", "@stream-io/state-store": "^1.2.0", "clsx": "^2.1.1", "dayjs": "^1.11.23", @@ -17,7 +18,9 @@ "human-id": "^4.1.3", "modern-normalize": "^3.0.1", "react": "^19.2.6", + "react-aria": "3.48.0", "react-dom": "^19.2.6", + "react-stately": "3.46.0", "stream-chat": "^10.2.0", "stream-chat-react": "workspace:^" }, diff --git a/examples/vite/src/App.tsx b/examples/vite/src/App.tsx index a27d568550..7e365f04e5 100644 --- a/examples/vite/src/App.tsx +++ b/examples/vite/src/App.tsx @@ -57,6 +57,12 @@ import { import { ChatSkipNavigation } from './AccessibilityNavigation/ChatSkipNavigation.tsx'; import { SlotGeometryProvider } from 'stream-chat-react/slot-geometry'; import { AlsoSentInChannelIndicator } from './ChatLayout/AlsoSentInChannelIndicator.tsx'; +import { ConfiguredScheduledMessageListDialog } from './ChatLayout/ConfiguredChannelDetail.tsx'; +import { + CalendarDateInput, + ConfirmScheduledMessageDelete, + TimeComboboxInput, +} from './ScheduledMessages'; import { useAdditiveWorkspaceNavigation } from './ChatLayout/useAdditiveWorkspaceNavigation.ts'; import { ChannelsPanels, ThreadsPanels } from './ChatLayout/Panels.tsx'; import { SidebarProvider } from './ChatLayout/SidebarContext.tsx'; @@ -703,6 +709,10 @@ const App = () => { MessageComposerPreviews: ConfigurableComposerPreviews, PollCreationDialogControls: ConfigurablePollCreationDialogControls, ScheduledMessageItem: ConfigurableScheduledMessageItem, + ScheduledMessageListDialog: ConfiguredScheduledMessageListDialog, + ScheduledMessageDeleteAlert: ConfirmScheduledMessageDelete, + ScheduleDateInput: CalendarDateInput, + ScheduleTimeInput: TimeComboboxInput, StartRecordingAudioButton: ConfigurableStartRecordingAudioButton, MessageUI: InlineEditableMessage, ...messageUiOverrides, diff --git a/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx b/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx index b54d8f3f60..abbe4e4cf6 100644 --- a/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx +++ b/examples/vite/src/ChatLayout/ConfiguredChannelDetail.tsx @@ -4,6 +4,7 @@ import { asDynamicKey, ChannelAvatar, type ChannelAvatarProps, + type ScheduledMessageListDialogProps, useChannel, useTranslationContext, } from 'stream-chat-react'; @@ -17,6 +18,7 @@ import { ChannelMembersView, type ChannelMembersViewModes, defaultChannelDetailSections, + ScheduledMessagesChannelDetailDialog, type SectionNavigatorSection, type SectionNavigatorSectionContentProps, } from 'stream-chat-react/channel-detail'; @@ -128,3 +130,12 @@ export const ConfiguredAvatarWithChannelDetail = ( ChannelDetail={ConfiguredChannelDetail} /> ); + +export const ConfiguredScheduledMessageListDialog = ( + props: ScheduledMessageListDialogProps, +) => ( + +); diff --git a/examples/vite/src/ScheduledMessages/CalendarDateInput.tsx b/examples/vite/src/ScheduledMessages/CalendarDateInput.tsx new file mode 100644 index 0000000000..e0a36948bd --- /dev/null +++ b/examples/vite/src/ScheduledMessages/CalendarDateInput.tsx @@ -0,0 +1,241 @@ +import clsx from 'clsx'; +import { + type ChangeEvent, + type FocusEvent, + type KeyboardEvent, + useCallback, + useEffect, + useId, + useMemo, + useRef, + useState, +} from 'react'; +import { type CalendarDate, parseDate } from '@internationalized/date'; +import { I18nProvider } from 'react-aria'; +import { + DialogAnchor, + type ScheduleDateInputProps, + TextInput, + useComponentContextIcons, + useDialogIsOpen, + useDialogOnNearestManager, + useTranslationContext, +} from 'stream-chat-react'; + +import { DateCalendar } from './DateCalendar'; +import { fromDateValue, parseDateText } from './dateTimeText'; + +const FIELD_WRAPPER_SELECTOR = '.str-chat__form-text-input__wrapper'; +const FOCUSED_DAY_SELECTOR = '[role="grid"] [tabindex="0"]'; +const DEFAULT_LOCALE = 'en'; + +const toCalendarDate = (dateValue?: string) => { + try { + return dateValue ? parseDate(dateValue) : undefined; + } catch { + return undefined; + } +}; + +const isFocusWithin = (element: Element | null, target: EventTarget | null) => + !!element && target instanceof Node && element.contains(target); + +const CalendarDateField = ({ + label, + max, + min, + onChange, + value, +}: ScheduleDateInputProps) => { + const { t, userLanguage } = useTranslationContext(); + const { IconCalendar, IconCaretDown } = useComponentContextIcons(); + const locale = userLanguage || DEFAULT_LOCALE; + + const calendarId = useId(); + const dialogId = `app-schedule-date-calendar-${calendarId}`; + const { dialog, dialogManager } = useDialogOnNearestManager({ id: dialogId }); + const isOpen = useDialogIsOpen(dialogId, dialogManager?.id); + + const [typedText, setTypedText] = useState(); + const [browsedMonthDay, setBrowsedMonthDay] = useState(); + const [shouldFocusCalendar, setShouldFocusCalendar] = useState(false); + const [fieldElement, setFieldElement] = useState(null); + const inputRef = useRef(null); + const calendarRef = useRef(null); + + const earliestDate = fromDateValue(min); + const typedDateValue = + typedText !== undefined && earliestDate + ? parseDateText(typedText, locale, earliestDate) + : undefined; + const selectedDate = fromDateValue(value); + const displayValue = selectedDate + ? t('timestamp.ScheduleDate', { timestamp: selectedDate }) + : ''; + const minValue = useMemo(() => toCalendarDate(min), [min]); + const maxValue = useMemo(() => toCalendarDate(max), [max]); + const calendarValue = useMemo( + () => toCalendarDate(typedDateValue ?? value), + [typedDateValue, value], + ); + const focusedValue = browsedMonthDay ?? calendarValue ?? minValue; + + const setInputElement = useCallback((element: HTMLInputElement | null) => { + inputRef.current = element; + setFieldElement(element?.closest(FIELD_WRAPPER_SELECTOR) ?? null); + }, []); + + const openCalendar = useCallback( + (focusCalendar: boolean) => { + setShouldFocusCalendar(focusCalendar); + setBrowsedMonthDay(undefined); + dialog.open(); + }, + [dialog], + ); + + const closeCalendar = useCallback(() => { + setTypedText(undefined); + dialog.close(); + }, [dialog]); + + const commitTypedDate = useCallback(() => { + if (typedDateValue && typedDateValue !== value) onChange(typedDateValue); + setTypedText(undefined); + }, [onChange, typedDateValue, value]); + + const selectDay = useCallback( + (day: CalendarDate) => { + onChange(day.toString()); + closeCalendar(); + inputRef.current?.focus(); + }, + [closeCalendar, onChange], + ); + + const handleInputChange = useCallback( + ({ target }: ChangeEvent) => { + setTypedText(target.value); + setBrowsedMonthDay(undefined); + if (!isOpen) openCalendar(false); + }, + [isOpen, openCalendar], + ); + + const handleInputKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === 'ArrowDown') { + event.preventDefault(); + if (!isOpen) { + openCalendar(true); + return; + } + calendarRef.current?.querySelector(FOCUSED_DAY_SELECTOR)?.focus(); + return; + } + if (event.key === 'Enter') { + event.preventDefault(); + commitTypedDate(); + dialog.close(); + return; + } + if (event.key === 'Escape' && (isOpen || typedText !== undefined)) { + event.preventDefault(); + closeCalendar(); + } + }, + [closeCalendar, commitTypedDate, dialog, isOpen, openCalendar, typedText], + ); + + const handleInputBlur = useCallback( + ({ relatedTarget }: FocusEvent) => { + if (isFocusWithin(calendarRef.current, relatedTarget)) return; + commitTypedDate(); + dialog.close(); + }, + [commitTypedDate, dialog], + ); + + const handleCalendarBlur = useCallback( + ({ currentTarget, relatedTarget }: FocusEvent) => { + if (isFocusWithin(currentTarget, relatedTarget)) return; + if (relatedTarget === inputRef.current) return; + closeCalendar(); + }, + [closeCalendar], + ); + + const returnFocusToInput = useCallback(() => { + closeCalendar(); + inputRef.current?.focus(); + }, [closeCalendar]); + + useEffect(() => () => dialogManager?.close(dialogId), [dialogId, dialogManager]); + + return ( + <> + } + onBlur={handleInputBlur} + onChange={handleInputChange} + onClick={() => { + if (!isOpen) openCalendar(false); + }} + onKeyDown={handleInputKeyDown} + ref={setInputElement} + required + role='combobox' + trailing={} + value={typedText ?? displayValue} + /> + + {minValue && focusedValue && ( +
+ +
+ )} +
+ + ); +}; + +/** The Figma date field: typing a date, or picking it from a calendar that starts on Monday. */ +export const CalendarDateInput = (props: ScheduleDateInputProps) => { + const { userLanguage } = useTranslationContext(); + return ( + + + + ); +}; diff --git a/examples/vite/src/ScheduledMessages/ConfirmScheduledMessageDelete.tsx b/examples/vite/src/ScheduledMessages/ConfirmScheduledMessageDelete.tsx new file mode 100644 index 0000000000..a23a08ad77 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/ConfirmScheduledMessageDelete.tsx @@ -0,0 +1,56 @@ +import { + Alert, + asDynamicKey, + Button, + type ScheduledMessageDeleteAlertProps, + useTranslationContext, +} from 'stream-chat-react'; + +/** The Figma delete confirmation for a scheduled message, registered as `ScheduledMessageDeleteAlert`. */ +export const ConfirmScheduledMessageDelete = ({ + channelName, + onCancel, + onDelete, +}: ScheduledMessageDeleteAlertProps) => { + const { t } = useTranslationContext(); + + const description = channelName + ? t( + asDynamicKey('viteExample.scheduledMessages.deleteAlert.descriptionWithName'), + "This message to {{ name }} won't be sent. This can't be undone.", + { name: channelName }, + ) + : t( + asDynamicKey('viteExample.scheduledMessages.deleteAlert.description'), + "This message won't be sent. This can't be undone.", + ); + + return ( + + + + + + + + ); +}; diff --git a/examples/vite/src/ScheduledMessages/DateCalendar.tsx b/examples/vite/src/ScheduledMessages/DateCalendar.tsx new file mode 100644 index 0000000000..6d2caf0ba3 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/DateCalendar.tsx @@ -0,0 +1,219 @@ +import clsx from 'clsx'; +import { type FocusEvent, type KeyboardEvent, type ReactNode, useRef } from 'react'; +import { + type CalendarDate, + createCalendar, + getLocalTimeZone, + isToday, +} from '@internationalized/date'; +import { + type AriaButtonProps, + mergeProps, + useButton, + useCalendar, + useCalendarCell, + useCalendarGrid, + useLocale, +} from 'react-aria'; +import { type CalendarState, useCalendarState } from 'react-stately'; +import { + asDynamicKey, + Button, + isDayOrMoment, + useComponentContextIcons, + useTranslationContext, +} from 'stream-chat-react'; + +const FIRST_DAY_OF_WEEK = 'mon'; +const WEEKDAY_FORMAT = 'dd'; + +export type DateCalendarProps = { + autoFocus: boolean; + focusedValue: CalendarDate; + minValue: CalendarDate; + onBlur: (event: FocusEvent) => void; + onClose: () => void; + onFocusChange: (day: CalendarDate) => void; + onSelect: (day: CalendarDate) => void; + maxValue?: CalendarDate; + value?: CalendarDate; +}; + +type CalendarNavButtonProps = { + ariaButtonProps: AriaButtonProps; + children: ReactNode; + label: string; +}; + +type CalendarDayProps = { + date: CalendarDate; + state: CalendarState; +}; + +const CalendarNavButton = ({ + ariaButtonProps, + children, + label, +}: CalendarNavButtonProps) => { + const ref = useRef(null); + const { buttonProps } = useButton(ariaButtonProps, ref); + + return ( + + ); +}; + +const CalendarDay = ({ date, state }: CalendarDayProps) => { + const ref = useRef(null); + const { + buttonProps, + cellProps, + formattedDate, + isDisabled, + isOutsideVisibleRange, + isSelected, + isUnavailable, + } = useCalendarCell({ date }, state, ref); + + return ( + +
+ {formattedDate} +
+ + ); +}; + +const CalendarGrid = ({ state }: { state: CalendarState }) => { + const { tDateTimeParser } = useTranslationContext(); + const { gridProps, headerProps, weeksInMonth } = useCalendarGrid( + { firstDayOfWeek: FIRST_DAY_OF_WEEK }, + state, + ); + + const weekIndexes = Array.from({ length: weeksInMonth }, (_, weekIndex) => weekIndex); + const weekDays = state.getDatesInWeek(0).map((date) => { + if (!date) return ''; + const parsedDate = tDateTimeParser(date.toDate(getLocalTimeZone())); + return isDayOrMoment(parsedDate) ? parsedDate.format(WEEKDAY_FORMAT) : ''; + }); + + return ( + + + + {weekDays.map((weekDay, dayIndex) => ( + + ))} + + + + {weekIndexes.map((weekIndex) => ( + + {state + .getDatesInWeek(weekIndex) + .map((date, dayIndex) => + date ? ( + + ) : ( + + ))} + +
+ {weekDay} +
+ ), + )} +
+ ); +}; + +export const DateCalendar = ({ + autoFocus, + focusedValue, + maxValue, + minValue, + onBlur, + onClose, + onFocusChange, + onSelect, + value, +}: DateCalendarProps) => { + const { t } = useTranslationContext(); + const { IconChevronLeft, IconChevronRight } = useComponentContextIcons(); + const { locale } = useLocale(); + + const calendarOptions = { + autoFocus, + firstDayOfWeek: FIRST_DAY_OF_WEEK, + focusedValue, + maxValue, + minValue, + onChange: onSelect, + onFocusChange, + value, + } as const; + const state = useCalendarState({ ...calendarOptions, createCalendar, locale }); + const { calendarProps, nextButtonProps, prevButtonProps, title } = useCalendar( + calendarOptions, + state, + ); + + const closeOnEscape = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return; + event.preventDefault(); + onClose(); + }; + + return ( +
+
+ + + + {title} + + + +
+ +
+ ); +}; diff --git a/examples/vite/src/ScheduledMessages/ScheduledMessagePickers.scss b/examples/vite/src/ScheduledMessages/ScheduledMessagePickers.scss new file mode 100644 index 0000000000..f596829fea --- /dev/null +++ b/examples/vite/src/ScheduledMessages/ScheduledMessagePickers.scss @@ -0,0 +1,148 @@ +// The Figma date and time pickers (CalendarDateInput, TimeComboboxInput) and delete confirmation +// (ConfirmScheduledMessageDelete), registered in App.tsx through the SDK's scheduled-message slots. +@mixin picker-surface { + box-sizing: border-box; + border-radius: var(--str-chat__radius-lg); + background: var(--str-chat__background-core-elevation-2); + box-shadow: var(--str-chat__box-shadow-3); + color: var(--str-chat__text-primary); +} + +.app__schedule-field { + .str-chat__form-text-input__input { + min-width: 0; + font: var(--str-chat__font-caption-default); + } + + &.app__schedule-field--open .str-chat__form-text-input__trailing svg { + transform: rotate(180deg); + } +} + +.app__schedule-time-popover { + @include picker-surface; +} + +.app__schedule-time-options { + position: relative; + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: var(--str-chat__spacing-xxxs); + max-height: 278px; + margin: 0; + padding: var(--str-chat__spacing-xxs); + overflow-y: auto; + overscroll-behavior: contain; + list-style: none; +} + +.app__schedule-time-option { + flex-shrink: 0; + padding: var(--str-chat__spacing-xs); + border-radius: var(--str-chat__radius-md); + cursor: pointer; + font: var(--str-chat__font-caption-emphasis); + + &[aria-selected='true'] { + color: var(--str-chat__accent-primary); + } + + &.app__schedule-time-option--active { + background-color: var(--str-chat__background-utility-hover); + } +} + +.app__schedule-calendar-popover { + @include picker-surface; + width: 276px; + padding: var(--str-chat__spacing-sm); +} + +.app__schedule-calendar { + display: flex; + flex-direction: column; + gap: var(--str-chat__spacing-xs); + + .app__schedule-calendar__header { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-xxs); + } + + .app__schedule-calendar__month { + flex: 1; + font: var(--str-chat__font-caption-emphasis); + text-align: center; + } + + .app__schedule-calendar__grid { + width: 100%; + border-collapse: collapse; + table-layout: fixed; + + th, + td { + padding: 0; + text-align: center; + } + } + + .app__schedule-calendar__weekday { + padding-block-end: var(--str-chat__spacing-xxs); + color: var(--str-chat__text-tertiary); + font: var(--str-chat__font-metadata-default); + } + + .app__schedule-calendar__day { + display: flex; + align-items: center; + justify-content: center; + margin-inline: auto; + width: var(--str-chat__button-visual-height-sm); + height: var(--str-chat__button-visual-height-sm); + border-radius: var(--str-chat__radius-max); + color: var(--str-chat__text-primary); + cursor: pointer; + font: var(--str-chat__font-caption-default); + + &:hover { + background-color: var(--str-chat__background-utility-hover); + } + + &:focus-visible { + outline: 2px solid var(--str-chat__border-utility-focused); + outline-offset: 2px; + } + + &.app__schedule-calendar__day--outside-month { + color: var(--str-chat__text-tertiary); + } + + &.app__schedule-calendar__day--today { + box-shadow: inset 0 0 0 1px var(--str-chat__accent-primary); + color: var(--str-chat__accent-primary); + font: var(--str-chat__font-caption-emphasis); + } + + &.app__schedule-calendar__day--selected { + background-color: var(--str-chat__accent-primary); + color: var(--str-chat__text-on-accent); + font: var(--str-chat__font-caption-emphasis); + } + + &.app__schedule-calendar__day--unavailable { + background-color: transparent; + color: var(--str-chat__text-disabled); + cursor: not-allowed; + } + } +} + +.app__schedule-delete-alert { + max-width: 300px; + + .str-chat__alert-header__description { + color: var(--str-chat__text-secondary); + } +} diff --git a/examples/vite/src/ScheduledMessages/TimeComboboxInput.tsx b/examples/vite/src/ScheduledMessages/TimeComboboxInput.tsx new file mode 100644 index 0000000000..efb9c51fc0 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/TimeComboboxInput.tsx @@ -0,0 +1,231 @@ +import clsx from 'clsx'; +import { + type KeyboardEvent, + type RefObject, + useCallback, + useEffect, + useId, + useMemo, + useRef, + useState, +} from 'react'; +import { + type AriaListBoxOptions, + I18nProvider, + mergeProps, + useComboBox, + useFilter, + useListBox, + useOption, +} from 'react-aria'; +import { + type ComboBoxState, + Item, + type Key, + type Node, + useComboBoxState, +} from 'react-stately'; +import { + DialogAnchor, + type ScheduleTimeInputProps, + TextInput, + useComponentContextIcons, + useDialogOnNearestManager, + useTranslationContext, +} from 'stream-chat-react'; + +import { getTimeOptions, parseTimeText, withTimeOption } from './dateTimeText'; + +const TIME_OPTION_INTERVAL_MINUTES = 15; +const FIELD_WRAPPER_SELECTOR = '.str-chat__form-text-input__wrapper'; +const DEFAULT_LOCALE = 'en'; + +type TimeOption = { id: string }; + +type TimeOptionListProps = { + listBoxProps: AriaListBoxOptions; + listBoxRef: RefObject; + state: ComboBoxState; + width?: number; +}; + +type TimeOptionItemProps = { + item: Node; + state: ComboBoxState; +}; + +const timeOptions = getTimeOptions(TIME_OPTION_INTERVAL_MINUTES); + +const renderTimeOption = ({ id }: TimeOption) => {id}; + +const withoutLeadingZero = (time: string) => time.replace(/^0/, ''); + +const TimeOptionItem = ({ item, state }: TimeOptionItemProps) => { + const ref = useRef(null); + const { isFocused, optionProps } = useOption({ key: item.key }, state, ref); + + return ( +
  • + {item.rendered} +
  • + ); +}; + +const TimeOptionList = ({ + listBoxProps, + listBoxRef, + state, + width, +}: TimeOptionListProps) => { + const { listBoxProps: listBoxDomProps } = useListBox(listBoxProps, state, listBoxRef); + + useEffect(() => { + const listBox = listBoxRef.current; + const selectedOption = listBox?.querySelector('[aria-selected="true"]'); + if (!listBox || !selectedOption) return; + listBox.scrollTop = + selectedOption.offsetTop - (listBox.clientHeight - selectedOption.offsetHeight) / 2; + }, [listBoxRef]); + + return ( +
      + {[...state.collection].map((item) => ( + + ))} +
    + ); +}; + +const TimeComboboxField = ({ label, onChange, value }: ScheduleTimeInputProps) => { + const { IconCaretDown, IconClock } = useComponentContextIcons(); + const { startsWith } = useFilter({ sensitivity: 'base' }); + + const listboxId = useId(); + const dialogId = `app-schedule-time-options-${listboxId}`; + const { dialogManager } = useDialogOnNearestManager({ id: dialogId }); + + const [fieldElement, setFieldElement] = useState(null); + const inputRef = useRef(null); + const listBoxRef = useRef(null); + const popoverRef = useRef(null); + + const matchesTypedText = useCallback( + (time: string, text: string) => + startsWith(time, text) || startsWith(withoutLeadingZero(time), text), + [startsWith], + ); + + const items = useMemo( + () => withTimeOption(timeOptions, value).map((time) => ({ id: time })), + [value], + ); + + const selectTime = useCallback( + (key: Key | null) => { + if (key !== null) onChange(String(key)); + }, + [onChange], + ); + + const commitTypedTime = useCallback(() => { + const parsedTime = parseTimeText(inputRef.current?.value ?? ''); + if (parsedTime && parsedTime !== value) onChange(parsedTime); + }, [onChange, value]); + + const comboBoxOptions = { + 'aria-label': label, + defaultFilter: matchesTypedText, + defaultItems: items, + menuTrigger: 'focus' as const, + onBlur: commitTypedTime, + onSelectionChange: selectTime, + selectedKey: value, + }; + const state = useComboBoxState({ ...comboBoxOptions, children: renderTimeOption }); + const { inputProps, listBoxProps } = useComboBox( + { ...comboBoxOptions, inputRef, listBoxRef, popoverRef }, + state, + ); + + const setInputElement = useCallback((element: HTMLInputElement | null) => { + inputRef.current = element; + setFieldElement(element?.closest(FIELD_WRAPPER_SELECTOR) ?? null); + }, []); + + const keepEscapeInList = (event: KeyboardEvent) => { + if (event.key === 'Escape' && state.isOpen) event.preventDefault(); + }; + + const openList = () => { + if (!state.isOpen) state.open(null, 'manual'); + }; + + useEffect(() => { + if (!dialogManager) return; + if (state.isOpen) dialogManager.open({ id: dialogId }); + else dialogManager.close(dialogId); + }, [dialogId, dialogManager, state.isOpen]); + + useEffect(() => () => dialogManager?.close(dialogId), [dialogId, dialogManager]); + + return ( + <> + } + ref={setInputElement} + required + trailing={} + /> + +
    + +
    +
    + + ); +}; + +/** The Figma time field: a list of times every 15 minutes that narrows as a time is typed. */ +export const TimeComboboxInput = (props: ScheduleTimeInputProps) => { + const { userLanguage } = useTranslationContext(); + return ( + + + + ); +}; diff --git a/examples/vite/src/ScheduledMessages/dateTimeText.ts b/examples/vite/src/ScheduledMessages/dateTimeText.ts new file mode 100644 index 0000000000..69effa22a4 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/dateTimeText.ts @@ -0,0 +1,106 @@ +const MINUTES_IN_HOUR = 60; +const HOURS_IN_DAY = 24; +const MONTHS_IN_YEAR = 12; +const MIN_MONTH_PREFIX_LENGTH = 3; +const MAX_DAY_DIGITS = 2; +const YEAR_DIGITS = 4; +const TIME_TEXT_PATTERN = /^(\d{1,2})(?::(\d{2}))?$/; +const ISO_DATE_PATTERN = /^(\d{4})-(\d{1,2})-(\d{1,2})$/; +const DATE_TEXT_SEPARATOR = /[\s,./]+/; +const NUMBER_PATTERN = /^\d+$/; + +const padTwoDigits = (value: number) => String(value).padStart(2, '0'); + +export const toDateValue = (date: Date) => + `${date.getFullYear()}-${padTwoDigits(date.getMonth() + 1)}-${padTwoDigits(date.getDate())}`; + +export const fromDateValue = (dateValue: string) => { + const date = new Date(`${dateValue}T00:00`); + return Number.isNaN(date.getTime()) ? undefined : date; +}; + +export const getTimeOptions = (intervalMinutes: number) => { + const optionCount = (HOURS_IN_DAY * MINUTES_IN_HOUR) / intervalMinutes; + const options = Array.from({ length: optionCount }, (_, index) => { + const minutesOfDay = index * intervalMinutes; + return `${padTwoDigits(Math.floor(minutesOfDay / MINUTES_IN_HOUR))}:${padTwoDigits( + minutesOfDay % MINUTES_IN_HOUR, + )}`; + }); + return options; +}; + +export const withTimeOption = (timeOptions: string[], time: string) => + timeOptions.includes(time) ? timeOptions : [...timeOptions, time].sort(); + +export const parseTimeText = (text: string) => { + const match = TIME_TEXT_PATTERN.exec(text.trim()); + if (!match) return undefined; + + const [, hourText, minuteText = '00'] = match; + const isValidTime = + Number(hourText) < HOURS_IN_DAY && Number(minuteText) < MINUTES_IN_HOUR; + if (!isValidTime) return undefined; + + const timeValue = `${hourText.padStart(2, '0')}:${minuteText}`; + return timeValue; +}; + +const getMonthNames = (locale: string) => { + const monthFormat = new Intl.DateTimeFormat(locale, { month: 'long' }); + const monthNames = Array.from({ length: MONTHS_IN_YEAR }, (_, monthIndex) => + monthFormat.format(new Date(2000, monthIndex, 1)).toLocaleLowerCase(locale), + ); + return monthNames; +}; + +const findMonthIndex = (words: string[], monthNames: string[]) => { + const monthIndex = words + .filter((word) => word.length >= MIN_MONTH_PREFIX_LENGTH) + .map((word) => monthNames.findIndex((monthName) => monthName.startsWith(word))) + .find((index) => index >= 0); + return monthIndex; +}; + +const toExistingDate = (year: number, monthIndex: number, day: number) => { + const date = new Date(year, monthIndex, day); + const exists = date.getMonth() === monthIndex && date.getDate() === day; + return exists ? date : undefined; +}; + +const getNextAllowedDate = (monthIndex: number, day: number, earliest: Date) => { + const startOfEarliestDay = new Date( + earliest.getFullYear(), + earliest.getMonth(), + earliest.getDate(), + ); + const dateThisYear = toExistingDate(earliest.getFullYear(), monthIndex, day); + if (dateThisYear && dateThisYear >= startOfEarliestDay) return dateThisYear; + return toExistingDate(earliest.getFullYear() + 1, monthIndex, day); +}; + +export const parseDateText = (text: string, locale: string, earliest: Date) => { + const trimmedText = text.trim(); + const isoMatch = ISO_DATE_PATTERN.exec(trimmedText); + if (isoMatch) { + const [, year, month, day] = isoMatch.map(Number); + const isoDate = toExistingDate(year, month - 1, day); + return isoDate && toDateValue(isoDate); + } + + const words = trimmedText + .toLocaleLowerCase(locale) + .split(DATE_TEXT_SEPARATOR) + .filter(Boolean); + const numbers = words.filter((word) => NUMBER_PATTERN.test(word)); + const dayText = numbers.find((number) => number.length <= MAX_DAY_DIGITS); + const yearText = numbers.find((number) => number.length === YEAR_DIGITS); + const monthIndex = findMonthIndex(words, getMonthNames(locale)); + if (monthIndex === undefined || !dayText) return undefined; + + const day = Number(dayText); + const date = yearText + ? toExistingDate(Number(yearText), monthIndex, day) + : getNextAllowedDate(monthIndex, day, earliest); + return date && toDateValue(date); +}; diff --git a/examples/vite/src/ScheduledMessages/index.ts b/examples/vite/src/ScheduledMessages/index.ts new file mode 100644 index 0000000000..5eaa4202c6 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/index.ts @@ -0,0 +1,3 @@ +export * from './CalendarDateInput'; +export * from './ConfirmScheduledMessageDelete'; +export * from './TimeComboboxInput'; diff --git a/examples/vite/src/i18n/de.ts b/examples/vite/src/i18n/de.ts index 5986ec0ece..0221a5a5c0 100644 --- a/examples/vite/src/i18n/de.ts +++ b/examples/vite/src/i18n/de.ts @@ -820,6 +820,118 @@ export const deTranslations = { 'relativeTime.weeksAgo_one': 'vor {{ count }} Wo.', 'relativeTime.weeksAgo_other': 'vor {{ count }} Wo.', 'relativeTime.yesterday': 'Gestern', + 'scheduledMessages.banner.failedToSend_one': '{{ count }} nicht gesendet', + 'scheduledMessages.banner.failedToSend_other': '{{ count }} nicht gesendet', + 'scheduledMessages.banner.limitReached_one': + '{{ scheduled }} von {{ count }} geplanten Nachricht', + 'scheduledMessages.banner.limitReached_other': + '{{ scheduled }} von {{ count }} geplanten Nachrichten', + 'scheduledMessages.banner.scheduledFor': 'Geplant für {{ time }}', + 'scheduledMessages.banner.scheduledMessages_one': '{{ count }} geplante Nachricht', + 'scheduledMessages.banner.scheduledMessages_other': '{{ count }} geplante Nachrichten', + 'scheduledMessages.banner.scheduledReplies_one': '{{ count }} geplante Antwort', + 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} geplante Antworten', + 'scheduledMessages.blockedByModeration': 'Von der Moderation blockiert', + 'scheduledMessages.cancel': 'Abbrechen', + 'scheduledMessages.cantSendInThisChannel': + 'Nicht verfügbar: Du kannst in diesem Kanal keine Nachrichten senden', + 'scheduledMessages.channelFrozenNotice': + 'Dieser Kanal ist eingefroren. Geplante Nachrichten werden nicht gesendet', + 'scheduledMessages.chooseALaterTime': 'Wähle einen späteren Zeitpunkt', + 'scheduledMessages.chooseAnEarlierTime': 'Wähle einen früheren Zeitpunkt', + 'scheduledMessages.clickTheArrowNextToTheSendButton': + 'Klicke in einem Kanal auf den Pfeil neben der Senden-Schaltfläche, um eine Nachricht zu planen.', + 'scheduledMessages.copyText': 'Text kopieren', + 'scheduledMessages.couldntCopyTheText': 'Der Text konnte nicht kopiert werden', + 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain': + 'Die geplante Nachricht konnte nicht gelöscht werden. Versuche es erneut', + 'scheduledMessages.couldntLoadScheduledMessages': + 'Geplante Nachrichten konnten nicht geladen werden', + 'scheduledMessages.couldntRescheduleTheMessageTryAgain': + 'Die Nachricht konnte nicht neu geplant werden. Versuche es erneut', + 'scheduledMessages.couldntScheduleMessageTryAgain': + 'Die Nachricht konnte nicht geplant werden. Versuche es erneut', + 'scheduledMessages.couldntSendTheMessageTryAgain': + 'Die Nachricht konnte nicht gesendet werden. Versuche es erneut', + 'scheduledMessages.couldntSendTryAgain': 'Senden fehlgeschlagen. Versuche es erneut', + 'scheduledMessages.customTime': 'Eigener Zeitpunkt', + 'scheduledMessages.date': 'Datum', + 'scheduledMessages.delete': 'Löschen', + 'scheduledMessages.deleteScheduledMessage': 'Geplante Nachricht löschen?', + 'scheduledMessages.edit': 'Bearbeiten', + 'scheduledMessages.editReschedule': 'Bearbeiten & neu planen', + 'scheduledMessages.editScheduledMessage': 'Geplante Nachricht bearbeiten', + 'scheduledMessages.limitReachedMax': 'Limit erreicht (max. {{ max }})', + 'scheduledMessages.loaded': 'Geplante Nachrichten geladen', + 'scheduledMessages.loadingScheduledMessages': 'Geplante Nachrichten werden geladen', + 'scheduledMessages.messageToName': 'Nachricht an {{ name }}', + 'scheduledMessages.noMessagesFound': 'Keine Nachrichten gefunden', + 'scheduledMessages.noScheduledMessages': 'Keine geplanten Nachrichten', + 'scheduledMessages.notSentTheServiceWasDelayed': + 'Nicht gesendet: Der Dienst war verzögert', + 'scheduledMessages.notification.alreadySent': 'Bereits gesendet', + 'scheduledMessages.notification.alreadySentEdit': + 'Diese Nachricht wurde bereits gesendet', + 'scheduledMessages.notification.blocked': 'Diese Nachricht kann nicht geplant werden', + 'scheduledMessages.notification.channelLimit': + 'Du hast die maximale Anzahl geplanter Nachrichten in diesem Kanal erreicht', + 'scheduledMessages.notification.conflict': 'Anderswo geändert. Versuche es erneut', + 'scheduledMessages.notification.disabled': 'Geplante Nachrichten sind deaktiviert', + 'scheduledMessages.notification.endedEdit': + 'Diese geplante Nachricht kann nicht mehr bearbeitet werden', + 'scheduledMessages.notification.forbidden': 'Du kannst hier keine Nachrichten planen', + 'scheduledMessages.notification.notEditable': + 'Fehlgeschlagene Nachrichten können nicht bearbeitet werden', + 'scheduledMessages.notification.sending': 'Diese Nachricht wird gerade gesendet', + 'scheduledMessages.notification.sentNow': 'Zeit verstrichen. Nachricht jetzt gesendet', + 'scheduledMessages.notification.updateFailed': + 'Die geplante Nachricht konnte nicht aktualisiert werden. Versuche es erneut', + 'scheduledMessages.notification.userLimit': + 'Du hast die maximale Anzahl geplanter Nachrichten erreicht', + 'scheduledMessages.openScheduleMessageMenu.ariaLabel': + 'Menü zum Planen der Nachricht öffnen', + 'scheduledMessages.openScheduledMessageActions.ariaLabel': + 'Aktionen für geplante Nachricht öffnen', + 'scheduledMessages.pickALaterTimeEditingCantSend': + 'Wähle einen späteren Zeitpunkt. Beim Bearbeiten kann eine Nachricht nicht sofort gesendet werden.', + 'scheduledMessages.rejectedByTheApp': 'Von der App abgelehnt', + 'scheduledMessages.reschedule': 'Neu planen', + 'scheduledMessages.rescheduleMessage': 'Nachricht neu planen', + 'scheduledMessages.save': 'Speichern', + 'scheduledMessages.schedule': 'Planen', + 'scheduledMessages.scheduleAgain': 'Erneut planen', + 'scheduledMessages.scheduleMessage': 'Nachricht planen', + 'scheduledMessages.scheduledForTime': 'Geplant für {{ time }}', + 'scheduledMessages.scheduledMessageActions': 'Aktionen für geplante Nachricht', + 'scheduledMessages.scheduledMessageSent': 'Geplante Nachricht gesendet', + 'scheduledMessages.scheduledMessages': 'Geplante Nachrichten', + 'scheduledMessages.scheduledReplies': 'Geplante Antworten', + 'scheduledMessages.schedulingUnavailableNotice': + 'Du kannst in diesem Kanal keine Nachrichten planen', + 'scheduledMessages.search': 'Suchen', + 'scheduledMessages.sendNow': 'Jetzt senden', + 'scheduledMessages.sendTime': 'Senden: {{ time }}', + 'scheduledMessages.sending': 'Wird gesendet...', + 'scheduledMessages.sentInYourTimeZoneTimezone': + 'Gesendet in deiner Zeitzone ({{ timeZone }})', + 'scheduledMessages.somethingWentWrongTryAgain': + 'Etwas ist schiefgelaufen. Versuche es erneut', + 'scheduledMessages.theMessageNoLongerMeetsTheAppsLimits': + 'Die Nachricht entspricht nicht mehr den Grenzen der App. Bearbeite sie', + 'scheduledMessages.thisChannelIsFrozen': 'Dieser Kanal ist eingefroren', + 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain': + 'Dieser Kanal erfordert jetzt eine Freigabe. Plane die Nachricht erneut', + 'scheduledMessages.thisChannelWasDeleted': 'Dieser Kanal wurde gelöscht', + 'scheduledMessages.thisMessageToNameWontBeSentThis': + 'Diese Nachricht an {{ name }} wird nicht gesendet. Das kann nicht rückgängig gemacht werden.', + 'scheduledMessages.thisMessageWontBeSentThisCantBe': + 'Diese Nachricht wird nicht gesendet. Das kann nicht rückgängig gemacht werden.', + 'scheduledMessages.time': 'Uhrzeit', + 'scheduledMessages.view': 'Anzeigen', + 'scheduledMessages.viewAll': 'Alle anzeigen', + 'scheduledMessages.youCantSendMessagesInThisChannel': + 'Du kannst in diesem Kanal keine Nachrichten senden', + 'scheduledMessages.youreNoLongerAllowedToPostHere': 'Du darfst hier nicht mehr posten', 'search.bar.clearSearch.ariaLabel': 'Suche leeren', 'search.bar.exitSearch.ariaLabel': 'Suche beenden', 'search.resultItem.selectUserChannel.ariaLabel': 'Benutzerkanal auswählen: {{ name }}', diff --git a/examples/vite/src/i18n/it.ts b/examples/vite/src/i18n/it.ts index ebf5221505..551d319d8b 100644 --- a/examples/vite/src/i18n/it.ts +++ b/examples/vite/src/i18n/it.ts @@ -819,6 +819,118 @@ export const itTranslations = { 'relativeTime.weeksAgo_one': '{{ count }}sett fa', 'relativeTime.weeksAgo_other': '{{ count }}sett fa', 'relativeTime.yesterday': 'Ieri', + 'scheduledMessages.banner.failedToSend_one': '{{ count }} non inviato', + 'scheduledMessages.banner.failedToSend_other': '{{ count }} non inviati', + 'scheduledMessages.banner.limitReached_one': + '{{ scheduled }} di {{ count }} messaggio programmato', + 'scheduledMessages.banner.limitReached_other': + '{{ scheduled }} di {{ count }} messaggi programmati', + 'scheduledMessages.banner.scheduledFor': 'Programmato per {{ time }}', + 'scheduledMessages.banner.scheduledMessages_one': '{{ count }} messaggio programmato', + 'scheduledMessages.banner.scheduledMessages_other': '{{ count }} messaggi programmati', + 'scheduledMessages.banner.scheduledReplies_one': '{{ count }} risposta programmata', + 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} risposte programmate', + 'scheduledMessages.blockedByModeration': 'Bloccato dalla moderazione', + 'scheduledMessages.cancel': 'Annulla', + 'scheduledMessages.cantSendInThisChannel': + 'Non disponibile: non puoi inviare messaggi in questo canale', + 'scheduledMessages.channelFrozenNotice': + 'Questo canale è congelato. I messaggi programmati non verranno inviati', + 'scheduledMessages.chooseALaterTime': 'Scegli un orario successivo', + 'scheduledMessages.chooseAnEarlierTime': 'Scegli un orario precedente', + 'scheduledMessages.clickTheArrowNextToTheSendButton': + 'Fai clic sulla freccia accanto al pulsante di invio in un canale per programmare un messaggio.', + 'scheduledMessages.copyText': 'Copia testo', + 'scheduledMessages.couldntCopyTheText': 'Impossibile copiare il testo', + 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain': + 'Impossibile eliminare il messaggio programmato. Riprova', + 'scheduledMessages.couldntLoadScheduledMessages': + 'Impossibile caricare i messaggi programmati', + 'scheduledMessages.couldntRescheduleTheMessageTryAgain': + 'Impossibile riprogrammare il messaggio. Riprova', + 'scheduledMessages.couldntScheduleMessageTryAgain': + 'Impossibile programmare il messaggio. Riprova', + 'scheduledMessages.couldntSendTheMessageTryAgain': + 'Impossibile inviare il messaggio. Riprova', + 'scheduledMessages.couldntSendTryAgain': 'Invio non riuscito. Riprova', + 'scheduledMessages.customTime': 'Orario personalizzato', + 'scheduledMessages.date': 'Data', + 'scheduledMessages.delete': 'Elimina', + 'scheduledMessages.deleteScheduledMessage': 'Eliminare il messaggio programmato?', + 'scheduledMessages.edit': 'Modifica', + 'scheduledMessages.editReschedule': 'Modifica e riprogramma', + 'scheduledMessages.editScheduledMessage': 'Modifica messaggio programmato', + 'scheduledMessages.limitReachedMax': 'Limite raggiunto (max {{ max }})', + 'scheduledMessages.loaded': 'Messaggi programmati caricati', + 'scheduledMessages.loadingScheduledMessages': 'Caricamento dei messaggi programmati', + 'scheduledMessages.messageToName': 'Messaggio a {{ name }}', + 'scheduledMessages.noMessagesFound': 'Nessun messaggio trovato', + 'scheduledMessages.noScheduledMessages': 'Nessun messaggio programmato', + 'scheduledMessages.notSentTheServiceWasDelayed': + 'Non inviato: il servizio ha subito un ritardo', + 'scheduledMessages.notification.alreadySent': 'Già inviato', + 'scheduledMessages.notification.alreadySentEdit': + 'Questo messaggio è già stato inviato', + 'scheduledMessages.notification.blocked': 'Questo messaggio non può essere programmato', + 'scheduledMessages.notification.channelLimit': + 'Hai raggiunto il limite di messaggi programmati in questo canale', + 'scheduledMessages.notification.conflict': 'Modificato altrove. Riprova', + 'scheduledMessages.notification.disabled': 'I messaggi programmati sono disattivati', + 'scheduledMessages.notification.endedEdit': + 'Questo messaggio programmato non può più essere modificato', + 'scheduledMessages.notification.forbidden': 'Non puoi programmare messaggi qui', + 'scheduledMessages.notification.notEditable': + 'I messaggi non riusciti non possono essere modificati', + 'scheduledMessages.notification.sending': 'Questo messaggio è in fase di invio', + 'scheduledMessages.notification.sentNow': 'Orario passato. Messaggio inviato ora', + 'scheduledMessages.notification.updateFailed': + 'Impossibile aggiornare il messaggio programmato. Riprova', + 'scheduledMessages.notification.userLimit': + 'Hai raggiunto il limite di messaggi programmati', + 'scheduledMessages.openScheduleMessageMenu.ariaLabel': + 'Apri il menu di programmazione del messaggio', + 'scheduledMessages.openScheduledMessageActions.ariaLabel': + 'Apri le azioni del messaggio programmato', + 'scheduledMessages.pickALaterTimeEditingCantSend': + 'Scegli un orario successivo. La modifica non può inviare subito un messaggio.', + 'scheduledMessages.rejectedByTheApp': "Rifiutato dall'app", + 'scheduledMessages.reschedule': 'Riprogramma', + 'scheduledMessages.rescheduleMessage': 'Riprogramma messaggio', + 'scheduledMessages.save': 'Salva', + 'scheduledMessages.schedule': 'Programma', + 'scheduledMessages.scheduleAgain': 'Programma di nuovo', + 'scheduledMessages.scheduleMessage': 'Programma messaggio', + 'scheduledMessages.scheduledForTime': 'Programmato per {{ time }}', + 'scheduledMessages.scheduledMessageActions': 'Azioni del messaggio programmato', + 'scheduledMessages.scheduledMessageSent': 'Messaggio programmato inviato', + 'scheduledMessages.scheduledMessages': 'Messaggi programmati', + 'scheduledMessages.scheduledReplies': 'Risposte programmate', + 'scheduledMessages.schedulingUnavailableNotice': + 'Non puoi programmare messaggi in questo canale', + 'scheduledMessages.search': 'Cerca', + 'scheduledMessages.sendNow': 'Invia ora', + 'scheduledMessages.sendTime': 'Invio: {{ time }}', + 'scheduledMessages.sending': 'Invio in corso...', + 'scheduledMessages.sentInYourTimeZoneTimezone': + 'Inviato nel tuo fuso orario ({{ timeZone }})', + 'scheduledMessages.somethingWentWrongTryAgain': 'Qualcosa è andato storto. Riprova', + 'scheduledMessages.theMessageNoLongerMeetsTheAppsLimits': + "Il messaggio non rispetta più i limiti dell'app. Modificalo", + 'scheduledMessages.thisChannelIsFrozen': 'Questo canale è congelato', + 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain': + 'Questo canale ora richiede approvazione. Programmalo di nuovo', + 'scheduledMessages.thisChannelWasDeleted': 'Questo canale è stato eliminato', + 'scheduledMessages.thisMessageToNameWontBeSentThis': + 'Questo messaggio a {{ name }} non verrà inviato. Questa azione non può essere annullata.', + 'scheduledMessages.thisMessageWontBeSentThisCantBe': + 'Questo messaggio non verrà inviato. Questa azione non può essere annullata.', + 'scheduledMessages.time': 'Ora', + 'scheduledMessages.view': 'Visualizza', + 'scheduledMessages.viewAll': 'Visualizza tutti', + 'scheduledMessages.youCantSendMessagesInThisChannel': + 'Non puoi inviare messaggi in questo canale', + 'scheduledMessages.youreNoLongerAllowedToPostHere': + 'Non hai più il permesso di pubblicare qui', 'search.bar.clearSearch.ariaLabel': 'Cancella ricerca', 'search.bar.exitSearch.ariaLabel': 'Esci dalla ricerca', 'search.resultItem.selectUserChannel.ariaLabel': diff --git a/examples/vite/src/index.scss b/examples/vite/src/index.scss index fb228b228d..d4e6898f5b 100644 --- a/examples/vite/src/index.scss +++ b/examples/vite/src/index.scss @@ -11,6 +11,8 @@ layer(stream-app-overrides); @import url('./InlineEditMessage/InlineEditMessage.scss') layer(stream-app-overrides); @import url('./ComposerPreviews/PollPreview.scss') layer(stream-app-overrides); +@import url('./ScheduledMessages/ScheduledMessagePickers.scss') +layer(stream-app-overrides); @import url('./SystemNotification/SystemNotification.scss') layer(stream-app-overrides); @import url('./AccessibilityNavigation/ReturnToSkipNavigation.scss') layer(stream-app-overrides); diff --git a/yarn.lock b/yarn.lock index 354f0e53b2..21dffef3ec 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3363,6 +3363,7 @@ __metadata: dependencies: "@babel/core": "npm:^7.29.0" "@emoji-mart/data": "npm:^1.2.1" + "@internationalized/date": "npm:^3.12.1" "@playwright/test": "npm:^1.60.0" "@stream-io/state-store": "npm:^1.2.0" "@types/react": "npm:^19.2.15" @@ -3376,7 +3377,9 @@ __metadata: human-id: "npm:^4.1.3" modern-normalize: "npm:^3.0.1" react: "npm:^19.2.6" + react-aria: "npm:3.48.0" react-dom: "npm:^19.2.6" + react-stately: "npm:3.46.0" sass: "npm:^1.100.0" stream-chat: "npm:^10.2.0" stream-chat-react: "workspace:^" From 00bf82df69d9a8600eab3d9a133c1e37efc7b240 Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Wed, 25 Nov 2026 13:35:35 +0100 Subject: [PATCH 19/35] chore(examples): build the examples against stream-chat master stream-chat master requires voice_transcription in the channel config, so the vite example's WebSocket event template sets it. The cookbook's Lucide icon set adds IconCalendar, IconCaretDown and IconChevronUp, which the scheduled-messages UI added to the icon slots. --- .../recipes/theming/replacing-the-icon-set/lucideIcons.tsx | 5 +++++ .../WebSocketEventPromptDialog/websocketEventTemplates.ts | 1 + 2 files changed, 6 insertions(+) diff --git a/examples/cookbook/src/recipes/theming/replacing-the-icon-set/lucideIcons.tsx b/examples/cookbook/src/recipes/theming/replacing-the-icon-set/lucideIcons.tsx index 4c94034c46..0594690f88 100644 --- a/examples/cookbook/src/recipes/theming/replacing-the-icon-set/lucideIcons.tsx +++ b/examples/cookbook/src/recipes/theming/replacing-the-icon-set/lucideIcons.tsx @@ -10,6 +10,7 @@ import { BellOff, Bookmark, BookmarkMinus, + Calendar, Camera, ChartBar, Check, @@ -17,6 +18,7 @@ import { ChevronDown, ChevronLeft, ChevronRight, + ChevronUp, CircleAlert, CircleArrowDown, CircleMinus, @@ -129,13 +131,16 @@ const lucideIconMap: Record = { IconBolt: [Zap], IconBookmark: [Bookmark], IconBookmarkRemove: [BookmarkMinus], + IconCalendar: [Calendar], IconCamera: [Camera], + IconCaretDown: [ChevronDown], IconCheckmark: [Check], IconCheckmark1Small: [Check], IconChecks: [CheckCheck], IconChevronDown: [ChevronDown], IconChevronLeft: [ChevronLeft, { mirrorInRtl: true }], IconChevronRight: [ChevronRight, { mirrorInRtl: true }], + IconChevronUp: [ChevronUp], IconClock: [Clock], IconCommand: [SquareSlash], IconCopy: [Copy], diff --git a/examples/vite/src/AppSettings/ActionsMenu/WebSocketEventPromptDialog/websocketEventTemplates.ts b/examples/vite/src/AppSettings/ActionsMenu/WebSocketEventPromptDialog/websocketEventTemplates.ts index 141dacd5b3..b41b0f24eb 100644 --- a/examples/vite/src/AppSettings/ActionsMenu/WebSocketEventPromptDialog/websocketEventTemplates.ts +++ b/examples/vite/src/AppSettings/ActionsMenu/WebSocketEventPromptDialog/websocketEventTemplates.ts @@ -252,6 +252,7 @@ const buildChannel = ( uploads: true, url_enrichment: true, user_message_reminders: true, + voice_transcription: false, }, created_at: createdAt, created_by: context.actor, From 3b1ed50cc78038dd23aa03302fa0a817efca27ac Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Wed, 25 Nov 2026 13:36:23 +0100 Subject: [PATCH 20/35] fix(ScheduledMessages): follow the merged stream-chat scheduled-message APIs The channel's scheduled-message wrappers are now plain API calls that write nothing to the lists, with the client signatures (`{ id }`). Delete, send now and reschedule from the list go through `channel.messageOperations`, which ingests the response, so the list updates at once. Cancelling an edit now clears the composer instead of restoring what it held before. --- .../ScheduledMessageActions.tsx | 2 +- .../ScheduledMessageItem.tsx | 2 +- .../__tests__/EditScheduledMessage.test.tsx | 10 ++-- .../ScheduledMessageActions.test.tsx | 47 +++++++++++-------- .../hooks/useRescheduleDialogProps.ts | 4 +- 5 files changed, 37 insertions(+), 28 deletions(-) diff --git a/src/components/ScheduledMessages/ScheduledMessageActions.tsx b/src/components/ScheduledMessages/ScheduledMessageActions.tsx index 99b88ef8c5..f4ad0ae0df 100644 --- a/src/components/ScheduledMessages/ScheduledMessageActions.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageActions.tsx @@ -321,7 +321,7 @@ const DropdownSendNow = () => { () => client .channel(...splitCid(scheduledMessage.cid)) - .sendScheduledMessageNow(scheduledMessage.id), + .messageOperations.sendScheduledMessageNow(scheduledMessage.id), { message: t( 'scheduledMessages.couldntSendTheMessageTryAgain', diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index ec4dcae8c3..8cba35b364 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -143,7 +143,7 @@ export const ScheduledMessageItem = ({ const deleteScheduledMessage = () => { closeDialog(); - void runRequest(() => getChannel().deleteScheduledMessage(id), { + void runRequest(() => getChannel().messageOperations.deleteScheduledMessage(id), { message: t( 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain', "Couldn't delete the scheduled message. Try again", diff --git a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx index 7220630eab..deae98a5e0 100644 --- a/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx +++ b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx @@ -141,7 +141,7 @@ describe('editing a scheduled message in the composer', () => { expect(sendMessage).not.toHaveBeenCalled(); }); - it('restores the earlier draft when the edit is cancelled', async () => { + it('clears the composer when the edit is cancelled', async () => { const { messageComposer, startEditing } = await renderComposer(); await act(() => messageComposer.textComposer.setText('my unsent draft')); @@ -151,7 +151,7 @@ describe('editing a scheduled message in the composer', () => { ); expect(screen.queryByText('Edit scheduled message')).not.toBeInTheDocument(); - expect(messageComposer.textComposer.text).toBe('my unsent draft'); + expect(messageComposer.textComposer.text).toBe(''); }); describe('scheduling a failed message again', () => { @@ -164,7 +164,7 @@ describe('editing a scheduled message in the composer', () => { expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); }); - it('restores the earlier draft when cancelled', async () => { + it('clears the composer when cancelled', async () => { const { messageComposer, startSchedulingAgain } = await renderComposer(); await act(() => messageComposer.textComposer.setText('my unsent draft')); @@ -174,7 +174,7 @@ describe('editing a scheduled message in the composer', () => { ); expect(screen.queryByText('Schedule again')).not.toBeInTheDocument(); - expect(messageComposer.textComposer.text).toBe('my unsent draft'); + expect(messageComposer.textComposer.text).toBe(''); }); it('deletes the failed message after sending it now', async () => { @@ -183,7 +183,7 @@ describe('editing a scheduled message in the composer', () => { fromPartial({ message: { id: 'sent-id', text: 'Launch moved to Monday' } }), ); const deleteScheduledMessage = vi - .spyOn(channel, 'deleteScheduledMessage') + .spyOn(channel.messageOperations, 'deleteScheduledMessage') .mockResolvedValue(failedMessage); await startSchedulingAgain(); diff --git a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx index fe3e3dc7c8..62c6b3389f 100644 --- a/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -258,7 +258,7 @@ describe('ScheduledMessageActions', () => { it('sends the message now and confirms it', async () => { const { client, scheduledMessage } = await renderActions(); const sendNow = vi - .spyOn(getChannel(client), 'sendScheduledMessageNow') + .spyOn(getChannel(client).messageOperations, 'sendScheduledMessageNow') .mockResolvedValue(scheduledMessage); await selectAction('sendNow'); @@ -273,9 +273,10 @@ describe('ScheduledMessageActions', () => { it('reports a send-now failure with its error', async () => { const { client } = await renderActions(); - vi.spyOn(getChannel(client), 'sendScheduledMessageNow').mockRejectedValue( - notFoundError, - ); + vi.spyOn( + getChannel(client).messageOperations, + 'sendScheduledMessageNow', + ).mockRejectedValue(notFoundError); await selectAction('sendNow'); @@ -294,7 +295,7 @@ describe('ScheduledMessageActions', () => { it('deletes only after the deletion is confirmed', async () => { const { client, scheduledMessage } = await renderActions(); const deleteScheduledMessage = vi - .spyOn(getChannel(client), 'deleteScheduledMessage') + .spyOn(getChannel(client).messageOperations, 'deleteScheduledMessage') .mockResolvedValue(scheduledMessage); await selectAction('delete'); @@ -322,7 +323,7 @@ describe('ScheduledMessageActions', () => { components: { ScheduledMessageDeleteAlert: CustomDeleteAlert }, }); const deleteScheduledMessage = vi - .spyOn(getChannel(client), 'deleteScheduledMessage') + .spyOn(getChannel(client).messageOperations, 'deleteScheduledMessage') .mockResolvedValue(scheduledMessage); await selectAction('delete'); @@ -336,7 +337,10 @@ describe('ScheduledMessageActions', () => { it('keeps the message when the deletion is cancelled', async () => { const { client } = await renderActions(); - const deleteScheduledMessage = vi.spyOn(getChannel(client), 'deleteScheduledMessage'); + const deleteScheduledMessage = vi.spyOn( + getChannel(client).messageOperations, + 'deleteScheduledMessage', + ); await selectAction('delete'); await screen.findByTestId('delete-scheduled-message-alert'); @@ -351,7 +355,7 @@ describe('ScheduledMessageActions', () => { it('reschedules from the dialog pre-filled with the current time', async () => { const { client, scheduledMessage } = await renderActions(); const updateScheduledMessage = vi - .spyOn(getChannel(client), 'updateScheduledMessage') + .spyOn(getChannel(client).messageOperations, 'updateScheduledMessage') .mockResolvedValue(scheduledMessage); await selectAction('reschedule'); @@ -366,7 +370,7 @@ describe('ScheduledMessageActions', () => { await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { - scheduled_at: new Date(2026, 9, 29, 14, 30), + request: { scheduled_at: new Date(2026, 9, 29, 14, 30) }, }); await waitFor(() => expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), @@ -375,9 +379,10 @@ describe('ScheduledMessageActions', () => { it('keeps the reschedule dialog open and reports a failure', async () => { const { client } = await renderActions(); - vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( - notFoundError, - ); + vi.spyOn( + getChannel(client).messageOperations, + 'updateScheduledMessage', + ).mockRejectedValue(notFoundError); await selectAction('reschedule'); await screen.findByTestId('schedule-message-dialog'); @@ -391,9 +396,10 @@ describe('ScheduledMessageActions', () => { it('clears a reschedule failure once another time is picked', async () => { const { client } = await renderActions(); - vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( - notFoundError, - ); + vi.spyOn( + getChannel(client).messageOperations, + 'updateScheduledMessage', + ).mockRejectedValue(notFoundError); await selectAction('reschedule'); await screen.findByTestId('schedule-message-dialog'); @@ -413,7 +419,7 @@ describe('ScheduledMessageActions', () => { }); const { client } = await renderActions({ scheduledMessage }); const updateScheduledMessage = vi - .spyOn(getChannel(client), 'updateScheduledMessage') + .spyOn(getChannel(client).messageOperations, 'updateScheduledMessage') .mockResolvedValue(scheduledMessage); await selectAction('reschedule'); @@ -421,15 +427,16 @@ describe('ScheduledMessageActions', () => { await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { - scheduled_at: sendTime, + request: { scheduled_at: sendTime }, }); }); it('reports a reschedule failure without a specific reason generically', async () => { const { client } = await renderActions(); - vi.spyOn(getChannel(client), 'updateScheduledMessage').mockRejectedValue( - new Error('Network Error'), - ); + vi.spyOn( + getChannel(client).messageOperations, + 'updateScheduledMessage', + ).mockRejectedValue(new Error('Network Error')); await selectAction('reschedule'); await screen.findByTestId('schedule-message-dialog'); diff --git a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts index 00f7cc05dc..09f7be38a7 100644 --- a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts +++ b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts @@ -39,7 +39,9 @@ export const useRescheduleDialogProps = ({ submit: async (scheduledAt: Date) => { await client .channel(...splitCid(scheduledMessage.cid)) - .updateScheduledMessage(scheduledMessage.id, { scheduled_at: scheduledAt }); + .messageOperations.updateScheduledMessage(scheduledMessage.id, { + request: { scheduled_at: scheduledAt }, + }); }, submitLabel: t('scheduledMessages.save', 'Save'), title: t('scheduledMessages.rescheduleMessage', 'Reschedule message'), From 94310b349e3fc41f563632ba710f45d91335490e Mon Sep 17 00:00:00 2001 From: "nikola.nnaumovski" Date: Wed, 25 Nov 2026 13:37:29 +0100 Subject: [PATCH 21/35] feat(ScheduledMessages): align the remaining web details with the Figma designs - Mobile web: the custom-time and reschedule dialogs and the scheduled list open full screen below 680px, the date and time fields stack, and the dialog's buttons split the footer. - On touch screens the row actions stay visible, as there is no hover to reveal them. - The limit counts messages being sent as pending, as the server does. - A message the server sent at once shows "Scheduled message sent" with a View action that jumps to it. - Clicking a row opens its actions menu; clicking a row that is being sent says it is still sending. A thread reply starts with "Thread reply:" in the list. - The edit preview's dismiss button is labelled "Cancel edit" ("Cancel scheduling again" for a failed message) through a new `removeLabel` prop of `QuotedMessagePreviewUI`. --- examples/vite/src/i18n/de.ts | 6 ++- examples/vite/src/i18n/it.ts | 6 ++- .../MessageComposer/QuotedMessagePreview.tsx | 13 +++-- .../ScheduleMessageButton.tsx | 18 +++++-- .../ScheduledMessageItem.tsx | 46 ++++++++++++++-- .../ScheduledMessagePreview.tsx | 7 ++- .../__tests__/EditScheduledMessage.test.tsx | 10 +++- .../__tests__/ScheduleMessageButton.test.tsx | 23 +++++++- .../ScheduledMessageActions.test.tsx | 54 +++++++++++++++++++ .../ScheduledMessages/__tests__/utils.test.ts | 4 +- .../styling/ScheduleMessageDialog.scss | 27 ++++++++++ .../styling/ScheduledMessageActions.scss | 5 ++ .../styling/ScheduledMessageList.scss | 30 +++++++++++ .../ScheduledMessages/styling/_variables.scss | 1 + src/components/ScheduledMessages/utils.ts | 5 +- src/i18n/__tests__/catalog.fixture.json | 5 +- src/i18n/keys.ts | 5 +- 17 files changed, 243 insertions(+), 22 deletions(-) create mode 100644 src/components/ScheduledMessages/styling/_variables.scss diff --git a/examples/vite/src/i18n/de.ts b/examples/vite/src/i18n/de.ts index 0221a5a5c0..e3cf9d5f40 100644 --- a/examples/vite/src/i18n/de.ts +++ b/examples/vite/src/i18n/de.ts @@ -833,6 +833,8 @@ export const deTranslations = { 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} geplante Antworten', 'scheduledMessages.blockedByModeration': 'Von der Moderation blockiert', 'scheduledMessages.cancel': 'Abbrechen', + 'scheduledMessages.cancelEdit.ariaLabel': 'Bearbeitung abbrechen', + 'scheduledMessages.cancelSchedulingAgain.ariaLabel': 'Erneutes Planen abbrechen', 'scheduledMessages.cantSendInThisChannel': 'Nicht verfügbar: Du kannst in diesem Kanal keine Nachrichten senden', 'scheduledMessages.channelFrozenNotice': @@ -883,7 +885,8 @@ export const deTranslations = { 'scheduledMessages.notification.notEditable': 'Fehlgeschlagene Nachrichten können nicht bearbeitet werden', 'scheduledMessages.notification.sending': 'Diese Nachricht wird gerade gesendet', - 'scheduledMessages.notification.sentNow': 'Zeit verstrichen. Nachricht jetzt gesendet', + 'scheduledMessages.notification.stillSending': + 'Wird noch gesendet. Versuche es gleich noch einmal.', 'scheduledMessages.notification.updateFailed': 'Die geplante Nachricht konnte nicht aktualisiert werden. Versuche es erneut', 'scheduledMessages.notification.userLimit': @@ -926,6 +929,7 @@ export const deTranslations = { 'Diese Nachricht an {{ name }} wird nicht gesendet. Das kann nicht rückgängig gemacht werden.', 'scheduledMessages.thisMessageWontBeSentThisCantBe': 'Diese Nachricht wird nicht gesendet. Das kann nicht rückgängig gemacht werden.', + 'scheduledMessages.threadReply': 'Thread-Antwort:', 'scheduledMessages.time': 'Uhrzeit', 'scheduledMessages.view': 'Anzeigen', 'scheduledMessages.viewAll': 'Alle anzeigen', diff --git a/examples/vite/src/i18n/it.ts b/examples/vite/src/i18n/it.ts index 551d319d8b..d7ec7874be 100644 --- a/examples/vite/src/i18n/it.ts +++ b/examples/vite/src/i18n/it.ts @@ -832,6 +832,8 @@ export const itTranslations = { 'scheduledMessages.banner.scheduledReplies_other': '{{ count }} risposte programmate', 'scheduledMessages.blockedByModeration': 'Bloccato dalla moderazione', 'scheduledMessages.cancel': 'Annulla', + 'scheduledMessages.cancelEdit.ariaLabel': 'Annulla modifica', + 'scheduledMessages.cancelSchedulingAgain.ariaLabel': 'Annulla nuova programmazione', 'scheduledMessages.cantSendInThisChannel': 'Non disponibile: non puoi inviare messaggi in questo canale', 'scheduledMessages.channelFrozenNotice': @@ -882,7 +884,8 @@ export const itTranslations = { 'scheduledMessages.notification.notEditable': 'I messaggi non riusciti non possono essere modificati', 'scheduledMessages.notification.sending': 'Questo messaggio è in fase di invio', - 'scheduledMessages.notification.sentNow': 'Orario passato. Messaggio inviato ora', + 'scheduledMessages.notification.stillSending': + 'Invio in corso. Riprova tra un momento.', 'scheduledMessages.notification.updateFailed': 'Impossibile aggiornare il messaggio programmato. Riprova', 'scheduledMessages.notification.userLimit': @@ -924,6 +927,7 @@ export const itTranslations = { 'Questo messaggio a {{ name }} non verrà inviato. Questa azione non può essere annullata.', 'scheduledMessages.thisMessageWontBeSentThisCantBe': 'Questo messaggio non verrà inviato. Questa azione non può essere annullata.', + 'scheduledMessages.threadReply': 'Risposta nel thread:', 'scheduledMessages.time': 'Ora', 'scheduledMessages.view': 'Visualizza', 'scheduledMessages.viewAll': 'Visualizza tutti', diff --git a/src/components/MessageComposer/QuotedMessagePreview.tsx b/src/components/MessageComposer/QuotedMessagePreview.tsx index 6a9f1f1604..0fd7ae83aa 100644 --- a/src/components/MessageComposer/QuotedMessagePreview.tsx +++ b/src/components/MessageComposer/QuotedMessagePreview.tsx @@ -332,6 +332,7 @@ type QuotedMessagePreviewUIProps = QuotedMessagePreviewProps & { className?: string; onClick?: MouseEventHandler; onRemove?: () => void; + removeLabel?: string; }; export const QuotedMessagePreviewUI = ({ @@ -341,6 +342,7 @@ export const QuotedMessagePreviewUI = ({ onClick, onRemove, quotedMessage, + removeLabel, renderText, }: QuotedMessagePreviewUIProps) => { const { client } = useChatContext(); @@ -525,10 +527,13 @@ export const QuotedMessagePreviewUI = ({ {onRemove && ( diff --git a/src/components/ScheduledMessages/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx index 98031c2d11..9bca883f02 100644 --- a/src/components/ScheduledMessages/ScheduleMessageButton.tsx +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -25,6 +25,7 @@ import { } from '../Dialog'; import { useMessageComposerHasSendableData } from '../MessageComposer/hooks'; import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; +import { useMessagePaginator } from '../../hooks/useMessagePaginator'; import { GlobalModal } from '../Modal'; import { useNotificationApi } from '../Notifications'; import { Portal } from '../Portal/Portal'; @@ -90,6 +91,7 @@ export const ScheduleMessageButton = () => { } = useComponentContext(); const { addNotification } = useNotificationApi(); const messageComposer = useMessageComposerController(); + const messagePaginator = useMessagePaginator(); const hasSendableData = useMessageComposerHasSendableData(); const { reachedLimit } = useChannelScheduledMessageLimit(messageComposer.channel); @@ -109,14 +111,20 @@ export const ScheduleMessageButton = () => { // the banner confirms a scheduled message, so success needs no notification const scheduleMessage = useCallback( async (scheduledAt: Date) => { + const messageId = messageComposer.id; const { error, status } = await messageComposer.scheduleMessage(scheduledAt); if (status === 'sent') { addNotification({ + actions: [ + { + handler: () => { + void messagePaginator.jumpToMessage(messageId); + }, + label: t('scheduledMessages.view', 'View'), + }, + ], emitter: SCHEDULED_MESSAGES_EMITTER, - message: t( - 'scheduledMessages.notification.sentNow', - 'Time passed. Message sent now', - ), + message: t('scheduledMessages.scheduledMessageSent', 'Scheduled message sent'), severity: 'success', type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sentNow, }); @@ -129,7 +137,7 @@ export const ScheduleMessageButton = () => { } throw error ?? new Error(`Message not scheduled: ${status}`); }, - [addNotification, messageComposer, t], + [addNotification, messageComposer, messagePaginator, t], ); // the dialog shows the failure itself, so the composer's notification of it is dropped diff --git a/src/components/ScheduledMessages/ScheduledMessageItem.tsx b/src/components/ScheduledMessages/ScheduledMessageItem.tsx index 8cba35b364..a19ce0ef92 100644 --- a/src/components/ScheduledMessages/ScheduledMessageItem.tsx +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -1,5 +1,11 @@ import clsx from 'clsx'; -import React, { type RefObject, useCallback, useRef, useState } from 'react'; +import React, { + type MouseEvent, + type RefObject, + useCallback, + useRef, + useState, +} from 'react'; import { nsToDate, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; import type { OwnCapabilitiesState, ScheduledMessageResponse } from 'stream-chat'; @@ -45,6 +51,13 @@ import { translateScheduledMessageFailureReason, } from './utils'; +const ROW_INTERACTIVE_ELEMENT_SELECTOR = 'a, button, input, textarea, [role="menu"]'; + +const isClickOnRowItself = ({ currentTarget, target }: MouseEvent) => + target instanceof Element && + currentTarget.contains(target) && + !target.closest(ROW_INTERACTIVE_ELEMENT_SELECTOR); + export type ScheduledMessageItemProps = { scheduledMessage: ScheduledMessageResponse; /** Opens the message in the composer; without it the list offers no edit action. */ @@ -97,6 +110,8 @@ export const ScheduledMessageItem = ({ }); const sendTime = nsToDate(scheduled_at); const isFailed = isFailedScheduledMessage(scheduledMessage); + const isSending = status === SCHEDULED_MESSAGE_STATUS.Sending; + const isThreadReply = !!scheduledMessage.message.parent_id; // a pending message is saved by scheduling it, a failed one is scheduled or sent again; a frozen // channel allows neither. Unknown for a channel not loaded, so left on there. const canEdit = @@ -141,6 +156,23 @@ export const ScheduledMessageItem = ({ } }; + const openRowMenu = (event: MouseEvent) => { + if (!isClickOnRowItself(event)) return; + if (isSending) { + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + message: t( + 'scheduledMessages.notification.stillSending', + 'Still sending. Try again in a moment.', + ), + severity: 'info', + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.stillSending, + }); + return; + } + menuButtonRef.current?.click(); + }; + const deleteScheduledMessage = () => { closeDialog(); void runRequest(() => getChannel().messageOperations.deleteScheduledMessage(id), { @@ -158,6 +190,7 @@ export const ScheduledMessageItem = ({ 'str-chat__scheduled-message-item--failed': isFailed, })} data-testid='scheduled-message-item' + onClick={openRowMenu} >