diff --git a/ai-docs/ai-migration-v14-v15.md b/ai-docs/ai-migration-v14-v15.md index 2f464dc150..6abf476175 100644 --- a/ai-docs/ai-migration-v14-v15.md +++ b/ai-docs/ai-migration-v14-v15.md @@ -336,7 +336,7 @@ These compile cleanly, or are ignored in plain JS, and change behavior at runtim ### Packages -- **`stream-chat` peer is v10.** Read the exact range from `peerDependencies['stream-chat']` in the installed `node_modules/stream-chat-react/package.json` and install a version that satisfies it; the minimum moves between release candidates. v9 does not satisfy it, and v10 is itself a breaking client release (see [`v10-breaking-changes.md`](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md) in stream-chat-js). +- **`stream-chat` peer is v10.** Read the exact range from `peerDependencies['stream-chat']` in the installed `node_modules/stream-chat-react/package.json` and install a version that satisfies it; the minimum moves between releases. From the release that adds scheduled messages, the range starts at `^10.3.1`, which brings the scheduled-message APIs: an app on an earlier `stream-chat` 10.x upgrades it together with this package. v9 does not satisfy it, and v10 is itself a breaking client release (see [`v10-breaking-changes.md`](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md) in stream-chat-js). - **The first compile errors are usually `stream-chat` type changes, not React ones.** The removed-exports table below lists only this package's exports. The common ones from `stream-chat`: `ChannelSort`, `UserSort` and the other sort aliases → `SortParamRequest[]` ([sort](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md#sort-shape)); `client.queryChannels` keeps its name but returns the raw response object, and the v9 behavior (`Channel[]`) is `client.queryChannelsAndHydrate` ([queryChannels](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md#query-channels-raw)); `client.queryUsers(filter, sort, options)` → `client.queryUsers({ payload: { filter_conditions, sort, limit } })` ([generated signatures](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md#generated-client-signatures)). - **Node `>=22.18.0`.** `stream-chat@10` declares `engines.node >=22.18.0`, and Yarn 1 refuses to install on older Node. Move `.nvmrc` and every CI `node-version` (GitHub Actions `setup-node`, Docker base images, deploy workflows) to Node 22 before anything else: CI is usually the first thing to break. - **`dayjs` and `i18next` are no longer dependencies of this package.** It depends on `@stream-io/i18n`, which brings both (`dayjs ^1.11.23`, `i18next ^26`). `stream-chat` v10 depends on neither. If the app declared them only because of this SDK, remove them. If it keeps `dayjs`, its version must dedupe with `@stream-io/i18n`'s, or `import 'dayjs/locale/xx'` registers the locale on a different instance and dates stay English. @@ -3708,7 +3708,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. +Seven formatter keys carry English words inside their formats (`timestamp.DateSeparator`, `timestamp.ReminderNotification`, `timestamp.ChannelPreviewTimestamp`, `timestamp.ChannelDetailPinnedMessageTimestamp`, `timestamp.ScheduledMessageConfirmation`, `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..cadf87f57b 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 718 translatable keys. The 19 `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. Seven 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 737-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. **Seven 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,11 @@ 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.ScheduledMessageSendTime` | `at` | +| `timestamp.SchedulePreset` | `Today`, `Tomorrow`, `Yesterday`, `Last`, `at` | -Translating those four means overriding the key itself — `dayjsLocaleConfigForLanguage` does not +Translating those seven 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/examples/ai-chatbot/package.json b/examples/ai-chatbot/package.json index f2a0da0a57..947f38ac44 100644 --- a/examples/ai-chatbot/package.json +++ b/examples/ai-chatbot/package.json @@ -18,7 +18,7 @@ "next": "^16.2.4", "react": "^19.2.6", "react-dom": "^19.2.6", - "stream-chat": "^10.2.0", + "stream-chat": "^10.3.1", "stream-chat-react": "workspace:^" }, "devDependencies": { diff --git a/examples/cookbook/package.json b/examples/cookbook/package.json index 5c1ad1fddf..7217c3c9ce 100644 --- a/examples/cookbook/package.json +++ b/examples/cookbook/package.json @@ -19,7 +19,7 @@ "react": "^19.2.6", "react-dom": "^19.2.6", "react-leaflet": "^5.0.0", - "stream-chat": "^10.2.0", + "stream-chat": "^10.3.1", "stream-chat-react": "workspace:^" }, "devDependencies": { 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/tutorial/package.json b/examples/tutorial/package.json index 1bc5d5f698..32ead39e1a 100644 --- a/examples/tutorial/package.json +++ b/examples/tutorial/package.json @@ -16,7 +16,7 @@ "emoji-mart": "^5.6.0", "react": "^19.2.6", "react-dom": "^19.2.6", - "stream-chat": "^10.2.0", + "stream-chat": "^10.3.1", "stream-chat-react": "workspace:^" }, "devDependencies": { diff --git a/examples/vite/package.json b/examples/vite/package.json index 2cc3f660e1..332d8fa252 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,8 +18,10 @@ "human-id": "^4.1.3", "modern-normalize": "^3.0.1", "react": "^19.2.6", + "react-aria": "3.48.0", "react-dom": "^19.2.6", - "stream-chat": "^10.2.0", + "react-stately": "3.46.0", + "stream-chat": "^10.3.1", "stream-chat-react": "workspace:^" }, "devDependencies": { diff --git a/examples/vite/src/App.tsx b/examples/vite/src/App.tsx index e50a68e28b..7e365f04e5 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 { @@ -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'; @@ -101,6 +107,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 { @@ -583,11 +590,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 { @@ -700,6 +708,11 @@ const App = () => { MessageBubbleContent: ConfigurableMessageBubbleContent, 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/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, diff --git a/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx new file mode 100644 index 0000000000..96dd6d5475 --- /dev/null +++ b/examples/vite/src/ChatLayout/ChannelFreezeAction.tsx @@ -0,0 +1,116 @@ +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); + // 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(() => { + 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 () => { + if (isUpdating) return; + const nextFrozen = !frozen; + setIsUpdating(true); + setFrozen(nextFrozen); + try { + await channel.updatePartial({ set: { frozen: nextFrozen } }); + } catch (error) { + // back to what the channel last confirmed + setFrozen(!!channel.data?.frozen); + 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', + }); + } finally { + setIsUpdating(false); + } + }; + + 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 af1a8661a4..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'; @@ -13,18 +14,28 @@ import { type AvatarWithChannelDetailProps, ChannelDetail, type ChannelDetailProps, + ChannelManagementView, ChannelMembersView, type ChannelMembersViewModes, defaultChannelDetailSections, + ScheduledMessagesChannelDetailDialog, type SectionNavigatorSection, type SectionNavigatorSectionContentProps, } from 'stream-chat-react/channel-detail'; import { useAppSettingsSelector } from '../AppSettings/state'; import { getChannelMembersHeaderActionSet } from '../AppSettings/tabs/ChannelDetail'; +import { channelManagementActionSetWithFreeze } from './ChannelFreezeAction'; import { ChannelMembersRemoveView } from './ChannelMembersRemoveView'; import { CHANNEL_THREAD_SLOT } from './constants.ts'; +const ChannelManagementViewWithFreeze = (props: SectionNavigatorSectionContentProps) => ( + +); + const ChannelMembersRemoveTitle = () => { const { t } = useTranslationContext(); return ( @@ -52,18 +63,20 @@ export 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], @@ -117,3 +130,12 @@ export const ConfiguredAvatarWithChannelDetail = ( ChannelDetail={ConfiguredChannelDetail} /> ); + +export const ConfiguredScheduledMessageListDialog = ( + props: ScheduledMessageListDialogProps, +) => ( + +); diff --git a/examples/vite/src/ChatLayout/Panels.tsx b/examples/vite/src/ChatLayout/Panels.tsx index 9068a0a360..36faf32763 100644 --- a/examples/vite/src/ChatLayout/Panels.tsx +++ b/examples/vite/src/ChatLayout/Panels.tsx @@ -9,8 +9,10 @@ import { type BaseSyntheticEvent, type MouseEvent, type PropsWithChildren, + type TransitionEvent, useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, @@ -190,6 +192,27 @@ const CustomChannelListItem = ({ item }: { item: unknown }) => { return ; }; +const useClosingThread = (thread?: ThreadType) => { + const [closingThread, setClosingThread] = useState(); + const previousThreadRef = useRef(thread); + + const finishClosing = useCallback(() => setClosingThread(undefined), []); + + useLayoutEffect(() => { + const previousThread = previousThreadRef.current; + previousThreadRef.current = thread; + if (thread || !previousThread) { + setClosingThread(undefined); + return; + } + setClosingThread(previousThread); + const timeout = setTimeout(finishClosing, 400); + return () => clearTimeout(timeout); + }, [finishClosing, thread]); + + return { closingThread, finishClosing }; +}; + // The in-channel reply thread is opened into the channels view's secondary slot (the same // slot a 2nd channel can occupy) — bound by the message "reply in thread" / replies-count // actions via `open`. It renders only when a thread is bound, and `useActiveThread` @@ -208,21 +231,27 @@ const ChannelThreadPanel = ({ }) => { const isOpen = !!thread; const registerThreadSlot = useRegisterSlotGeometry(CHANNEL_THREAD_SLOT); + const { closingThread, finishClosing } = useClosingThread(thread); + const shownThread = thread ?? closingThread; useActiveThread({ activeThread: thread }); + const finishClosingOnPanelTransition = (event: TransitionEvent) => { + if (!isOpen && event.target === event.currentTarget) finishClosing(); + }; + const panelClassName = clsx('app-chat-secondary-panel', { 'app-chat-secondary-panel--open': isOpen, }); // The resize handle is rendered once at the slot level (see `ResponsiveChannelPanels`), not // here — the bar belongs to the slot, which may hold layers, not to this base content. - return thread ? ( + return shownThread ? ( // The dropzone sits inside so WithDragAndDropUpload's `useChannel` resolves the // thread's own channel — the thread panel no longer depends on an ambient , so it // can live in its own slot beside the primary channel. The panel shell stays outside, so the // open and closed states present the same box to the layout. -
- +
+ @@ -231,11 +260,11 @@ const ChannelThreadPanel = ({ onOpenMemberDetail( getMentionedUserId(event, message), event, - thread.channel, + shownThread.channel, ) } onUserClick={(event, user) => - onOpenMemberDetail(user.id, event, thread.channel) + onOpenMemberDetail(user.id, event, shownThread.channel) } /> diff --git a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx index a75562ef2f..9c0c251ed5 100644 --- a/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx +++ b/examples/vite/src/ComposerPreviews/ConfigurablePollCreationDialogControls.tsx @@ -1,11 +1,18 @@ +import { useMemo, useRef, 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,150 @@ 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(); + // 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. + 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(); + pollCreatedForScheduleRef.current = messageComposer.pollId; + } + if (!messageComposer.pollId) throw new Error('The poll was not created'); + const { error, status } = await messageComposer.scheduleMessage(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 ( - - - - {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', + )} + + + + + {isPickingTime && ( + + )} + + ); }; diff --git a/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx new file mode 100644 index 0000000000..3ead1359ed --- /dev/null +++ b/examples/vite/src/ComposerPreviews/ConfigurableScheduledMessageItem.tsx @@ -0,0 +1,23 @@ +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 = ({ + openInComposer, + ...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 { + 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..27efee6929 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/ScheduledMessagePickers.scss @@ -0,0 +1,152 @@ +// 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; +} + +.app__schedule-calendar-frame { + box-sizing: border-box; + min-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..4c216b2310 --- /dev/null +++ b/examples/vite/src/ScheduledMessages/TimeComboboxInput.tsx @@ -0,0 +1,247 @@ +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 firstMatchFocusedForRef = 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 { inputValue, isOpen, selectedItem, selectionManager } = state; + const firstMatchKey = state.collection.getFirstKey(); + const isFiltering = isOpen && inputValue !== (selectedItem?.textValue ?? ''); + + const setInputElement = useCallback((element: HTMLInputElement | null) => { + inputRef.current = element; + setFieldElement(element?.closest(FIELD_WRAPPER_SELECTOR) ?? null); + }, []); + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape' && isOpen) event.preventDefault(); + if (event.key === 'Enter' && selectionManager.focusedKey === null) commitTypedTime(); + }; + + const openList = () => { + if (!state.isOpen) state.open(null, 'manual'); + }; + + useEffect(() => { + if (!isFiltering || firstMatchKey === null) { + firstMatchFocusedForRef.current = null; + return; + } + if (firstMatchFocusedForRef.current === inputValue) return; + firstMatchFocusedForRef.current = inputValue; + selectionManager.setFocusedKey(firstMatchKey); + }, [firstMatchKey, inputValue, isFiltering, selectionManager]); + + useEffect(() => { + if (!dialogManager) return; + if (isOpen) dialogManager.open({ id: dialogId }); + else dialogManager.close(dialogId); + }, [dialogId, dialogManager, 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 27cc8fa820..fc08419b92 100644 --- a/examples/vite/src/i18n/de.ts +++ b/examples/vite/src/i18n/de.ts @@ -283,6 +283,12 @@ export const deTranslations = { 'channelDetail.channelMembersView.members.title_one': '{{ count }} Mitglied', 'channelDetail.channelMembersView.members.title_other': '{{ count }} Mitglieder', 'channelDetail.listLoaded.text': 'Liste geladen', + 'channelDetail.navButton.channelInfo.title': 'Kanalinfo', + 'channelDetail.navButton.files.title': 'Dateien', + 'channelDetail.navButton.media.title': 'Fotos & Videos', + 'channelDetail.navButton.members.title': 'Mitglieder', + 'channelDetail.navButton.pinnedMessages.title': 'Angeheftete Nachrichten', + 'channelDetail.navButton.scheduledMessages.title': 'Geplant', 'channelDetail.pinnedMessagesEmpty.noPinnedMessages.text': 'Keine angepinnten Nachrichten', 'channelDetail.pinnedMessagesEmpty.pinMessageSee.text': @@ -814,6 +820,121 @@ 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.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': + '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.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': + '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.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.threadReply': 'Thread-Antwort:', + '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 cac7f9ba54..a64d51623c 100644 --- a/examples/vite/src/i18n/it.ts +++ b/examples/vite/src/i18n/it.ts @@ -272,6 +272,12 @@ export const itTranslations = { 'channelDetail.channelMembersView.members.title_one': '{{ count }} membro', 'channelDetail.channelMembersView.members.title_other': '{{ count }} membri', 'channelDetail.listLoaded.text': 'Elenco caricato', + 'channelDetail.navButton.channelInfo.title': 'Info canale', + 'channelDetail.navButton.files.title': 'File', + 'channelDetail.navButton.media.title': 'Foto e video', + 'channelDetail.navButton.members.title': 'Membri', + 'channelDetail.navButton.pinnedMessages.title': 'Messaggi fissati', + 'channelDetail.navButton.scheduledMessages.title': 'Programmati', 'channelDetail.pinnedMessagesEmpty.noPinnedMessages.text': 'Nessun messaggio fissato', 'channelDetail.pinnedMessagesEmpty.pinMessageSee.text': 'Fissa un messaggio per vederlo qui', @@ -813,6 +819,121 @@ 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.cancelEdit.ariaLabel': 'Annulla modifica', + 'scheduledMessages.cancelSchedulingAgain.ariaLabel': 'Annulla nuova programmazione', + '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.stillSending': + 'Invio in corso. Riprova tra un momento.', + '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.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.threadReply': 'Risposta nel thread:', + '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/icons.tsx b/examples/vite/src/icons.tsx index cc97e568e7..5be9ea509a 100644 --- a/examples/vite/src/icons.tsx +++ b/examples/vite/src/icons.tsx @@ -95,3 +95,18 @@ export const IconCollapse = createIcon( strokeWidth='1.5' />, ); + +/** The design system's `core/line/lock` icon, for the channel freeze switch. */ +export const IconLock = createIcon( + 'IconLock', + <> + + + , +); 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/package.json b/package.json index ffe1fb0758..7b21c41638 100644 --- a/package.json +++ b/package.json @@ -163,7 +163,7 @@ "modern-normalize": "^3.0.1", "react": "^19.0.0 || ^18.0.0 || ^17.0.0", "react-dom": "^19.0.0 || ^18.0.0 || ^17.0.0", - "stream-chat": "^10.2.0" + "stream-chat": "^10.3.1" }, "peerDependenciesMeta": { "@a2ui/react": { @@ -246,7 +246,7 @@ "react-dom": "^19.2.6", "sass": "^1.100.0", "semantic-release": "^25.0.3", - "stream-chat": "^10.2.0", + "stream-chat": "^10.3.1", "typescript": "^6.0.3", "typescript-eslint": "^8.59.4", "vite": "^8.1.3", 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..288ba1a140 100644 --- a/src/components/Chat/hooks/useChat.ts +++ b/src/components/Chat/hooks/useChat.ts @@ -43,6 +43,8 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.registerSubscriptions(); client.reminders.registerSubscriptions(); client.reminders.initTimers(); + const releaseScheduledMessagePaginators = + client.scheduledMessagePaginators.registerSubscriptions(); return () => { releaseChannelManager(); @@ -50,6 +52,7 @@ export const useChat = ({ client }: UseChatParams) => { client.polls.unregisterSubscriptions(); client.reminders.unregisterSubscriptions(); client.reminders.clearTimers(); + releaseScheduledMessagePaginators(); }; }, [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/Form/SearchInput.tsx b/src/components/Form/SearchInput.tsx new file mode 100644 index 0000000000..df50a0849e --- /dev/null +++ b/src/components/Form/SearchInput.tsx @@ -0,0 +1,74 @@ +import clsx from 'clsx'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; + +import { useComponentContextIcons, useTranslationContext } from '../../context'; +import { Button } from '../Button'; +import { TextInput } from './TextInput'; + +export type SearchInputProps = { + onSearchChange: (query: string) => void; + autoFocus?: boolean; + className?: string; + resetKey?: number; +}; + +export const SearchInput = React.memo( + ({ autoFocus, className, onSearchChange, resetKey }: SearchInputProps) => { + const { IconSearch, IconXCircle } = useComponentContextIcons(); + const { t } = useTranslationContext(); + const inputRef = useRef(null); + const [searchInput, setSearchInput] = useState(''); + + useEffect(() => { + setSearchInput(''); + }, [resetKey]); + + const handleSearchChange = useCallback( + (event: React.ChangeEvent) => { + const { value } = event.target; + setSearchInput(value); + onSearchChange(value); + }, + [onSearchChange], + ); + + const clearSearch = () => { + setSearchInput(''); + onSearchChange(''); + inputRef.current?.focus(); + }; + + return ( + } + onChange={handleSearchChange} + placeholder={t('common.search.ariaLabel', 'Search')} + ref={inputRef} + trailing={ + + } + type='search' + value={searchInput} + /> + ); + }, +); + +SearchInput.displayName = 'SearchInput'; diff --git a/src/components/Form/__tests__/SearchInput.test.tsx b/src/components/Form/__tests__/SearchInput.test.tsx new file mode 100644 index 0000000000..d3299f2bd7 --- /dev/null +++ b/src/components/Form/__tests__/SearchInput.test.tsx @@ -0,0 +1,64 @@ +import React from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; + +import { axe } from '../../../../axe-helper'; +import { SearchInput } from '../SearchInput'; + +const renderSearchInput = (resetKey?: number) => { + const onSearchChange = vi.fn(); + const view = render( + , + ); + const input = screen.getByRole('searchbox') as HTMLInputElement; + const clearButton = screen.getByRole('button', { hidden: true, name: 'Clear search' }); + return { clearButton, input, onSearchChange, view }; +}; + +describe('SearchInput', () => { + it('reports each change of the query', () => { + const { input, onSearchChange } = renderSearchInput(); + + fireEvent.change(input, { target: { value: 'demo' } }); + + expect(input.value).toBe('demo'); + expect(onSearchChange).toHaveBeenLastCalledWith('demo'); + }); + + it('hides the clear button while the query is empty', () => { + const { clearButton, input } = renderSearchInput(); + + expect(clearButton).toHaveClass('str-chat__form-text-input__clear-button--hidden'); + + fireEvent.change(input, { target: { value: 'demo' } }); + + expect(clearButton).not.toHaveClass( + 'str-chat__form-text-input__clear-button--hidden', + ); + }); + + it('clears the query and keeps the focus in the field', () => { + const { clearButton, input, onSearchChange } = renderSearchInput(); + fireEvent.change(input, { target: { value: 'demo' } }); + + fireEvent.click(clearButton); + + expect(input.value).toBe(''); + expect(onSearchChange).toHaveBeenLastCalledWith(''); + expect(input).toHaveFocus(); + }); + + it('empties the field when the reset key changes', () => { + const { input, onSearchChange, view } = renderSearchInput(1); + fireEvent.change(input, { target: { value: 'demo' } }); + + view.rerender(); + + expect(input.value).toBe(''); + }); + + it('passes axe checks', async () => { + const { view } = renderSearchInput(); + + expect(await axe(view.container)).toHaveNoViolations(); + }); +}); diff --git a/src/components/Form/index.ts b/src/components/Form/index.ts index 1b4ba1b9ce..e570014dd4 100644 --- a/src/components/Form/index.ts +++ b/src/components/Form/index.ts @@ -2,6 +2,7 @@ export * from './Checkbox'; export * from './Dropdown'; export * from './FieldError'; export * from './NumericInput'; +export * from './SearchInput'; export * from './SwitchField'; export * from './TextInput'; export * from './TextInputFieldSet'; 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', { 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/MessageComposer/MessageComposer.tsx b/src/components/MessageComposer/MessageComposer.tsx index 4799d07770..3f635a451e 100644 --- a/src/components/MessageComposer/MessageComposer.tsx +++ b/src/components/MessageComposer/MessageComposer.tsx @@ -102,7 +102,9 @@ const MessageComposerProvider = (props: PropsWithChildren) // it: clearing on unmount would discard an edit the supplier still holds (visible in Strict // Mode). if (messageComposer === suppliedComposer) return; - draftSaved.finally(() => messageComposer.clear()); + draftSaved.finally(() => { + if (!messageComposer.editedScheduledMessage) messageComposer.clear(); + }); }, [messageComposer, suppliedComposer], ); @@ -120,7 +122,7 @@ const MessageComposerProvider = (props: PropsWithChildren) messageComposer.channel .getDraft({ parent_id: threadId }) .then(({ draft }) => { - if (draft) { + if (draft && !messageComposer.editedScheduledMessage) { messageComposer.initState({ composition: draft }); } }) diff --git a/src/components/MessageComposer/MessageComposerActions.tsx b/src/components/MessageComposer/MessageComposerActions.tsx index bce104db9f..5b6df26018 100644 --- a/src/components/MessageComposer/MessageComposerActions.tsx +++ b/src/components/MessageComposer/MessageComposerActions.tsx @@ -1,4 +1,4 @@ -import React, { useCallback } from 'react'; +import React, { useCallback, useEffect, useMemo } from 'react'; import { StopAIGenerationButton as DefaultStopAIGenerationButton } from './StopAIGenerationButton'; import { CooldownTimer as DefaultCooldownTimer } from './CooldownTimer'; import { SendButton as DefaultSendButton } from './SendButton'; @@ -7,6 +7,7 @@ import { useComponentContext, useComponentContextIcons, useMessageComposerContext, + useTranslationContext, } from '../../context'; import { useAIState } from '../AIStateIndicator'; import { @@ -17,17 +18,41 @@ import { import { AudioRecordingButtonWithNotification } from '../MediaRecorder/AudioRecorder/AudioRecordingButtonWithNotification'; import { useIsCooldownActive } from './hooks/useIsCooldownActive'; import { AIStates } from 'stream-chat'; -import type { AIState, MessageComposerState, TextComposerState } from 'stream-chat'; +import type { + AIState, + MessageComposer, + MessageComposerState, + TextComposerState, +} from 'stream-chat'; import { useStateStore } from '../../store'; import { useInertWhenHidden } from '../Accessibility'; +import { CHANNEL_CONTAINER_ID } from '../Channel/constants'; +import { GlobalModal } from '../Modal'; +import { Portal } from '../Portal/Portal'; +import { useCanScheduleMessage } from '../ScheduledMessages/hooks/useCanScheduleMessage'; +import { useScheduleComposition } from '../ScheduledMessages/hooks/useScheduleComposition'; +import { ScheduleMessageButton as DefaultScheduleMessageButton } from '../ScheduledMessages/ScheduleMessageButton'; +import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from '../ScheduledMessages/ScheduleTimeDialog'; +import { + getScheduleDialogId, + isFailedScheduledMessage, + toCompositionPreview, +} from '../ScheduledMessages/utils'; +import { useDialogIsOpen, useDialogOnNearestManager } from '../Dialog'; // Typed as `AIState[]` because an inferred array of the literal-typed `AIStates` members would // reject the wide `AIState` that `useAIState` returns. const STOPPABLE_AI_STATES: readonly AIState[] = [AIStates.Thinking, AIStates.Generating]; -const messageComposerStateSelector = ({ editedMessage }: MessageComposerState) => ({ - editedMessage, -}); +const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); + +const createMessageComposerStateSelector = + (messageComposer: MessageComposer) => (state: MessageComposerState) => ({ + isEditing: messageComposer.hasEditInProgress, + isSchedulingAgain: + !!state.editedScheduledMessage && + isFailedScheduledMessage(state.editedScheduledMessage), + }); const textComposerStateSelector = ({ command, text }: TextComposerState) => ({ command, @@ -35,17 +60,38 @@ const textComposerStateSelector = ({ command, text }: TextComposerState) => ({ }); export const MessageComposerActions = () => { + const { t } = useTranslationContext(); const { IconCheckmark, IconSend } = useComponentContextIcons(); const channel = useChannel(); const { hideSendButton } = useMessageComposerContext(); const messageComposer = useMessageComposerController(); const { CooldownTimer = DefaultCooldownTimer, + Modal = GlobalModal, + ScheduleMessageButton: ScheduleMessageButtonOverride, + ScheduleTimeDialog = DefaultScheduleTimeDialog, SendButton, StopAIGenerationButton: StopAIGenerationButtonOverride, } = useComponentContext(); - const { editedMessage } = useStateStore( + const canScheduleMessage = useCanScheduleMessage(); + const { scheduleMessageFromDialog } = useScheduleComposition(); + + const scheduleDialogId = getScheduleDialogId(messageComposer); + const { dialog: scheduleDialog, dialogManager } = useDialogOnNearestManager({ + id: scheduleDialogId, + }); + const isScheduleDialogRequested = useDialogIsOpen(scheduleDialogId, dialogManager?.id); + const schedulePreview = useMemo( + () => (isScheduleDialogRequested ? toCompositionPreview(messageComposer) : undefined), + [isScheduleDialogRequested, messageComposer], + ); + + const messageComposerStateSelector = useMemo( + () => createMessageComposerStateSelector(messageComposer), + [messageComposer], + ); + const { isEditing, isSchedulingAgain } = useStateStore( messageComposer.state, messageComposerStateSelector, ); @@ -69,12 +115,31 @@ export const MessageComposerActions = () => { const { aiState } = useAIState(channel); const stopGenerating = useCallback(() => channel?.stopAIResponse(), [channel]); + + useEffect( + () => () => dialogManager?.close(scheduleDialogId), + [dialogManager, scheduleDialogId], + ); + const shouldDisplayStopAIGeneration = STOPPABLE_AI_STATES.includes(aiState) && !!StopAIGenerationButton; // 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 || isSchedulingAgain || 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,19 +149,54 @@ export const MessageComposerActions = () => { return null; } else if (isCooldownActive) { content = ; - } else if (contentIsEmpty && !editedMessage && !command && recordingEnabled) { + } else if (isSchedulingAgain) { + content = sendButton; + } else if ( + contentIsEmpty && + !isEditing && + !command && + recordingEnabled && + !isScheduleDialogRequested + ) { content = ; - } else if (SendButton) { - content = ; - } else { + } else if (canScheduleMessage && ScheduleMessageButton) { content = ( - - {editedMessage || command ? : } - +
    + {sendButton} + +
    ); + } else { + content = sendButton; } - return
    {content}
    ; + return ( +
    + {content} + + + {schedulePreview && ( + + )} + + +
    + ); }; export const AdditionalMessageComposerActions = () => { diff --git a/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx b/src/components/MessageComposer/MessageComposerPreviews.defaults.tsx index c880b5b30a..6bc1b245e6 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 ; @@ -87,6 +110,11 @@ const DefaultMessageComposerPreviewComponents = { * extend it and pass the result as `messageComposerPreviewSet`. */ export const defaultMessageComposerPreviewSet: MessageComposerPreviewSetItem[] = [ + { + Component: DefaultMessageComposerPreviewComponents.ScheduledMessage, + isVisible: ({ editedScheduledMessage }) => !!editedScheduledMessage, + type: 'scheduledMessage', + }, { Component: DefaultMessageComposerPreviewComponents.EditedMessage, isVisible: ({ editedMessage }) => !!editedMessage, @@ -94,7 +122,8 @@ export const defaultMessageComposerPreviewSet: MessageComposerPreviewSetItem[] = }, { Component: DefaultMessageComposerPreviewComponents.QuotedMessage, - // The edited message preview takes the quoted message's place while editing. + // 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/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 && }
    ; 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/MessageComposer/__tests__/MessageInput.test.tsx b/src/components/MessageComposer/__tests__/MessageInput.test.tsx index 6af915e6b7..748f81f661 100644 --- a/src/components/MessageComposer/__tests__/MessageInput.test.tsx +++ b/src/components/MessageComposer/__tests__/MessageInput.test.tsx @@ -63,6 +63,7 @@ import { generateLocalAttachmentData, generateMember, generateMessage, + generateScheduledMessage, generateScrapedDataAttachment, generateUser, initClientWithChannels, @@ -2251,6 +2252,23 @@ describe(`MessageInputFlat`, () => { expect(consoleError).toHaveBeenCalledWith(error); }); + it('keeps a scheduled message being edited', async () => { + const { customChannel, customClient } = await setup(); + const { messageComposer } = customChannel; + const scheduledMessage = generateScheduledMessage({ + cid: customChannel.cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + }); + const { unmount } = await renderComponent({ customChannel, customClient }); + await act(() => messageComposer.editScheduledMessage(scheduledMessage)); + + unmount(); + await flushMicrotasks(); + + expect(messageComposer.editedScheduledMessage?.id).toBe(scheduledMessage.id); + expect(messageComposer.textComposer.text).toBe('Launch moved to Monday'); + }); + it('saves the draft of a supplied composer but leaves clearing it to its owner', async () => { const { customChannel, customClient } = await setup(); const supplied = new MessageComposerController({ diff --git a/src/components/MessageComposer/hooks/useMessageComposerPreviewState.ts b/src/components/MessageComposer/hooks/useMessageComposerPreviewState.ts index 4b48067980..d28ba31510 100644 --- a/src/components/MessageComposer/hooks/useMessageComposerPreviewState.ts +++ b/src/components/MessageComposer/hooks/useMessageComposerPreviewState.ts @@ -14,10 +14,12 @@ import { useMessageComposerController } from './useMessageComposerController'; const messageComposerStateSelector = ({ editedMessage, + editedScheduledMessage, pollId, quotedMessage, }: MessageComposerState) => ({ 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..650b540296 100644 --- a/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts +++ b/src/components/MessageComposer/hooks/useMessageComposerSubmitFn.ts @@ -1,20 +1,35 @@ import { useCallback } from 'react'; +import { useNearestDialogManagerContext } from '../../../context'; +import { + getScheduleDialogId, + isFailedScheduledMessage, +} 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, + * opens the schedule dialog for a failed scheduled message loaded to be scheduled again, and 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 messageComposer = useMessageComposerController(); + const { dialogManager } = useNearestDialogManagerContext() ?? {}; - return useCallback( - () => - messageComposer.editedMessage ? messageComposer.update() : messageComposer.send(), - [messageComposer], - ); + return useCallback(() => { + const { editedScheduledMessage } = messageComposer; + if (editedScheduledMessage && isFailedScheduledMessage(editedScheduledMessage)) { + dialogManager?.open({ id: getScheduleDialogId(messageComposer) }); + return; + } + if (editedScheduledMessage) { + return messageComposer.updateScheduledMessage(); + } + return messageComposer.editedMessage + ? messageComposer.update() + : messageComposer.send(); + }, [dialogManager, messageComposer]); }; 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); diff --git a/src/components/ScheduledMessages/ListStates.tsx b/src/components/ScheduledMessages/ListStates.tsx new file mode 100644 index 0000000000..39dee7be67 --- /dev/null +++ b/src/components/ScheduledMessages/ListStates.tsx @@ -0,0 +1,132 @@ +import React from 'react'; + +import { + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { + ListLoadErrorUI as SharedListLoadErrorUI, + ListLoadingNextPageUI as SharedListLoadingNextPageUI, +} from '../ListStates'; +import type { ListLoadErrorUIProps, ListLoadingNextPageUIProps } from '../ListStates'; + +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 = () => ( +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +); + +export const ScheduledMessageListLoading = () => { + const { t } = useTranslationContext(); + + return ( +
    + {loadingRowKeys.map((key) => ( + + ))} +
    + ); +}; + +export const ScheduledMessageListEmpty = () => { + const { t } = useTranslationContext(); + const { IconClock } = useComponentContextIcons(); + + 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.', + )} +

    +
    + ); +}; + +export const ScheduledMessageListEmptySearchResults = () => { + const { t } = useTranslationContext(); + const { IconSearch } = useComponentContextIcons(); + + return ( +
    + +

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

    +
    + ); +}; + +const ScheduledMessageListLoadErrorTitle = () => { + const { t } = useTranslationContext(); + + return ( + <> + {t( + 'scheduledMessages.couldntLoadScheduledMessages', + "Couldn't load scheduled messages", + )} + + ); +}; + +export const ScheduledMessageListLoadError = (props: ListLoadErrorUIProps) => ( + +); + +export const ScheduledMessageListFirstPageLoadingUI = () => { + const { ListFirstPageLoadingUI = ScheduledMessageListLoading } = useComponentContext(); + + return ; +}; + +export const ScheduledMessageListEmptyUI = () => { + const { ListEmptyUI = ScheduledMessageListEmpty } = useComponentContext(); + + return ; +}; + +export const ScheduledMessageListLoadingNextPageUI = ( + props: ListLoadingNextPageUIProps, +) => { + const { ListLoadingNextPageUI = SharedListLoadingNextPageUI } = useComponentContext(); + + return ; +}; + +export const ScheduledMessageListLoadErrorUI = (props: ListLoadErrorUIProps) => { + const { ListLoadErrorUI = ScheduledMessageListLoadError } = useComponentContext(); + + return ; +}; 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/ScheduleMessageButton.tsx b/src/components/ScheduledMessages/ScheduleMessageButton.tsx new file mode 100644 index 0000000000..607977e028 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleMessageButton.tsx @@ -0,0 +1,167 @@ +import React, { useEffect, useRef } from 'react'; +import type { MessageComposer } from 'stream-chat'; + +import { + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { Button } from '../Button'; +import { + ContextMenu, + ContextMenuButton, + ContextMenuHeader, + useDialogIsOpen, + useDialogOnNearestManager, +} from '../Dialog'; +import { useMessageComposerHasSendableData } from '../MessageComposer/hooks'; +import { useMessageComposerController } from '../MessageComposer/hooks/useMessageComposerController'; +import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit'; +import { useScheduleComposition } from './hooks/useScheduleComposition'; +import { getScheduleDialogId, getSchedulePresets, getScheduleTimeBounds } from './utils'; + +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 ( + + {title} + + ); +}; + +/** + * 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 { IconChevronUp, IconClock } = useComponentContextIcons(); + const { ContextMenu: ContextMenuComponent = ContextMenu } = useComponentContext(); + const messageComposer = useMessageComposerController(); + const { scheduleMessage } = useScheduleComposition(); + const hasSendableData = useMessageComposerHasSendableData(); + + 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 scheduleDialogId = getScheduleDialogId(messageComposer); + const { dialog: scheduleDialog } = useDialogOnNearestManager({ id: scheduleDialogId }); + const isScheduleDialogOpen = useDialogIsOpen(scheduleDialogId, dialogManager?.id); + const buttonRef = useRef(null); + const openedScheduleDialogRef = useRef(false); + + const openDialog = () => { + menu.close(); + openedScheduleDialogRef.current = true; + scheduleDialog.open(); + }; + + useEffect(() => { + if (isScheduleDialogOpen || !openedScheduleDialogRef.current) return; + openedScheduleDialogRef.current = false; + const frame = requestAnimationFrame(() => buttonRef.current?.focus()); + return () => cancelAnimationFrame(frame); + }, [isScheduleDialogOpen]); + + return ( + <> + + ('.str-chat__split-send-button') ?? + buttonRef.current + } + tabIndex={-1} + > + {isMenuOpen && + getSchedulePresets( + new Date(), + getScheduleTimeBounds(messageComposer.channel), + ).map((scheduledAt) => ( + { + if (isLimitReached) return; + menu.close(); + scheduleMessage(scheduledAt).catch(() => undefined); + }} + > + {t('timestamp.SchedulePreset', { timestamp: scheduledAt })} + + ))} +
    + { + if (!isLimitReached) openDialog(); + }} + > + {t('scheduledMessages.customTime', 'Custom time')} + + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduleTimeDialog.tsx b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx new file mode 100644 index 0000000000..37decfccbf --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleTimeDialog.tsx @@ -0,0 +1,232 @@ +import React, { type MouseEvent, useEffect, useState } from 'react'; +import { ScheduledMessageErrorReason } from 'stream-chat'; +import type { Channel, LocalMessage } from 'stream-chat'; + +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 { QuotedMessagePreviewUI } from '../MessageComposer/QuotedMessagePreview'; +import { ScheduleDateInput as DefaultScheduleDateInput } from './ScheduleDateInput'; +import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; +import { ScheduleTimeInput as DefaultScheduleTimeInput } from './ScheduleTimeInput'; +import { + formatTimeZoneOffset, + fromInputValues, + getDefaultScheduledAt, + getScheduleTimeBounds, + getScheduleTimeError, + toDateInputValue, + toTimeInputValue, +} from './utils'; +import { + getScheduledMessageErrorKey, + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS, +} from './translations'; + +/** 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; + /** 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; +}; + +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 NATIVE_PICKER_INPUT_SELECTOR = 'input[type="date"], input[type="time"]'; + +const openNativePicker = ({ target }: MouseEvent) => { + const input = (target as Element) + .closest('.str-chat__form-text-input__wrapper') + ?.querySelector(NATIVE_PICKER_INPUT_SELECTOR); + try { + input?.showPicker?.(); + } catch { + return; + } +}; + +/** 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 { + ScheduleDateInput = DefaultScheduleDateInput, + ScheduleTimeInput = DefaultScheduleTimeInput, + } = useComponentContext(); + const channelDisplayName = useChannelDisplayName(channel); + const isOnline = useWSConnectionState()?.isHealthy ?? false; + const isMounted = useIsMounted(); + + // 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(); + + // 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 timeErrorMessage = + timeError && + ((timeError === ScheduledMessageErrorReason.TooSoon && tooSoonMessage) || + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS[timeError]?.(t)); + 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); + if (isMounted.current) close(); + } catch (error) { + if (!isMounted.current) return; + setSubmitError(error); + setStatus('failed'); + } + }; + + const submitErrorKey = getScheduledMessageErrorKey(submitError); + + return ( + + + + + {status === 'failed' && ( + + {(submitErrorKey && + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS[submitErrorKey]?.(t)) ?? + errorMessage} + + )} +
    + + +
    + {timeErrorMessage ? ( + {timeErrorMessage} + ) : ( + + {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/ScheduleTimeInput.tsx b/src/components/ScheduledMessages/ScheduleTimeInput.tsx new file mode 100644 index 0000000000..afb1fced3a --- /dev/null +++ b/src/components/ScheduledMessages/ScheduleTimeInput.tsx @@ -0,0 +1,22 @@ +import React from 'react'; + +import { useComponentContextIcons } from '../../context'; +import { TextInput } from '../Form'; +import type { ScheduleTimeInputProps } from './ScheduleTimeDialog'; + +export const ScheduleTimeInput = ({ label, onChange, value }: ScheduleTimeInputProps) => { + const { IconCaretDown, IconClock } = useComponentContextIcons(); + + return ( + } + onChange={({ target }) => onChange(target.value)} + required + trailing={} + type='time' + value={value} + /> + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageActions.tsx b/src/components/ScheduledMessages/ScheduledMessageActions.tsx new file mode 100644 index 0000000000..62cc0b7dcb --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageActions.tsx @@ -0,0 +1,456 @@ +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 { + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, +} from './constants'; +import { getChannelByCid } 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', 'reschedule', '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, reschedule 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 { IconClock } = 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( + () => + getChannelByCid( + client, + scheduledMessage.cid, + ).messageOperations.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: an edit button beside the menu, and the + * rest in the menu. A failed message is edited or rescheduled into a new scheduled message. + * 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, + placement: 'quick', + 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/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 new file mode 100644 index 0000000000..c6e90942c2 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageItem.tsx @@ -0,0 +1,382 @@ +import clsx from 'clsx'; +import React, { + type MouseEvent, + type RefObject, + useCallback, + useRef, + useState, +} from 'react'; +import { nsToDate, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +import { + useChatContext, + useComponentContext, + useComponentContextIcons, + useTranslationContext, +} from '../../context'; +import { ChannelAvatar } from '../Avatar'; +import { useChannelCapabilities } from '../Channel/hooks/useChannelCapabilities'; +import { useIsMounted } from '../Channel/hooks/useIsMounted'; +import { useChannelPreviewInfo } from '../ChannelListItem/hooks/useChannelPreviewInfo'; +import { ContextMenu, useDialogIsOpen, useDialogOnNearestManager } from '../Dialog'; +import { useSplitActionSet } from '../Chat/hooks/useSplitActionSet'; +import { GlobalModal } from '../Modal'; +import { useNotificationApi } from '../Notifications'; +import { SummarizedMessagePreview } from '../SummarizedMessagePreview'; +import { useStableId } from '../UtilityComponents/useStableId'; +import { VisuallyHidden } from '../VisuallyHidden'; +import { useScheduledMessagePreview } from './hooks/useScheduledMessagePreview'; +import { useRescheduleDialogProps } from './hooks/useRescheduleDialogProps'; +import { ScheduledMessageDeleteAlert as DefaultScheduledMessageDeleteAlert } from './ScheduledMessageDeleteAlert'; +import { ScheduleTimeDialog as DefaultScheduleTimeDialog } from './ScheduleTimeDialog'; +import { + defaultScheduledMessageActionSet, + ScheduledMessageActionsContextProvider, + useBaseScheduledMessageActionSetFilter, + useScheduledMessageActionsContext, +} from './ScheduledMessageActions'; +import type { + ScheduledMessageActionsContextValue, + ScheduledMessageActionSetItem, + ScheduledMessageItemDialog, +} from './ScheduledMessageActions'; +import { + SCHEDULE_MESSAGE_CAPABILITY, + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, +} from './constants'; +import { + getScheduledMessageErrorKey, + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS, + SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS, +} from './translations'; +import { getChannelByCid, isFailedScheduledMessage } 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. */ + openInComposer?: (scheduledMessage: ScheduledMessageResponse) => void; + /** + * The message's actions, in render order. Defaults to `defaultScheduledMessageActionSet`; + * filter, reorder or extend it. Filtered by `useBaseScheduledMessageActionSetFilter`. + */ + scheduledMessageActionSet?: ScheduledMessageActionSetItem[]; +}; + +/** A scheduled message: when it is sent, where, its status and what can be done with it. */ +export const ScheduledMessageItem = ({ + openInComposer, + scheduledMessage, + scheduledMessageActionSet = defaultScheduledMessageActionSet, +}: ScheduledMessageItemProps) => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const { IconExclamationTriangleFill, IconLoading } = useComponentContextIcons(); + const { + Modal = GlobalModal, + ScheduledMessageDeleteAlert = DefaultScheduledMessageDeleteAlert, + ScheduleTimeDialog = DefaultScheduleTimeDialog, + } = useComponentContext(); + const { addNotification } = useNotificationApi(); + const isMounted = useIsMounted(); + + 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({ + channel: loadedChannel, + }); + const capabilities = useChannelCapabilities({ channel: loadedChannel }); + 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); + const isSending = status === SCHEDULED_MESSAGE_STATUS.Sending; + const isThreadReply = !!scheduledMessage.message.parent_id; + const failureReasonTranslation = failure_reason + ? SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS[failure_reason] + : undefined; + const failureReasonText = + failureReasonTranslation === null + ? undefined + : (failureReasonTranslation?.(t) ?? + t('scheduledMessages.couldntSendTryAgain', "Couldn't send. Try again")); + // 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 = + !loadedChannel || + capabilities.has(SCHEDULE_MESSAGE_CAPABILITY) || + (isFailed && capabilities.has('send-message')); + + const menuButtonRef = useRef(null); + const [openDialog, setOpenDialog] = useState(); + const [isPending, setIsPending] = useState(false); + + const closeDialog = () => { + setOpenDialog(undefined); + requestAnimationFrame(() => menuButtonRef.current?.focus()); + }; + + const runRequest: ScheduledMessageActionsContextValue['runRequest'] = async ( + request, + failure, + success, + ) => { + setIsPending(true); + try { + await request(); + if (success) { + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + severity: 'success', + ...success, + }); + } + } catch (error) { + const errorKey = getScheduledMessageErrorKey(error); + addNotification({ + emitter: SCHEDULED_MESSAGES_EMITTER, + error: error as Error, + severity: 'error', + ...failure, + message: + (errorKey && SCHEDULED_MESSAGE_ERROR_TRANSLATIONS[errorKey]?.(t)) ?? + failure.message, + }); + } finally { + if (isMounted.current) setIsPending(false); + } + }; + + 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), { + message: t( + 'scheduledMessages.couldntDeleteTheScheduledMessageTryAgain', + "Couldn't delete the scheduled message. Try again", + ), + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.deleteFailed, + }); + }; + + return ( +
    + + + + + {!canEdit && ( + + {t( + 'scheduledMessages.cantSendInThisChannel', + "Unavailable: you can't send messages in this channel", + )} + + )} +
    +
    + + {openDialog === 'reschedule' && ( + + )} + + + {openDialog === 'delete' && ( + + )} + +
    + ); +}; + +/** + * 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 new file mode 100644 index 0000000000..85a82b991f --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageList.tsx @@ -0,0 +1,214 @@ +import React, { useEffect, useMemo, useRef } from 'react'; +import type { ComponentType } from 'react'; +import type { + ChannelDataState, + PaginatorState, + ScheduledMessageResponse, + ScheduledMessagesView, +} from 'stream-chat'; + +import { + useChatContext, + useComponentContext, + useTranslationContext, +} from '../../context'; +import { useStateStore } from '../../store'; +import { useChannelCapabilities } from '../Channel/hooks/useChannelCapabilities'; +import { InfiniteScrollPaginator } from '../InfiniteScrollPaginator'; +import { useFirstPageLoadRetry } from '../ListStates/hooks'; +import { getFirstPageLoadError } from '../ListStates/utils'; +import { SCHEDULE_MESSAGE_CAPABILITY } from './constants'; +import { useScheduledMessages } from './hooks'; +import { + ScheduledMessageListEmptySearchResults, + ScheduledMessageListEmptyUI, + ScheduledMessageListFirstPageLoadingUI, + ScheduledMessageListLoadErrorUI, + ScheduledMessageListLoadingNextPageUI, +} from './ListStates'; +import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; +import { ScheduledMessageItem as DefaultScheduledMessageItem } from './ScheduledMessageItem'; +import { ScheduledMessagesNotice } from './ScheduledMessagesNotice'; +import { getChannelByCid } from './utils'; + +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 + * paginator is a channel's, the list also says why the channel takes no scheduled messages, if + * it doesn't. Its loading, empty and error states are the `ListFirstPageLoadingUI`, + * `ListEmptyUI`, `ListLoadingNextPageUI` and `ListLoadErrorUI` slots. + */ + scheduledMessages: ScheduledMessagesView; + /** Lists only the messages it accepts, e.g. the search from `useScheduledMessagesSearch`. */ + filter?: (scheduledMessage: ScheduledMessageResponse) => boolean; + /** Messages are scheduled, but none match the search. */ + EmptySearchResultsIndicator?: ComponentType; +}; + +const selectLoadState = (state: PaginatorState) => ({ + firstPageLoadError: getFirstPageLoadError(state), + hasMoreTail: state.hasMoreTail, + isFirstPageLoading: state.items === undefined && !state.lastQueryError, + isLoading: state.isLoading, + lastQueryError: state.lastQueryError, +}); + +const selectFrozen = ({ data }: ChannelDataState) => ({ 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 capabilities = useChannelCapabilities({ channel }); + const { frozen } = useStateStore(channel.state, selectFrozen); + + if (capabilities.has(SCHEDULE_MESSAGE_CAPABILITY)) 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", + )} + + ); +}; + +/** + * A scheduled-message view's messages, earliest first, loading further pages on scroll, with their + * list states. A view of a thread and a `filter` (searching) narrow its paginator's loaded + * messages, so while none of + * them are shown and more pages exist, the list loads the next one: with nothing shown there is + * nothing to scroll, and the messages to show may be on a page not loaded yet. + */ +export const ScheduledMessageList = ({ + EmptySearchResultsIndicator = ScheduledMessageListEmptySearchResults, + filter, + openInComposer, + scheduledMessages: view, +}: ScheduledMessageListProps) => { + const { ScheduledMessageItem = DefaultScheduledMessageItem } = useComponentContext(); + const { paginator } = view; + const { scheduledMessages } = useScheduledMessages(view); + const shownMessages = useMemo( + () => (filter ? scheduledMessages.filter(filter) : scheduledMessages), + [filter, scheduledMessages], + ); + const { t } = useTranslationContext(); + const { + firstPageLoadError, + hasMoreTail, + isFirstPageLoading, + isLoading, + lastQueryError, + } = useStateStore(paginator.state, selectLoadState); + const firstPageLoadRetry = useFirstPageLoadRetry({ + firstPageLoadError, + loadedMessage: t('scheduledMessages.loaded', 'Scheduled messages loaded'), + paginator, + reload: paginator.reload, + }); + const showsNothing = !isFirstPageLoading && !shownMessages.length; + // stops at a failed page instead of retrying it + 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(); + }, [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 ( + + ); + } + if (isFirstPageLoading) return ; + if (loadsFurther) { + return ; + } + if (furtherPageLoadError) { + return ( + + ); + } + if (showsNothing) { + // some are scheduled, but the filter accepts none of them + return scheduledMessages.length ? ( + + ) : ( + + ); + } + return ( + +
      + {shownMessages.map((scheduledMessage) => ( +
    • + +
    • + ))} +
    + +
    + ); + }; + + return ( + <> + {paginator.cid && } + {renderContent()} + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx new file mode 100644 index 0000000000..b341370f03 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessageListDialog.tsx @@ -0,0 +1,95 @@ +import React from 'react'; + +import { useComponentContext, useTranslationContext } from '../../context'; +import { CHANNEL_CONTAINER_ID } from '../Channel/constants'; +import { Prompt } from '../Dialog'; +import { SearchInput } from '../Form'; +import { GlobalModal } from '../Modal'; +import { Portal } from '../Portal/Portal'; +import { useChannelScheduledMessages, useScheduledMessagesSearch } from './hooks'; +import type { ScheduledMessagesView } from 'stream-chat'; +import type { ScheduledMessageItemProps } from './ScheduledMessageItem'; +import { ScheduledMessageList as DefaultScheduledMessageList } from './ScheduledMessageList'; + +const getChannelContainer = () => document.getElementById(CHANNEL_CONTAINER_ID); + +export type ScheduledMessageListDialogProps = Pick< + ScheduledMessageItemProps, + 'openInComposer' +> & { + close: () => void; + open: boolean; + /** What to list: `channel.scheduledMessages` or `thread.scheduledMessages`. */ + scheduledMessages: ScheduledMessagesView; +}; + +/** The dialog's content, mounted only while it is open: the search starts empty each time. */ +const ScheduledMessageListDialogBody = ({ + openInComposer, + scheduledMessages: view, +}: Pick) => { + const { ScheduledMessageList = DefaultScheduledMessageList } = useComponentContext(); + const { scheduledMessages } = useChannelScheduledMessages(view); + const { filter, setSearchQuery } = useScheduledMessagesSearch(); + + return ( + + {scheduledMessages.length > 0 && ( + + )} + + + ); +}; + +/** + * 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, + * or search differently with `useScheduledMessagesSearch`'s `filter`. + */ +export const ScheduledMessageListDialog = ({ + close, + open, + openInComposer, + scheduledMessages, +}: ScheduledMessageListDialogProps) => { + const { t } = useTranslationContext(); + const { Modal = GlobalModal } = useComponentContext(); + + return ( + + + {open && ( + + + + + )} + + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessagePreview.tsx b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx new file mode 100644 index 0000000000..f22ee824ee --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessagePreview.tsx @@ -0,0 +1,38 @@ +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; +}; + +export const ScheduledMessagePreview = ({ + onCancel, + scheduledMessage, +}: ScheduledMessagePreviewProps) => { + const { t } = useTranslationContext(); + + const previewMessage = useScheduledMessagePreview(scheduledMessage); + + const isFailed = isFailedScheduledMessage(scheduledMessage); + const authorLabel = isFailed + ? t('scheduledMessages.scheduleAgain', 'Schedule again') + : t('scheduledMessages.editScheduledMessage', 'Edit scheduled message'); + const removeLabel = isFailed + ? t('scheduledMessages.cancelSchedulingAgain.ariaLabel', 'Cancel scheduling again') + : t('scheduledMessages.cancelEdit.ariaLabel', 'Cancel edit'); + + return ( + + ); +}; diff --git a/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx new file mode 100644 index 0000000000..2d18acafd9 --- /dev/null +++ b/src/components/ScheduledMessages/ScheduledMessagesBanner.tsx @@ -0,0 +1,170 @@ +import clsx from 'clsx'; +import React, { useEffect, useRef, useState } from 'react'; +import { nsToDate, Thread } 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 } from './constants'; +import { + useChannelScheduledMessages, + useChannelWideScheduledMessagesView, + useOpenScheduledMessageInComposer, +} from './hooks'; +import { ScheduledMessageListDialog as DefaultScheduledMessageListDialog } from './ScheduledMessageListDialog'; +import { useChannelScheduledMessageLimit } from './hooks/useChannelScheduledMessageLimit'; +import { isFailedScheduledMessage } from './utils'; + +const selectIsLoaded = ({ items }: PaginatorState) => ({ + isLoaded: items !== undefined, +}); + +const selectIsEditing = ({ + editedMessage, + editedScheduledMessage, +}: MessageComposerState) => ({ + 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 sent message or a failed scheduled one; 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 { channel, compositionContext } = messageComposer; + const channelWideView = useChannelWideScheduledMessagesView(channel); + const openInChannelComposer = useOpenScheduledMessageInComposer(channel); + const isThreadComposer = compositionContext instanceof Thread; + // a thread's composer lists the thread's scheduled replies + const view = isThreadComposer ? compositionContext.scheduledMessages : channelWideView; + const { parentId } = view; + const canSchedule = useChannelCapabilities({ channel }).has( + 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(); + 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', + }) + : 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, + }) + : 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(); + if (isThreadComposer) { + void messageComposer.editScheduledMessage(scheduledMessage); + return; + } + void openInChannelComposer(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..2bf65cbb93 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/EditScheduledMessage.test.tsx @@ -0,0 +1,216 @@ +import '../../..'; +import React from 'react'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; + +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 { + 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' }, + scheduled_at: convertDateToTimestamp(SEND_TIME), + }); + 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', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] }); + vi.setSystemTime(WEDNESDAY_MORNING); + }); + + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('previews the message being edited and hides the schedule button', async () => { + const { startEditing } = await renderComposer(); + + await startEditing(); + + 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('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); + 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 [editPreview, quotePreview] = screen.getAllByTestId('quoted-message-preview'); + expect(editPreview).toHaveTextContent('Edit scheduled message'); + expect(quotePreview).toHaveTextContent('Venue options for Saturday'); + + await act(() => + fireEvent.click( + within(quotePreview).getByTestId('quoted-message-preview-dismiss-btn'), + ), + ); + + expect(screen.getAllByTestId('quoted-message-preview')).toHaveLength(1); + expect(messageComposer.quotedMessage).toBeNull(); + expect(screen.getByText('Edit scheduled message')).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('clears the composer 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.getByTestId('quoted-message-preview-dismiss-btn')), + ); + + expect(screen.queryByText('Edit scheduled message')).not.toBeInTheDocument(); + expect(messageComposer.textComposer.text).toBe(''); + }); + + it('labels the preview dismiss button as cancelling the edit', async () => { + const { startEditing } = await renderComposer(); + + await startEditing(); + + expect(screen.getByRole('button', { name: 'Cancel edit' })).toBeInTheDocument(); + }); + + describe('scheduling a failed message again', () => { + it('shows the schedule-again preview and a save button instead of the schedule button', async () => { + const { startSchedulingAgain } = await renderComposer(); + + await startSchedulingAgain(); + + expect(screen.getByText('Schedule again')).toBeInTheDocument(); + expect(screen.getByTestId('send-button')).toBeInTheDocument(); + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + }); + + it('clears the composer 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 scheduling again' })), + ); + + expect(screen.queryByText('Schedule again')).not.toBeInTheDocument(); + expect(messageComposer.textComposer.text).toBe(''); + }); + + it('opens the schedule dialog when saved, instead of sending', async () => { + const { channel, startSchedulingAgain } = await renderComposer(); + const sendMessage = vi.spyOn(channel, 'sendMessage'); + + await startSchedulingAgain(); + await act(() => fireEvent.click(screen.getByTestId('send-button'))); + + expect(await screen.findByTestId('schedule-message-dialog')).toHaveTextContent( + 'Launch moved to Monday', + ); + expect(sendMessage).not.toHaveBeenCalled(); + }); + + it('schedules it from the dialog', async () => { + const { failedMessage, messageComposer, startSchedulingAgain } = + await renderComposer(); + const scheduleMessage = vi + .spyOn(messageComposer, 'scheduleMessage') + .mockResolvedValue({ scheduledMessage: failedMessage, status: 'scheduled' }); + + await startSchedulingAgain(); + await act(() => fireEvent.click(screen.getByTestId('send-button'))); + await screen.findByTestId('schedule-message-dialog'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(scheduleMessage).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx new file mode 100644 index 0000000000..cbba7c5f6a --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduleMessageButton.test.tsx @@ -0,0 +1,713 @@ +import '../../..'; +import React from 'react'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { CORE_NOTIFICATION_TYPE, 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 { enterDate, enterTime, getDateField, getTimeField } from './scheduleTimeFields'; +import type { + ScheduleDateInputProps, + ScheduleTimeInputProps, +} from '../ScheduleTimeDialog'; +import { + convertDateToTimestamp, + erroredScheduledMessageApi, + generateScheduledMessage, + generateUser, + hydrateScheduledMessages, + initClientWithChannels, + sendScheduledMessageApi, + setWSConnectionStatus, + useMockedApis, +} from '../../../mock-builders'; +import { MediaRecorderMock } from '../../../mock-builders/browser'; + +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 = { + 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', 'upload-file'] + : ['send-message', 'upload-file']; + 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, 'scheduleMessage'); + +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('comes back when the command that blocked scheduling is removed', async () => { + const { channel } = await renderComposer({ text: '/giphy hello' }); + const { messageComposer } = channel; + + expect(screen.queryByTestId('schedule-message-button')).not.toBeInTheDocument(); + // 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('hides the chevron once a shared location is attached', async () => { + const { channel } = await renderComposer(); + + expect(screen.getByTestId('schedule-message-button')).toBeInTheDocument(); + + await act(() => + channel.messageComposer.locationComposer.setData({ latitude: 50, longitude: 14 }), + ); + + 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('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: 'Scheduled message sent', + severity: 'success', + type: 'api:scheduled-message:create:sent-now', + }), + ]), + ); + }); + + it('jumps to the sent message from the notification', async () => { + const { channel, client } = await renderComposer(); + const messageId = channel.messageComposer.id; + mockSchedule(channel).mockResolvedValue({ status: 'sent' }); + const jumpToMessage = vi + .spyOn(channel.messagePaginator, 'jumpToMessage') + .mockResolvedValue(true); + + await openMenu(); + await act(() => fireEvent.click(screen.getByText('Tomorrow at 09:00'))); + await waitFor(() => expect(getNotifications(client)).toHaveLength(1)); + + const [viewAction] = getNotifications(client)[0].actions ?? []; + expect(viewAction.label).toBe('View'); + await act(() => { + viewAction.handler(); + }); + + expect(jumpToMessage).toHaveBeenCalledWith(messageId); + }); + + 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('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, [ + 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('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(); + + 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(getDateField()).toHaveValue('2026-10-28'); + expect(getTimeField()).toHaveValue('11:00'); + expect(dialog).toHaveTextContent(/Sent in your time zone \(GMT(\+0)?\)/); + expect(screen.getByRole('button', { name: 'Schedule' })).toBeEnabled(); + }); + + it('shows the picked date in the design format', async () => { + await renderComposer(); + + const dialog = await openDialog(); + enterDate('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(); + 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)); + await waitFor(() => + expect(screen.queryByTestId('schedule-message-dialog')).not.toBeInTheDocument(), + ); + }); + + it('blocks a time before the minimum lead time', async () => { + await renderComposer(); + + await openDialog(); + enterTime('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(); + 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({ + 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', + options: { type: CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed }, + 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("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) => { + 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('disables Schedule while offline and enables it again on reconnect', async () => { + const { client } = await renderComposer(); + + await openDialog(); + await act(() => setWSConnectionStatus(client, false)); + + expect(screen.getByRole('button', { name: 'Schedule' })).toBeDisabled(); + + await act(() => setWSConnectionStatus(client, true)); + + 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(); + 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)); + 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 date and time fields from their slots', 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: { ScheduleDateInput: DateInput, ScheduleTimeInput: TimeInput }, + }); + 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); + + 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(); + }); + }); + + 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__/ScheduledMessageActionSet.test.tsx b/src/components/ScheduledMessages/__tests__/ScheduledMessageActionSet.test.tsx new file mode 100644 index 0000000000..f2bf9f410b --- /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 an edit button, and reschedule and delete from the menu', () => { + expect( + filterActions({ + scheduledMessage: generateScheduledMessage({ + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + status: 'failed', + }), + }), + ).toEqual(['toggle', 'quick:edit', 'dropdown:reschedule', '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 new file mode 100644 index 0000000000..2f072f6da2 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageActions.test.tsx @@ -0,0 +1,663 @@ +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, + useChatContext, +} 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 '../constants'; +import { getChannelByCid } from '../utils'; +import { ScheduledMessageList } from '../ScheduledMessageList'; +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; + +const cid = 'messaging:general'; + +const ChannelScheduledMessageList = ({ + openInComposer, +}: { + openInComposer?: OpenInComposer; +}) => { + const { client } = useChatContext(); + return ( + + ); +}; + +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']; + openInComposer?: OpenInComposer; + scheduledMessage?: ScheduledMessageResponse; +}; + +const renderActions = async ({ + components = {}, + openInComposer, + 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({ openInComposer: 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('opens the actions menu when the row itself is clicked', async () => { + await renderActions({ openInComposer: vi.fn() }); + + await act(() => + fireEvent.click(screen.getByText('Send Thu, Oct 29 at 09:00', { exact: false })), + ); + + expect( + await screen.findByTestId('scheduled-message-actions-menu'), + ).toBeInTheDocument(); + }); + + it('says a sending message is still sending when its row is clicked, opening no menu', async () => { + const { client } = await renderActions({ + scheduledMessage: generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Launch moved to Monday' }, + scheduled_at: convertDateToTimestamp(new Date(2026, 9, 29, 9, 0)), + status: 'sending', + }), + }); + + await act(() => fireEvent.click(screen.getByText('Sending...'))); + + expect(getNotificationTypes(client)).toEqual([ + SCHEDULED_MESSAGE_NOTIFICATION_TYPE.stillSending, + ]); + expect( + screen.queryByTestId('scheduled-message-actions-menu'), + ).not.toBeInTheDocument(); + }); + + it('marks a thread reply in its row', async () => { + const client = await getTestClientWithUser({ id: 'user-id' }); + const { t, tDateTimeParser } = await new Streami18n({ language: 'en' }).init(); + const threadReply = generateScheduledMessage({ + cid, + message: { custom: {}, parent_id: 'parent-id', text: 'Launch moved to Monday' }, + scheduled_at: convertDateToTimestamp(new Date(2026, 9, 29, 9, 0)), + }); + + render( + + + + + + + , + ); + + expect(screen.getByText('Thread reply:')).toBeInTheDocument(); + }); + + 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 openInComposer = vi.fn(); + const { client } = await renderActions({ openInComposer }); + 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(openInComposer).not.toHaveBeenCalled(); + }); + + it('disables Edit of a failed message, keeping it focusable and saying why', async () => { + const openInComposer = vi.fn(); + const { client } = await renderActions({ + openInComposer, + scheduledMessage: generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen, + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + }); + removeComposeCapabilities(client); + + const edit = screen.getByTestId('scheduled-message-edit-button'); + fireEvent.click(edit); + + expect(edit).toHaveAttribute('aria-disabled', 'true'); + expect(edit).toHaveAccessibleDescription( + "Unavailable: you can't send messages in this channel", + ); + expect(openInComposer).not.toHaveBeenCalled(); + }); + }); + + describe('a failed message', () => { + const failedMessage = () => + generateScheduledMessage({ + cid, + failure_reason: SCHEDULED_MESSAGE_FAILURE_REASON.InternalError, + message: { custom: {}, text: 'Launch moved to Monday' }, + scheduled_at: convertDateToTimestamp(new Date(2026, 9, 27, 9, 0)), + status: SCHEDULED_MESSAGE_STATUS.Failed, + }); + + it('offers an Edit button and Reschedule and Delete', async () => { + await renderActions({ openInComposer: vi.fn(), scheduledMessage: failedMessage() }); + + await openActionsMenu(); + + expect(screen.getByTestId('scheduled-message-edit-button')).toBeInTheDocument(); + expect(getMenuLabels()).toEqual(['Reschedule', 'Delete']); + }); + + it('opens it in the composer from the Edit button', async () => { + const openInComposer = vi.fn(); + const { scheduledMessage } = await renderActions({ + openInComposer, + scheduledMessage: failedMessage(), + }); + + fireEvent.click(screen.getByTestId('scheduled-message-edit-button')); + + expect(openInComposer).toHaveBeenCalledWith(scheduledMessage); + }); + + it('reschedules it as a new message and deletes the failed one', async () => { + const { client, scheduledMessage } = await renderActions({ + scheduledMessage: failedMessage(), + }); + const { messageOperations } = getChannel(client); + const scheduleMessage = vi + .spyOn(messageOperations, 'scheduleMessage') + .mockResolvedValue(fromPartial({})); + const deleteScheduledMessage = vi + .spyOn(messageOperations, 'deleteScheduledMessage') + .mockResolvedValue(scheduledMessage); + + await selectAction('reschedule'); + const dialog = await screen.findByTestId('schedule-message-dialog'); + expect(dialog).toHaveTextContent('Reschedule message'); + + enterDate('2026-10-29'); + enterTime('14:30'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Schedule' }))); + + expect(scheduleMessage).toHaveBeenCalledWith({ + message: expect.objectContaining({ text: 'Launch moved to Monday' }), + options: { scheduled_at: new Date(2026, 9, 29, 14, 30) }, + }); + expect(scheduleMessage.mock.calls[0][0].message).not.toHaveProperty('id'); + await waitFor(() => + expect(deleteScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id), + ); + expect(scheduleMessage.mock.invocationCallOrder[0]).toBeLessThan( + deleteScheduledMessage.mock.invocationCallOrder[0], + ); + }); + }); + + it('offers no actions while the message is being sent', async () => { + await renderActions({ + scheduledMessage: generateScheduledMessage({ + cid, + status: SCHEDULED_MESSAGE_STATUS.Sending, + }), + }); + + 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({ + 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, + }), + }); + + 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 openInComposer = vi.fn(); + const { scheduledMessage } = await renderActions({ openInComposer }); + + await act(() => fireEvent.click(screen.getByTestId('scheduled-message-edit-button'))); + + expect(openInComposer).toHaveBeenCalledWith(scheduledMessage); + }); + + it('sends the message now and confirms it', async () => { + const { client, scheduledMessage } = await renderActions(); + const sendNow = vi + .spyOn(getChannel(client).messageOperations, 'sendScheduledMessageNow') + .mockResolvedValue(scheduledMessage); + + await selectAction('sendNow'); + + 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).messageOperations, + 'sendScheduledMessageNow', + ).mockRejectedValue(notFoundError); + + await selectAction('sendNow'); + + 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).messageOperations, '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('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).messageOperations, '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).messageOperations, + '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).messageOperations, '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(getDateField()).toHaveValue('2026-10-29'); + expect(getTimeField()).toHaveValue('09:00'); + + enterTime('14:30'); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Save' }))); + + expect(updateScheduledMessage).toHaveBeenCalledWith(scheduledMessage.id, { + request: { 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).messageOperations, + '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('clears a reschedule failure once another time is picked', async () => { + const { client } = await renderActions(); + vi.spyOn( + getChannel(client).messageOperations, + '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(); + + enterTime('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).messageOperations, '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, { + request: { scheduled_at: sendTime }, + }); + }); + + it('reports a reschedule failure without a specific reason generically', async () => { + const { client } = await renderActions(); + vi.spyOn( + getChannel(client).messageOperations, + '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'); + 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.", + ); + 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('copyMessageText'); + + 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('copyMessageText'); + + await waitFor(() => + expect(getNotificationTypes(client)).toEqual([ + SCHEDULED_MESSAGE_NOTIFICATION_TYPE.copyFailed, + ]), + ); + }); + + 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({ openInComposer: 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..68882b41f1 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessageList.test.tsx @@ -0,0 +1,647 @@ +import React, { useEffect } 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, + useChatContext, +} from '../../../context'; +import { WithComponents } from '../../../context/WithComponents'; +import { Streami18n } from '../../../i18n'; +import { + convertDateToTimestamp, + generatePoll, + generateScheduledMessage, + getScheduledMessagesPaginator, + getTestClientWithUser, + 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 { ScheduledMessageItemProps } from '../ScheduledMessageItem'; + +type OpenInComposer = NonNullable; + +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']; + openInComposer?: OpenInComposer; + filter?: ScheduledMessageSearchFilter; + listProps?: Partial; + scheduledMessages?: ScheduledMessageResponse[]; + searchQuery?: string; +}; + +/** The list as the dialog renders it: searched with `useScheduledMessagesSearch`. */ +const SearchedList = ({ + filter, + listProps, + openInComposer, + searchQuery = '', +}: Pick< + RenderListOptions, + 'filter' | 'listProps' | 'openInComposer' | 'searchQuery' +>) => { + const { client } = useChatContext(); + const { filter: searchFilter, setSearchQuery } = useScheduledMessagesSearch({ filter }); + useEffect(() => setSearchQuery(searchQuery), [searchQuery, setSearchQuery]); + return ( + + ); +}; + +const renderList = async ({ + client: clientArg, + components = {}, + filter, + listProps, + openInComposer, + 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 getListedTexts = () => + screen + .getAllByTestId('scheduled-message-item') + .map( + (item) => item.querySelector('.str-chat__summarized-message-preview')?.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(); + const loadingState = screen.getByRole('status', { + name: 'Loading scheduled messages', + }); + expect( + loadingState.querySelectorAll('.str-chat__scheduled-message-list-loading__row'), + ).toHaveLength(6); + }); + + 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); + }); + + // 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: [ + generateScheduledMessage({ cid, message: { custom: {}, text: 'Lunch at noon' } }), + ], + searchQuery: 'friday', + }); + const query = vi + .spyOn(client, 'queryScheduledMessages') + .mockRejectedValue(new Error('offline')); + + setNextCursor(client); + + 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(); + }); + + it('renders the shared list-state slots, not the deprecated channel list keys', async () => { + const { client } = await renderList({ + components: { + EmptyListIndicator: () =>
    No channels
    , + FirstPageLoadingIndicator: () =>
    Loading channels
    , + ListEmptyUI: () =>
    Nothing scheduled
    , + ListFirstPageLoadingUI: () =>
    Loading scheduled
    , + }, + }); + + expect(screen.getByText('Nothing scheduled')).toBeInTheDocument(); + expect(screen.queryByText('No channels')).not.toBeInTheDocument(); + + setPaginatorState(client, { isLoading: true, items: undefined }); + + expect(screen.getByText('Loading scheduled')).toBeInTheDocument(); + expect(screen.queryByText('Loading channels')).not.toBeInTheDocument(); + }); + + it('renders the shared load error and next-page slots', async () => { + const { client } = await renderList({ + components: { + ListLoadErrorUI: ({ error }) =>
    Failed: {error.message}
    , + ListLoadingNextPageUI: ({ isLoading }) => + isLoading ?
    Loading more
    : null, + }, + scheduledMessages: [generateScheduledMessage({ cid })], + }); + + setPaginatorState(client, { hasMoreTail: true, isLoading: true }); + + expect(screen.getByText('Loading more')).toBeInTheDocument(); + + setPaginatorState(client, { + isLoading: false, + items: undefined, + lastQueryError: new Error('offline'), + }); + + expect(screen.getByText('Failed: offline')).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 + it('lists the messages earliest first, failed ones included, without grouping', async () => { + await renderList({ + scheduledMessages: [ + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Friday plans' }, + scheduled_at: atLocalTime(30, 13), + }), + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Tomorrow plans' }, + scheduled_at: atLocalTime(29, 9), + }), + generateScheduledMessage({ + cid, + message: { custom: {}, text: 'Failed earlier' }, + scheduled_at: atLocalTime(28, 9), + status: SCHEDULED_MESSAGE_STATUS.Failed, + }), + ], + }); + + expect(getListedTexts()).toEqual([ + expect.stringContaining('Failed earlier'), + expect.stringContaining('Tomorrow plans'), + expect.stringContaining('Friday plans'), + ]); + expect(screen.queryByRole('heading')).not.toBeInTheDocument(); + }); + + 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..6b268a4c83 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/ScheduledMessagesBanner.test.tsx @@ -0,0 +1,523 @@ +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 { + defaultWorkspaceNavigation, + WorkspaceNavigationProvider, +} from '../../../context/WorkspaceNavigationContext'; +import type { WorkspaceNavigation } from '../../../context/WorkspaceNavigationContext'; +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; + openThread?: WorkspaceNavigation['openThread']; + scheduledMessages?: ScheduledMessageResponse[]; +}; + +const renderComposer = async ({ + announce, + awaitsScheduledMessages = true, + canSchedule = true, + components = {}, + inThread = false, + openThread = defaultWorkspaceNavigation.openThread, + 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, thread replies included', async () => { + await renderComposer({ + scheduledMessages: [ + generateScheduledMessage({ cid }), + generateScheduledMessage({ cid }), + threadReply(), + ], + }); + + expect(queryBanner()).toHaveTextContent('3 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 })], + }); + + expect(queryBanner()).toHaveTextContent('Scheduled for Tue, Jan 15 at 09:00'); + expect(screen.getByRole('button', { name: 'View' })).toBeInTheDocument(); + }); + + 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(); + }); + + 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'); + }); + + /** 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, + }); + 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 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 }); + + 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('edits a thread reply from the channel list in its thread', async () => { + const reply = threadReply(); + const openThread = vi.fn(); + const ScheduledMessageListDialog = ({ + open, + openInComposer, + }: ScheduledMessageListDialogProps) => + open ? ( + + ) : null; + const { channel, client } = await renderComposer({ + components: { ScheduledMessageListDialog }, + openThread, + scheduledMessages: [reply], + }); + vi.spyOn(client, 'getMessage').mockResolvedValue( + fromPartial({ message: generateMessage({ cid, id: parentId }) }), + ); + + await act(() => fireEvent.click(screen.getByRole('button', { name: 'View' }))); + await act(() => fireEvent.click(screen.getByRole('button', { name: 'Edit it' }))); + + await waitFor(() => expect(openThread).toHaveBeenCalledTimes(1)); + const [thread] = openThread.mock.calls[0] as [Thread]; + expect(thread.id).toBe(parentId); + await waitFor(() => + expect(thread.messageComposer.editedScheduledMessage?.id).toBe(reply.id), + ); + expect(channel.messageComposer.editedScheduledMessage).toBeUndefined(); + }); + + it('opens what the ScheduledMessageListDialog slot renders', async () => { + const scheduledMessage = generateScheduledMessage({ cid }); + const ScheduledMessageListDialog = vi.fn( + ({ close, open, openInComposer }: 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({ + open: true, + scheduledMessages: expect.objectContaining({ + paginator: channel.scheduledMessagesPaginator, + scope: { type: 'all' }, + }), + }), + 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__/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__/translations.test.ts b/src/components/ScheduledMessages/__tests__/translations.test.ts new file mode 100644 index 0000000000..02284d833c --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/translations.test.ts @@ -0,0 +1,60 @@ +import { fromPartial } from '@total-typescript/shoehorn'; +import { SCHEDULED_MESSAGE_FAILURE_REASON, StreamAPIError } from 'stream-chat'; + +import { + getScheduledMessageErrorKey, + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS, + SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS, +} from '../translations'; + +const t = ((_key: string, defaultValue: string) => defaultValue) as never; + +const apiError = ({ code, status }: { code?: number; status: number }) => + new StreamAPIError('request failed', { + code, + response: fromPartial>({ + data: { code }, + status, + }), + status, + }); + +describe('scheduled message translations', () => { + it('explains each failure reason, except a deleted user', () => { + expect( + SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS[ + SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen + ]?.(t), + ).toBe('This channel is frozen'); + expect( + SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS[ + SCHEDULED_MESSAGE_FAILURE_REASON.PendingNotSupported + ]?.(t), + ).toBe('This channel now needs approval. Schedule it again'); + expect( + SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS[ + SCHEDULED_MESSAGE_FAILURE_REASON.UserDeleted + ], + ).toBeNull(); + }); + + it('keys a request error by its reason, or by a not-found or forbidden status', () => { + expect(getScheduledMessageErrorKey(apiError({ code: 117, status: 400 }))).toBe( + 'scheduled_limit_channel', + ); + expect(getScheduledMessageErrorKey(apiError({ status: 404 }))).toBe(404); + expect(getScheduledMessageErrorKey(apiError({ status: 403 }))).toBe(403); + expect(getScheduledMessageErrorKey(apiError({ status: 500 }))).toBeUndefined(); + expect(getScheduledMessageErrorKey(new Error('offline'))).toBeUndefined(); + }); + + it('explains the request errors it has copy for', () => { + expect(SCHEDULED_MESSAGE_ERROR_TRANSLATIONS.scheduled_limit_channel?.(t)).toBe( + "You've reached the limit of scheduled messages in this channel", + ); + expect(SCHEDULED_MESSAGE_ERROR_TRANSLATIONS[404]?.(t)).toBe('Already sent'); + expect( + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS.scheduled_message_id_taken, + ).toBeUndefined(); + }); +}); diff --git a/src/components/ScheduledMessages/__tests__/utils.test.ts b/src/components/ScheduledMessages/__tests__/utils.test.ts new file mode 100644 index 0000000000..dbff2a99e9 --- /dev/null +++ b/src/components/ScheduledMessages/__tests__/utils.test.ts @@ -0,0 +1,154 @@ +import { ScheduledMessageErrorReason } from 'stream-chat'; +import type { Channel, MessageComposer } from 'stream-chat'; + +import { generateScheduledMessage, getTestClientWithUser } from '../../../mock-builders'; +import { + formatTimeZoneOffset, + fromInputValues, + getChannelByCid, + getDefaultScheduledAt, + getScheduleDialogId, + getSchedulePresets, + getScheduleTimeBounds, + getScheduleTimeError, + toRescheduledMessageRequest, +} from '../utils'; + +const at = (day: number, hour: number) => new Date(2026, 9, day, hour, 0); +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("returns the client's channel instance for a cid", async () => { + const client = await getTestClientWithUser({ id: 'user-id' }); + const channel = client.channel('messaging', 'general'); + + expect(getChannelByCid(client, 'messaging:general')).toBe(channel); + }); + + it('takes the content of a failed message to schedule it again, without its id', () => { + const failed = generateScheduledMessage({ + message: { + custom: { priority: 'high' }, + html: '

    Launch moved to Monday

    ', + mentioned_users: ['user-2'], + parent_id: 'parent-id', + quoted_message_id: 'quoted-id', + show_in_channel: true, + text: 'Launch moved to Monday', + }, + status: 'failed', + }); + + expect(toRescheduledMessageRequest(failed)).toEqual( + expect.objectContaining({ + custom: { priority: 'high' }, + mentioned_users: ['user-2'], + parent_id: 'parent-id', + quoted_message_id: 'quoted-id', + show_in_channel: true, + text: 'Launch moved to Monday', + }), + ); + expect(toRescheduledMessageRequest(failed)).not.toHaveProperty('id'); + expect(toRescheduledMessageRequest(failed)).not.toHaveProperty('html'); + }); + + 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( + ScheduledMessageErrorReason.TooSoon, + ); + expect(getScheduleTimeError(at(30, 9), bounds)).toBe( + ScheduledMessageErrorReason.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), + ); + }); + + 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', () => { + 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), + ]); + }); + }); + + 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', () => { + expect(formatTimeZoneOffset(new Date(2026, 9, 28, 10, 0))).toMatch(/^GMT(\+0)?$/); + }); + + 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(getScheduleDialogId(channelComposer)).toBe( + 'schedule-message-dialog-messaging:general', + ); + expect(getScheduleDialogId(threadComposer)).toBe( + 'schedule-message-dialog-messaging:general-parent-id', + ); + }); +}); diff --git a/src/components/ScheduledMessages/constants.ts b/src/components/ScheduledMessages/constants.ts new file mode 100644 index 0000000000..f330dadf7a --- /dev/null +++ b/src/components/ScheduledMessages/constants.ts @@ -0,0 +1,29 @@ +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', + sentNow: 'api:scheduled-message:create:sent-now', + stillSending: 'validation:scheduled-message:still-sending', +} as const; + +export const SCHEDULED_MESSAGES_EMITTER = 'ScheduledMessages'; + +export const SCHEDULE_MESSAGE_CAPABILITY = 'schedule-message'; + +export const RESCHEDULED_MESSAGE_FIELDS = [ + 'attachments', + 'custom', + 'mentioned_channel', + 'mentioned_group_ids', + 'mentioned_here', + 'mentioned_roles', + 'mentioned_users', + 'parent_id', + 'poll_id', + 'quoted_message_id', + 'restricted_visibility', + 'show_in_channel', + 'silent', + 'text', +] as const; diff --git a/src/components/ScheduledMessages/hooks/__tests__/useScheduledMessagesSearch.test.ts b/src/components/ScheduledMessages/hooks/__tests__/useScheduledMessagesSearch.test.ts new file mode 100644 index 0000000000..e81eb2eb22 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/__tests__/useScheduledMessagesSearch.test.ts @@ -0,0 +1,15 @@ +import { generateScheduledMessage } from '../../../../mock-builders'; +import { matchesScheduledMessageText } from '../useScheduledMessagesSearch'; + +describe('matchesScheduledMessageText', () => { + 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(matchesScheduledMessageText(lunch, ' LUNCH ')).toBe(true); + expect(matchesScheduledMessageText(launch, ' LUNCH ')).toBe(false); + expect(matchesScheduledMessageText(launch, ' ')).toBe(true); + }); +}); diff --git a/src/components/ScheduledMessages/hooks/index.ts b/src/components/ScheduledMessages/hooks/index.ts new file mode 100644 index 0000000000..57bae29b9d --- /dev/null +++ b/src/components/ScheduledMessages/hooks/index.ts @@ -0,0 +1,7 @@ +export * from './useCanScheduleMessage'; +export * from './useChannelScheduledMessages'; +export * from './useChannelWideScheduledMessagesView'; +export * from './useOpenScheduledMessageInComposer'; +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 new file mode 100644 index 0000000000..770e47bf0d --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useCanScheduleMessage.ts @@ -0,0 +1,51 @@ +import { useEffect, useState } from 'react'; +import type { + MessageComposer, + ScheduledMessagePaginatorsManagerState, +} from 'stream-chat'; + +import { useChatContext } from '../../../context'; +import { useStateStore } from '../../../store'; +import { useMessageComposerController } from '../../MessageComposer/hooks/useMessageComposerController'; + +const selectIsDisabled = ({ isDisabled }: ScheduledMessagePaginatorsManagerState) => ({ + isDisabled, +}); + +const readComposerCanSchedule = (messageComposer: MessageComposer) => + !messageComposer.hasEditInProgress && !messageComposer.scheduleBlockReason; + +const useComposerCanSchedule = (messageComposer: MessageComposer) => { + const [canSchedule, setCanSchedule] = useState(() => + readComposerCanSchedule(messageComposer), + ); + + useEffect(() => { + const { channel, locationComposer, textComposer } = messageComposer; + const update = () => setCanSchedule(readComposerCanSchedule(messageComposer)); + const unsubscribes = [ + messageComposer.state, + textComposer.state, + locationComposer.state, + channel.state, + channel.configState, + ].map((store) => store.subscribe(update)); + return () => unsubscribes.forEach((unsubscribe) => unsubscribe()); + }, [messageComposer]); + + return canSchedule; +}; + +export const useCanScheduleMessage = () => { + const { client } = useChatContext(); + const messageComposer = useMessageComposerController(); + + const { isDisabled } = useStateStore( + client.scheduledMessagePaginators.state, + selectIsDisabled, + ); + const composerCanSchedule = useComposerCanSchedule(messageComposer); + + const canSchedule = !isDisabled && composerCanSchedule; + return canSchedule; +}; diff --git a/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts b/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts new file mode 100644 index 0000000000..a579ab4e34 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useChannelScheduledMessageLimit.ts @@ -0,0 +1,29 @@ +import { getScheduledMessageLimits, SCHEDULED_MESSAGE_STATUS } from 'stream-chat'; +import type { Channel, PaginatorState, ScheduledMessageResponse } from 'stream-chat'; + +import { useStateStore } from '../../../store'; +const isPending = ({ status }: ScheduledMessageResponse) => + status === SCHEDULED_MESSAGE_STATUS.Scheduled || + status === SCHEDULED_MESSAGE_STATUS.Sending; + +const selectPendingCount = ({ + items = [], +}: PaginatorState) => ({ + pendingCount: items.filter(isPending).length, +}); + +export const useChannelScheduledMessageLimit = (channel: Channel) => { + const { pendingCount } = useStateStore( + channel.scheduledMessages.paginator.state, + selectPendingCount, + ); + + const maxPerChannel = getScheduledMessageLimits(channel)?.maxPerChannel; + const reachedLimit = + maxPerChannel !== undefined && pendingCount >= maxPerChannel + ? maxPerChannel + : undefined; + + const limit = { pendingCount, reachedLimit }; + return limit; +}; diff --git a/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts new file mode 100644 index 0000000000..64f635818d --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useChannelScheduledMessages.ts @@ -0,0 +1,41 @@ +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; + channel.ensureScheduledMessagesLoaded(); + }, [channel, initialized, isEnabledByConfig, ownCapabilities]); + + return useScheduledMessages(view); +}; diff --git a/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts b/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts new file mode 100644 index 0000000000..e6be12ddc8 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useChannelWideScheduledMessagesView.ts @@ -0,0 +1,11 @@ +import { useMemo } from 'react'; +import { ScheduledMessagesView } from 'stream-chat'; +import type { Channel } from 'stream-chat'; + +export const useChannelWideScheduledMessagesView = (channel: Channel) => { + const view = useMemo( + () => new ScheduledMessagesView({ paginator: channel.scheduledMessagesPaginator }), + [channel], + ); + return view; +}; diff --git a/src/components/ScheduledMessages/hooks/useOpenScheduledMessageInComposer.ts b/src/components/ScheduledMessages/hooks/useOpenScheduledMessageInComposer.ts new file mode 100644 index 0000000000..3fa14985df --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useOpenScheduledMessageInComposer.ts @@ -0,0 +1,49 @@ +import { useCallback } from 'react'; +import { formatMessage } from 'stream-chat'; +import type { + Channel, + LocalMessage, + ScheduledMessageResponse, + StreamChat, +} from 'stream-chat'; + +import { useChatContext, useWorkspaceNavigation } from '../../../context'; + +const resolveParentMessage = async ( + client: StreamChat, + parentId: string, +): Promise => { + const storedMessage = client.messageStore.get(parentId); + if (storedMessage) return storedMessage; + try { + const { message } = await client.getMessage({ id: parentId }); + return formatMessage(message); + } catch { + return undefined; + } +}; + +export const useOpenScheduledMessageInComposer = (channel: Channel) => { + const { client } = useChatContext(); + const { openThread } = useWorkspaceNavigation(); + + const openInComposer = useCallback( + async (scheduledMessage: ScheduledMessageResponse) => { + const { parent_id: parentId } = scheduledMessage.message; + if (!parentId) { + await channel.messageComposer.editScheduledMessage(scheduledMessage); + return; + } + + const parentMessage = await resolveParentMessage(client, parentId); + if (!parentMessage) return; + + const thread = client.threads.ensure({ channel, parentMessage }); + openThread(thread); + await thread.messageComposer.editScheduledMessage(scheduledMessage); + }, + [channel, client, openThread], + ); + + return openInComposer; +}; diff --git a/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts new file mode 100644 index 0000000000..10baee6eef --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useRescheduleDialogProps.ts @@ -0,0 +1,83 @@ +import { nsToDate } from 'stream-chat'; +import type { Channel, LocalMessage, ScheduledMessageResponse } from 'stream-chat'; + +import { useChatContext, useTranslationContext } from '../../../context'; +import type { ScheduleTimeDialogProps } from '../ScheduleTimeDialog'; +import { + getChannelByCid, + isFailedScheduledMessage, + toRescheduledMessageRequest, +} from '../utils'; + +export type UseRescheduleDialogPropsParams = { + previewMessage: LocalMessage; + scheduledMessage: ScheduledMessageResponse; +}; + +const scheduleFailedMessageAgain = async ( + channel: Channel, + failedMessage: ScheduledMessageResponse, + scheduledAt: Date, +) => { + await channel.messageOperations.scheduleMessage({ + message: toRescheduledMessageRequest(failedMessage), + options: { scheduled_at: scheduledAt }, + }); + await channel.messageOperations + .deleteScheduledMessage(failedMessage.id) + .catch(() => undefined); +}; + +/** + * `ScheduleTimeDialog` props that pick a new send time for a scheduled message. A pending one keeps + * its message and gets the new time. A failed one is scheduled again as a new message, and the failed + * one is deleted once the new one is scheduled. The caller adds `channel` and `close`. + */ +export const useRescheduleDialogProps = ({ + previewMessage, + scheduledMessage, +}: UseRescheduleDialogPropsParams): Omit< + ScheduleTimeDialogProps, + 'channel' | 'close' +> => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const sendTime = nsToDate(scheduledMessage.scheduled_at); + const getChannel = () => getChannelByCid(client, scheduledMessage.cid); + const title = t('scheduledMessages.rescheduleMessage', 'Reschedule message'); + const errorMessage = t( + 'scheduledMessages.couldntRescheduleTheMessageTryAgain', + "Couldn't reschedule the message. Try again", + ); + + if (isFailedScheduledMessage(scheduledMessage)) { + return { + errorMessage, + previewMessage, + submit: (scheduledAt: Date) => + scheduleFailedMessageAgain(getChannel(), scheduledMessage, scheduledAt), + title, + }; + } + + return { + errorMessage, + 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) => { + await getChannel().messageOperations.updateScheduledMessage(scheduledMessage.id, { + request: { scheduled_at: scheduledAt }, + }); + }, + submitLabel: t('scheduledMessages.save', 'Save'), + title, + tooSoonMessage: t( + 'scheduledMessages.pickALaterTimeEditingCantSend', + "Pick a later time. Editing can't send a message right away.", + ), + }; +}; diff --git a/src/components/ScheduledMessages/hooks/useScheduleComposition.ts b/src/components/ScheduledMessages/hooks/useScheduleComposition.ts new file mode 100644 index 0000000000..5c5df831d2 --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduleComposition.ts @@ -0,0 +1,83 @@ +import { useCallback } from 'react'; +import { + CORE_NOTIFICATION_TYPE, + getScheduledMessageErrorReason, + ScheduledMessageErrorReason, +} from 'stream-chat'; + +import { useChatContext, useTranslationContext } from '../../../context'; +import { useMessagePaginator } from '../../../hooks/useMessagePaginator'; +import { useMessageComposerController } from '../../MessageComposer/hooks/useMessageComposerController'; +import { useNotificationApi } from '../../Notifications'; +import { + SCHEDULED_MESSAGE_NOTIFICATION_TYPE, + SCHEDULED_MESSAGES_EMITTER, +} from '../constants'; + +const SCHEDULING_FAILURE_NOTIFICATION_TYPES: ReadonlySet = new Set([ + CORE_NOTIFICATION_TYPE.scheduledMessageBlocked, + CORE_NOTIFICATION_TYPE.scheduledMessageCreateFailed, +]); + +export const useScheduleComposition = () => { + const { t } = useTranslationContext(); + const { client } = useChatContext(); + const { addNotification } = useNotificationApi(); + const messageComposer = useMessageComposerController(); + const messagePaginator = useMessagePaginator(); + + 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.scheduledMessageSent', 'Scheduled message sent'), + severity: 'success', + type: SCHEDULED_MESSAGE_NOTIFICATION_TYPE.sentNow, + }); + return; + } + if (status === 'scheduled') return; + if (getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.IdTaken) { + messageComposer.refreshId(); + } + throw error ?? new Error(`Message not scheduled: ${status}`); + }, + [addNotification, messageComposer, messagePaginator, t], + ); + + 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, type }) => + !shownBefore.has(id) && + origin.context?.composer === messageComposer && + !!type && + SCHEDULING_FAILURE_NOTIFICATION_TYPES.has(type), + ) + .forEach(({ id }) => notifications.remove(id)); + throw error; + } + }, + [client, messageComposer, scheduleMessage], + ); + + const scheduleComposition = { scheduleMessage, scheduleMessageFromDialog }; + return scheduleComposition; +}; 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/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..975c8ad74b --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessages.ts @@ -0,0 +1,28 @@ +import { useEffect } from 'react'; +import type { + ScheduledMessageResponse, + ScheduledMessagesView, + ScheduledMessagesViewState, +} from 'stream-chat'; + +import { useStateStore } from '../../../store'; + +const NO_SCHEDULED_MESSAGES: ScheduledMessageResponse[] = []; + +const selectItems = ({ items }: ScheduledMessagesViewState) => ({ items }); + +/** + * 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(() => { + view.registerSubscriptions(); + return () => { + view.unregisterSubscriptions(); + }; + }, [view]); + + 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..41444329fa --- /dev/null +++ b/src/components/ScheduledMessages/hooks/useScheduledMessagesSearch.ts @@ -0,0 +1,39 @@ +import { useCallback, useState } from 'react'; +import type { ScheduledMessageResponse } from 'stream-chat'; + +export const matchesScheduledMessageText = ( + { message }: ScheduledMessageResponse, + searchQuery: string, +) => { + const query = searchQuery.trim().toLocaleLowerCase(); + return !query || !!message.text?.toLocaleLowerCase().includes(query); +}; + +/** 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/index.ts b/src/components/ScheduledMessages/index.ts new file mode 100644 index 0000000000..de7334a955 --- /dev/null +++ b/src/components/ScheduledMessages/index.ts @@ -0,0 +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/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..a9e4dcd1a3 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduleMessageDialog.scss @@ -0,0 +1,101 @@ +@use '../../../styling/utils'; +@use 'variables'; + +.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); + } + + @media (max-width: variables.$full-screen-max-width) { + width: 100dvw; + max-width: none; + height: 100dvh; + border-radius: 0; + box-shadow: none; + + .str-chat__schedule-message-dialog__body { + flex: 1; + min-height: 0; + overflow-y: auto; + } + + .str-chat__schedule-message-dialog__fields { + grid-template-columns: minmax(0, 1fr); + } + + .str-chat__prompt__footer__controls { + width: 100%; + + .str-chat__prompt__footer__controls-button { + flex: 1; + } + } + } + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss b/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss new file mode 100644 index 0000000000..4e633ff4f7 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessageActions.scss @@ -0,0 +1,36 @@ +@use '../../../styling/utils'; + +.str-chat { + .str-chat__scheduled-message-list__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; + + @media (hover: none) { + opacity: 1; + pointer-events: auto; + } + } +} diff --git a/src/components/ScheduledMessages/styling/ScheduledMessageList.scss b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss new file mode 100644 index 0000000000..1405d42f1b --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessageList.scss @@ -0,0 +1,286 @@ +@use '../../../styling/utils'; +@use 'variables'; + +@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 +// ancestor. +.str-chat__scheduled-message-list-modal > .str-chat__modal__dialog { + max-width: calc(100% - 2 * var(--str-chat__spacing-md)); + + @media (max-width: variables.$full-screen-max-width) { + max-width: none; + } +} + +.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; + 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))); + + @media (max-width: variables.$full-screen-max-width) { + width: 100dvw; + max-width: none; + height: 100dvh; + border-radius: 0; + box-shadow: none; + } + + // 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; + + // 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-list__items { + display: flex; + flex-direction: column; + margin: 0; + padding: 0; + list-style: none; + } + + .str-chat__scheduled-message-list__item { + padding: var(--str-chat__spacing-md) var(--str-chat__spacing-xl); + border-block-end: 1px solid var(--str-chat__border-core-subtle); + + &: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__scheduled-message-item__preview { + display: flex; + align-items: baseline; + gap: var(--str-chat__spacing-xxs); + min-width: 0; + + .str-chat__summarized-message-preview { + flex: 1; + } + } + + .str-chat__scheduled-message-item__thread-reply-label { + flex-shrink: 0; + color: var(--str-chat__text-secondary); + font: var(--str-chat__font-body-emphasis); + } + + .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 { + 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 { + display: flex; + flex: 1; + 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/ScheduledMessagesBanner.scss b/src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss new file mode 100644 index 0000000000..7b93bafb52 --- /dev/null +++ b/src/components/ScheduledMessages/styling/ScheduledMessagesBanner.scss @@ -0,0 +1,81 @@ +@use '../../../styling/utils'; + +$banner-selector: '.str-chat__scheduled-messages-banner'; +$composer-with-banner-selector: '.str-chat__message-composer-container:has(> #{$banner-selector})'; + +.str-chat { + --str-chat__scheduled-messages-banner-height: 40px; + --str-chat__scheduled-messages-banner-clearance: calc( + var(--str-chat__scheduled-messages-banner-height) + 2 * var(--str-chat__spacing-md) + ); + + #{$composer-with-banner-selector} { + position: relative; + + > #{$banner-selector} { + position: absolute; + inset-block-end: calc(100% + var(--str-chat__spacing-md)); + inset-inline: var(--str-chat__spacing-md); + z-index: 1; + width: auto; + } + } + + .str-chat__message-list-main-panel:has( + ~ .str-chat__message-composer-container > #{$banner-selector} + ) { + .str-chat__jump-to-latest-message, + .str-chat__new-message-notification { + inset-block-end: var(--str-chat__scheduled-messages-banner-clearance); + } + + .str-chat__message-list .str-chat__ul { + padding-block-end: var(--str-chat__scheduled-messages-banner-clearance); + } + } + + .str-chat__scheduled-messages-banner { + display: flex; + align-items: center; + gap: var(--str-chat__spacing-sm); + width: 100%; + min-height: var(--str-chat__scheduled-messages-banner-height); + 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/_variables.scss b/src/components/ScheduledMessages/styling/_variables.scss new file mode 100644 index 0000000000..0bdda85837 --- /dev/null +++ b/src/components/ScheduledMessages/styling/_variables.scss @@ -0,0 +1 @@ +$full-screen-max-width: 679.98px; 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/translations.ts b/src/components/ScheduledMessages/translations.ts new file mode 100644 index 0000000000..373344343f --- /dev/null +++ b/src/components/ScheduledMessages/translations.ts @@ -0,0 +1,106 @@ +import { + getScheduledMessageErrorReason, + SCHEDULED_MESSAGE_FAILURE_REASON, + ScheduledMessageErrorReason, + StreamAPIError, +} from 'stream-chat'; +import type { ScheduledMessageFailureReason } from 'stream-chat'; + +import type { StreamTFunction } from '../../i18n/types'; + +const NOT_FOUND_STATUS = 404; +const FORBIDDEN_STATUS = 403; + +type ScheduledMessageTranslation = (t: StreamTFunction) => string; + +type ScheduledMessageErrorKey = + | ScheduledMessageErrorReason + | typeof NOT_FOUND_STATUS + | typeof FORBIDDEN_STATUS; + +export const SCHEDULED_MESSAGE_FAILURE_REASON_TRANSLATIONS: Record< + ScheduledMessageFailureReason, + ScheduledMessageTranslation | null +> = { + [SCHEDULED_MESSAGE_FAILURE_REASON.Banned]: (t) => + t( + 'scheduledMessages.youCantSendMessagesInThisChannel', + "You can't send messages in this channel", + ), + [SCHEDULED_MESSAGE_FAILURE_REASON.ChannelDeleted]: (t) => + t('scheduledMessages.thisChannelWasDeleted', 'This channel was deleted'), + [SCHEDULED_MESSAGE_FAILURE_REASON.ChannelFrozen]: (t) => + t('scheduledMessages.thisChannelIsFrozen', 'This channel is frozen'), + [SCHEDULED_MESSAGE_FAILURE_REASON.Expired]: (t) => + t( + 'scheduledMessages.notSentTheServiceWasDelayed', + 'Not sent: the service was delayed', + ), + [SCHEDULED_MESSAGE_FAILURE_REASON.HookRejected]: (t) => + t('scheduledMessages.rejectedByTheApp', 'Rejected by the app'), + [SCHEDULED_MESSAGE_FAILURE_REASON.InternalError]: (t) => + t('scheduledMessages.somethingWentWrongTryAgain', 'Something went wrong. Try again'), + [SCHEDULED_MESSAGE_FAILURE_REASON.InvalidMessage]: (t) => + t( + 'scheduledMessages.theMessageNoLongerMeetsTheAppsLimits', + "The message no longer meets the app's limits. Edit it", + ), + [SCHEDULED_MESSAGE_FAILURE_REASON.ModerationBlocked]: (t) => + t('scheduledMessages.blockedByModeration', 'Blocked by moderation'), + [SCHEDULED_MESSAGE_FAILURE_REASON.NoPermission]: (t) => + t( + 'scheduledMessages.youreNoLongerAllowedToPostHere', + "You're no longer allowed to post here", + ), + [SCHEDULED_MESSAGE_FAILURE_REASON.PendingNotSupported]: (t) => + t( + 'scheduledMessages.thisChannelNowNeedsApprovalScheduleItAgain', + 'This channel now needs approval. Schedule it again', + ), + [SCHEDULED_MESSAGE_FAILURE_REASON.UserDeleted]: null, +}; + +export const SCHEDULED_MESSAGE_ERROR_TRANSLATIONS: Partial< + Record +> = { + [ScheduledMessageErrorReason.AlreadySent]: (t) => + t('scheduledMessages.notification.alreadySent', 'Already sent'), + [ScheduledMessageErrorReason.ChannelLimit]: (t) => + t( + 'scheduledMessages.notification.channelLimit', + "You've reached the limit of scheduled messages in this channel", + ), + [ScheduledMessageErrorReason.Conflict]: (t) => + t('scheduledMessages.notification.conflict', 'Updated elsewhere. Try again'), + [ScheduledMessageErrorReason.Disabled]: (t) => + t('scheduledMessages.notification.disabled', 'Scheduled messages are turned off'), + [ScheduledMessageErrorReason.NotEditable]: (t) => + t('scheduledMessages.notification.notEditable', "Failed messages can't be edited"), + [ScheduledMessageErrorReason.Sending]: (t) => + t('scheduledMessages.notification.sending', 'This message is being sent'), + [ScheduledMessageErrorReason.TooFar]: (t) => + t('scheduledMessages.chooseAnEarlierTime', 'Choose an earlier time'), + [ScheduledMessageErrorReason.TooSoon]: (t) => + t('scheduledMessages.chooseALaterTime', 'Choose a later time'), + [ScheduledMessageErrorReason.UserLimit]: (t) => + t( + 'scheduledMessages.notification.userLimit', + "You've reached the limit of scheduled messages", + ), + [FORBIDDEN_STATUS]: (t) => + t('scheduledMessages.notification.forbidden', "You can't schedule messages here"), + [NOT_FOUND_STATUS]: (t) => + t('scheduledMessages.notification.alreadySent', 'Already sent'), +}; + +export const getScheduledMessageErrorKey = ( + error: unknown, +): ScheduledMessageErrorKey | undefined => { + const reason = getScheduledMessageErrorReason(error); + if (reason) return reason; + if (!(error instanceof StreamAPIError)) return undefined; + if (error.status === NOT_FOUND_STATUS || error.status === FORBIDDEN_STATUS) { + return error.status; + } + return undefined; +}; diff --git a/src/components/ScheduledMessages/utils.ts b/src/components/ScheduledMessages/utils.ts new file mode 100644 index 0000000000..21275b94d8 --- /dev/null +++ b/src/components/ScheduledMessages/utils.ts @@ -0,0 +1,153 @@ +import { + dateToNs, + getScheduledMessageLimits, + SCHEDULED_MESSAGE_STATUS, + ScheduledMessageErrorReason, + toScheduledMessagePreview, +} from 'stream-chat'; +import type { + Channel, + MessageComposer, + MessageRequest, + ScheduledMessageResponse, + StreamChat, + UserResponse, +} from 'stream-chat'; + +import { RESCHEDULED_MESSAGE_FIELDS } from './constants'; + +const pickFields = ( + source: T, + fields: readonly K[], +) => { + const picked = Object.fromEntries( + fields.filter((field) => field in source).map((field) => [field, source[field]]), + ) as Pick; + return picked; +}; + +const padTwoDigits = (value: number) => String(value).padStart(2, '0'); + +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; +}; + +export const getChannelByCid = (client: StreamChat, cid: string) => { + const [type, id] = cid.split(':'); + const channel = client.channel(type, id); + return channel; +}; + +export const getScheduleDialogId = ({ + channel, + threadId, +}: Pick) => + ['schedule-message-dialog', channel.cid, threadId].filter(Boolean).join('-'); + +export const toCompositionPreview = ({ + attachmentManager, + channel, + client, + id, + textComposer, +}: MessageComposer) => { + const now = dateToNs(new Date()); + const user = (client.user ?? { id: client.userID ?? '' }) as UserResponse; + + const preview = toScheduledMessagePreview({ + cid: channel.cid, + created_at: now, + id, + message: { + attachments: attachmentManager.attachments, + custom: {}, + text: textComposer.text, + }, + scheduled_at: now, + status: SCHEDULED_MESSAGE_STATUS.Scheduled, + updated_at: now, + user, + }); + return preview; +}; + +export const toRescheduledMessageRequest = ({ + message, +}: ScheduledMessageResponse): MessageRequest => + pickFields(message, RESCHEDULED_MESSAGE_FIELDS); + +export const isFailedScheduledMessage = ({ status }: ScheduledMessageResponse) => + status === SCHEDULED_MESSAGE_STATUS.Failed; + +export const toDateInputValue = (date: Date) => + `${date.getFullYear()}-${padTwoDigits(date.getMonth() + 1)}-${padTwoDigits(date.getDate())}`; + +export const toTimeInputValue = (date: Date) => + `${padTwoDigits(date.getHours())}:${padTwoDigits(date.getMinutes())}`; + +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; +}; + +export const getScheduleTimeBounds = (channel: Channel, now = new Date()) => { + const limits = getScheduledMessageLimits(channel); + const nowMs = now.getTime(); + const clockSkewBufferMs = 60 * 1000; + + const bounds: { earliest: Date; latest?: Date } = { + earliest: new Date( + nowMs + (limits?.minLeadTimeSeconds ?? 0) * 1000 + clockSkewBufferMs, + ), + latest: limits && new Date(nowMs + limits.maxLeadTimeSeconds * 1000), + }; + return bounds; +}; + +export const getScheduleTimeError = ( + scheduledAt: Date, + { earliest, latest }: ReturnType, +) => { + if (scheduledAt < earliest) return ScheduledMessageErrorReason.TooSoon; + if (latest && scheduledAt > latest) return ScheduledMessageErrorReason.TooFar; + return undefined; +}; + +export const getDefaultScheduledAt = ({ + earliest, + latest, +}: ReturnType) => { + 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; +}; + +export const getSchedulePresets = ( + now: Date, + bounds: ReturnType, +) => { + const daysUntilMonday = (8 - now.getDay()) % 7 || 7; + const presets = [ + atLocalHour(now, 1, 9), + atLocalHour(now, 1, 13), + ...(daysUntilMonday === 1 ? [] : [atLocalHour(now, daysUntilMonday, 9)]), + ]; + return presets.filter((preset) => !getScheduleTimeError(preset, bounds)); +}; + +export const formatTimeZoneOffset = (date: Date) => { + const timeZoneName = new Intl.DateTimeFormat('en-US', { timeZoneName: 'shortOffset' }) + .formatToParts(date) + .find(({ type }) => type === 'timeZoneName')?.value; + return timeZoneName ?? 'GMT'; +}; diff --git a/src/components/index.ts b/src/components/index.ts index 1396723040..2a4cea4177 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 bcc1f7f0ef..c8fe3b2aa5 100644 --- a/src/context/ComponentContext.tsx +++ b/src/context/ComponentContext.tsx @@ -81,6 +81,16 @@ 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 { + ScheduleDateInputProps, + ScheduledMessageDeleteAlertProps, + ScheduledMessageItemProps, + ScheduledMessageListDialogProps, + ScheduledMessageListProps, + ScheduledMessagePreviewProps, + ScheduleTimeDialogProps, + ScheduleTimeInputProps, +} from '../components/ScheduledMessages'; export type ComponentContextValue = { /** Progress of an attachment whose upload is still in flight. */ @@ -375,6 +385,32 @@ 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. */ + 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; + /** 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. 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; /** diff --git a/src/i18n/TranslationBuilder/notifications/translators.ts b/src/i18n/TranslationBuilder/notifications/translators.ts index c138371222..1993ab64e3 100644 --- a/src/i18n/TranslationBuilder/notifications/translators.ts +++ b/src/i18n/TranslationBuilder/notifications/translators.ts @@ -1,5 +1,13 @@ +import { + CORE_NOTIFICATION_TYPE, + ScheduledMessageCompositionEndReason, +} from 'stream-chat'; import type { Notification } from 'stream-chat'; +import { + getScheduledMessageErrorKey, + SCHEDULED_MESSAGE_ERROR_TRANSLATIONS, +} from '../../../components/ScheduledMessages/translations'; import type { NotificationTranslatorOptions } from './types'; import type { Translator } from '../../index'; @@ -94,3 +102,35 @@ 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 errorKey = getScheduledMessageErrorKey(notification?.originalError); + const specific = errorKey && SCHEDULED_MESSAGE_ERROR_TRANSLATIONS[errorKey]?.(t); + 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