Add multi selection to the Forward action (#6190)

* Start message selection from the Forward action

Behind the multi-select developer option, choosing Forward on a message
now starts a selection with that message checked, instead of the
dedicated Select menu action which is removed. Only forwardable
messages can be selected: remote, decrypted, non-redacted events that
aren't state, unsupported, poll or live location items.

The chrome follows the Figma exploration: the room header stays, an X
in the trailing toolbar position ends the selection, rows show only the
checkbox (no highlight, 10pt gap to the bubble), and the composer is
replaced by a single primary "Forward N messages" button. The limits
are now 10 messages into 5 rooms.

Tapping the button forwards the selection in timeline order, never in
the order the messages were tapped. MessageForwardingItem carries
several contents and the forwarding screen sends them one after the
other per room, reporting a single error toast on partial failures.
The selection is kept while the forwarding screen is open so cancelling
it returns to the selection; it is cleared by the flow coordinator once
the messages are sent, or by the X in the timeline.

New plural action_forward_messages lives in Untranslated for now;
action_select and screen_room_selection_count are no longer used.

* Tidy the selection code after review

Reuse ToolbarButton's cancel role for the selection's toolbar item so it
matches the other screens on every OS version, and disable the room
header while selecting so the room details can't cover the selection.

Move the forwardable/selected item helpers next to the existing
nonisolated array extension, drop the unused MessageForwardingItem
initialisers and the single-item makeForwardingItem overload, and
simplify the forwarding loop now that a room either sends or isn't
reachable.

The action bar preview builds its own view model instead of putting
the shared mock into selection mode for every later preview, and a
test locks that Forward keeps forwarding directly in the pinned
timeline.

* Select messages to forward from the pinned timeline too

Forward is offered in the pinned events timeline, so with the flag on
it starts a selection there as well, with the same cancel item in the
toolbar and the same forward button at the bottom. Forwarding from
that sheet already dismisses the whole sheet, so the selection is
discarded with it. Only the media timelines keep forwarding a single
item directly.

* Confirm with a toast when messages are forwarded to several rooms

When a single room is picked the flow opens it, which is confirmation
enough. When several rooms are picked the user stays in the origin room,
so a "Messages forwarded" toast tells them it worked, as in the designs.
The new screen_room_message_forwarded / screen_room_messages_forwarded
strings live in Untranslated for now.

* Apply review suggestions to multi-message forwarding

Strings
- The forward button and the multi-room toast now use the Localazy
  plurals action_forward_messages and screen_room_messages_forwarded;
  the toast shows the count. The Untranslated copies and the unused
  action_select are gone.

Selection
- Drop the dead startSelection view action and the redundant
  canSelectMessages guard; tests start a selection through Forward
  like the app does.
- Remove two comments on the selection state that restated the code.

Forwarding
- After a send, clear the selection in the room and any open thread
  instead of working out which one started it; only one can be
  selecting at a time.
- Explain that stickers are excluded because the SDK can only forward
  m.room.message content.

* Rename the timeline selection to message selection

"Selection" alone was too generic in a timeline that also has text and
room selections. The selection state, toolbar, action bar and
accessibility types, the timeline state's property, the view actions
and the public clear method now say "message selection". Private
helpers keep their short names.

* Rename MessageForwardingItem to MessageForwardingPayload

The type now carries several messages, so "item" no longer described
it. The factory method and the variables and action labels holding it
follow the new name.
This commit is contained in:
Mauro
2026-09-25 13:51:14 +02:00
committed by GitHub
parent fc8ee9d93d
commit ad1d7a3010
71 changed files with 826 additions and 388 deletions
@@ -11,7 +11,7 @@ import SwiftUI
enum TimelineMediaPreviewViewModelAction: Equatable {
case viewInRoomTimeline(TimelineItemIdentifier)
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
case dismiss
}
@@ -136,9 +136,9 @@ class TimelineMediaPreviewViewModel: TimelineMediaPreviewViewModelType {
}
private func forwardItem(itemID: TimelineItemIdentifier) async {
guard let forwardingItem = await timelineViewModel.makeForwardingItem(for: itemID) else { return }
guard let forwardingPayload = await timelineViewModel.makeForwardingPayload(for: [itemID]) else { return }
state.previewControllerDriver.send(.dismissDetailsSheet)
actionsSubject.send(.displayMessageForwarding(forwardingItem))
actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
private func updateCurrentItem(_ previewItem: TimelineMediaPreviewItem) async {
@@ -231,7 +231,6 @@ class TimelineMediaPreviewViewModel: TimelineMediaPreviewViewModelType {
pinnedEventIDs: timelineContext.viewState.pinnedEventIDs,
isViewSourceEnabled: timelineContext.viewState.isViewSourceEnabled,
areThreadsEnabled: timelineContext.viewState.areThreadsEnabled,
isMultiSelectEnabled: timelineContext.viewState.canSelectMessages,
timelineKind: timelineContext.viewState.timelineKind,
emojiProvider: timelineContext.viewState.emojiProvider)
.makeActions()
@@ -26,7 +26,7 @@ struct MediaEventsTimelineScreenCoordinatorParameters {
enum MediaEventsTimelineScreenCoordinatorAction {
case viewInRoomTimeline(TimelineItemIdentifier)
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
}
final class MediaEventsTimelineScreenCoordinator: CoordinatorProtocol {
@@ -74,8 +74,8 @@ final class MediaEventsTimelineScreenCoordinator: CoordinatorProtocol {
.sink { [weak self] action in
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.displayMessageForwarding(forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.displayMessageForwarding(forwardingPayload))
case .viewInRoomTimeline(let itemID):
actionsSubject.send(.viewInRoomTimeline(itemID))
}
@@ -9,7 +9,7 @@
import SwiftUI
enum MediaEventsTimelineScreenViewModelAction {
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
case viewInRoomTimeline(TimelineItemIdentifier)
}
@@ -169,8 +169,8 @@ class MediaEventsTimelineScreenViewModel: MediaEventsTimelineScreenViewModelType
sheetModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
displayMessageForwarding(forwardingItem: forwardingItem)
case .displayMessageForwarding(let forwardingPayload):
displayMessageForwarding(forwardingPayload: forwardingPayload)
case .viewInRoomTimeline(let itemID):
actionsSubject.send(.viewInRoomTimeline(itemID))
case .dismiss:
@@ -246,8 +246,8 @@ class MediaEventsTimelineScreenViewModel: MediaEventsTimelineScreenViewModelType
viewModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
displayMessageForwarding(forwardingItem: forwardingItem)
case .displayMessageForwarding(let forwardingPayload):
displayMessageForwarding(forwardingPayload: forwardingPayload)
case .viewInRoomTimeline(let itemID):
state.bindings.mediaPreviewViewModel = nil
actionsSubject.send(.viewInRoomTimeline(itemID))
@@ -268,12 +268,12 @@ class MediaEventsTimelineScreenViewModel: MediaEventsTimelineScreenViewModelType
}
}
private func displayMessageForwarding(forwardingItem: MessageForwardingItem) {
private func displayMessageForwarding(forwardingPayload: MessageForwardingPayload) {
state.bindings.mediaPreviewViewModel = nil
state.bindings.mediaPreviewSheetViewModel = nil
// We need a small delay because we need to wait for the presented sheet to be fully dismissed.
DispatchQueue.main.asyncAfter(deadline: .now() + TimelineMediaPreviewViewModel.displayMessageForwardingDelay) {
self.actionsSubject.send(.displayMessageForwarding(forwardingItem))
self.actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
}
}
@@ -10,7 +10,7 @@ import Combine
import SwiftUI
struct MessageForwardingScreenCoordinatorParameters {
let forwardingItem: MessageForwardingItem
let forwardingPayload: MessageForwardingPayload
let userSession: UserSessionProtocol
let roomSummaryProvider: RoomSummaryProviderProtocol
let userIndicatorController: UserIndicatorControllerProtocol
@@ -31,7 +31,7 @@ final class MessageForwardingScreenCoordinator: CoordinatorProtocol {
}
init(parameters: MessageForwardingScreenCoordinatorParameters) {
viewModel = MessageForwardingScreenViewModel(forwardingItem: parameters.forwardingItem,
viewModel = MessageForwardingScreenViewModel(forwardingPayload: parameters.forwardingPayload,
userSession: parameters.userSession,
roomSummaryProvider: parameters.roomSummaryProvider,
userIndicatorController: parameters.userIndicatorController)
@@ -17,7 +17,7 @@ enum MessageForwardingScreenViewModelAction {
struct MessageForwardingScreenViewState: BindableState {
var rooms: [MessageForwardingRoom] = []
var selectedRoomIDs: Set<String> = []
let maxRoomSelectionCount = 10
let maxRoomSelectionCount = 5
var bindings = MessageForwardingScreenViewStateBindings()
var isAtRoomSelectionLimit: Bool {
@@ -44,20 +44,20 @@ struct MessageForwardingRoom: Identifiable, Equatable {
let avatar: RoomAvatar
}
struct MessageForwardingItem: Hashable {
/// The source item's timeline ID. Only necessary for a rough Hashable conformance.
let id: TimelineItemIdentifier
/// The source item's room ID.
struct MessageForwardingPayload: Hashable {
/// The source items' timeline IDs. Only necessary for a rough Hashable conformance.
let ids: [TimelineItemIdentifier]
/// The source items' room ID.
let roomID: String
/// The item's content to be forwarded.
let content: RoomMessageEventContentWithoutRelation
/// The contents to be forwarded, in timeline order.
let contents: [RoomMessageEventContentWithoutRelation]
static func == (lhs: MessageForwardingItem, rhs: MessageForwardingItem) -> Bool {
lhs.id == rhs.id && lhs.roomID == rhs.roomID
static func == (lhs: MessageForwardingPayload, rhs: MessageForwardingPayload) -> Bool {
lhs.ids == rhs.ids && lhs.roomID == rhs.roomID
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(ids)
hasher.combine(roomID)
}
}
@@ -12,7 +12,7 @@ import SwiftUI
typealias MessageForwardingScreenViewModelType = StateStoreViewModel<MessageForwardingScreenViewState, MessageForwardingScreenViewAction>
class MessageForwardingScreenViewModel: MessageForwardingScreenViewModelType, MessageForwardingScreenViewModelProtocol {
private let forwardingItem: MessageForwardingItem
private let forwardingPayload: MessageForwardingPayload
private let clientProxy: ClientProxyProtocol
private let roomSummaryProvider: RoomSummaryProviderProtocol
private let userIndicatorController: UserIndicatorControllerProtocol
@@ -23,11 +23,11 @@ class MessageForwardingScreenViewModel: MessageForwardingScreenViewModelType, Me
actionsSubject.eraseToAnyPublisher()
}
init(forwardingItem: MessageForwardingItem,
init(forwardingPayload: MessageForwardingPayload,
userSession: UserSessionProtocol,
roomSummaryProvider: RoomSummaryProviderProtocol,
userIndicatorController: UserIndicatorControllerProtocol) {
self.forwardingItem = forwardingItem
self.forwardingPayload = forwardingPayload
clientProxy = userSession.clientProxy
self.roomSummaryProvider = roomSummaryProvider
self.userIndicatorController = userIndicatorController
@@ -86,7 +86,7 @@ class MessageForwardingScreenViewModel: MessageForwardingScreenViewModelType, Me
var rooms = [MessageForwardingRoom]()
for summary in roomSummaryProvider.roomListPublisher.value {
if summary.id == forwardingItem.roomID {
if summary.id == forwardingPayload.roomID {
continue
}
@@ -123,23 +123,33 @@ class MessageForwardingScreenViewModel: MessageForwardingScreenViewModelType, Me
}
var succeededRoomIdentifiers = [String]()
var hasFailures = false
for roomID in state.selectedRoomIDs {
guard case let .joined(targetRoomProxy) = await clientProxy.roomForIdentifier(roomID) else {
MXLog.error("Failed retrieving room to forward to with id: \(roomID)")
userIndicatorController.submitIndicator(UserIndicator(title: L10n.errorUnknown))
hasFailures = true
continue
}
if case .failure(let error) = await targetRoomProxy.timeline.sendMessageEventContent(forwardingItem.content) {
MXLog.error("Failed forwarding message with error: \(error)")
userIndicatorController.submitIndicator(UserIndicator(title: L10n.errorUnknown))
continue
// The contents are already in timeline order and the send queue preserves it.
for content in forwardingPayload.contents {
if case .failure(let error) = await targetRoomProxy.timeline.sendMessageEventContent(content) {
MXLog.error("Failed forwarding message with error: \(error)")
hasFailures = true
}
}
succeededRoomIdentifiers.append(roomID)
}
if hasFailures {
userIndicatorController.submitIndicator(UserIndicator(title: L10n.errorUnknown))
} else if succeededRoomIdentifiers.count > 1 {
// The flow opens the room when there is a single one, otherwise the user stays here and needs to know it worked.
userIndicatorController.submitIndicator(UserIndicator(title: L10n.screenRoomMessagesForwarded(forwardingPayload.contents.count)))
}
if !succeededRoomIdentifiers.isEmpty {
actionsSubject.send(.sent(roomIDs: succeededRoomIdentifiers))
}
@@ -99,9 +99,9 @@ private struct MessageForwardingListRow: View {
struct MessageForwardingScreen_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
let summaryProvider = RoomSummaryProviderMock(.init(state: .loaded(.mockRooms)))
let viewModel = MessageForwardingScreenViewModel(forwardingItem: .init(id: .randomEvent,
roomID: "",
content: RoomMessageEventContentWithoutRelationSDKMock()),
let viewModel = MessageForwardingScreenViewModel(forwardingPayload: .init(ids: [.randomEvent],
roomID: "",
contents: [RoomMessageEventContentWithoutRelationSDKMock()]),
userSession: UserSessionMock(.init()),
roomSummaryProvider: summaryProvider,
userIndicatorController: UserIndicatorControllerMock())
@@ -28,7 +28,7 @@ enum PinnedEventsTimelineScreenCoordinatorAction {
case displayUser(userID: String)
case presentLocationViewer(StaticLocationData)
case presentLiveLocationViewer(sender: TimelineItemSender, initialLiveLocationShare: LiveLocationShare)
case displayMessageForwarding(forwardingItem: MessageForwardingItem)
case displayMessageForwarding(forwardingPayload: MessageForwardingPayload)
case displayRoomScreenWithFocussedPin(eventID: String, threadRootEventID: String?)
}
@@ -67,8 +67,8 @@ final class PinnedEventsTimelineScreenCoordinator: CoordinatorProtocol {
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.displayMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.displayMessageForwarding(forwardingPayload: forwardingPayload))
case .viewInRoomTimeline(let eventID, let threadRootEventID):
actionsSubject.send(.displayRoomScreenWithFocussedPin(eventID: eventID, threadRootEventID: threadRootEventID))
case .dismiss:
@@ -84,8 +84,8 @@ final class PinnedEventsTimelineScreenCoordinator: CoordinatorProtocol {
switch action {
case .displaySenderDetails(let userID):
actionsSubject.send(.displayUser(userID: userID))
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.displayMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.displayMessageForwarding(forwardingPayload: forwardingPayload))
case .displayMediaPreview(let mediaPreviewViewModel):
viewModel.displayMediaPreview(mediaPreviewViewModel)
case .displayLocation(let location):
@@ -10,7 +10,7 @@ import Foundation
enum PinnedEventsTimelineScreenViewModelAction {
case viewInRoomTimeline(eventID: String, threadRootEventID: String?)
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
case dismiss
}
@@ -54,11 +54,11 @@ class PinnedEventsTimelineScreenViewModel: PinnedEventsTimelineScreenViewModelTy
mediaPreviewViewModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
case .displayMessageForwarding(let forwardingPayload):
state.bindings.mediaPreviewViewModel = nil
// We need a small delay because we need to wait for the media preview to be fully dismissed.
DispatchQueue.main.asyncAfter(deadline: .now() + TimelineMediaPreviewViewModel.displayMessageForwardingDelay) {
self.actionsSubject.send(.displayMessageForwarding(forwardingItem))
self.actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
case .viewInRoomTimeline(let itemID):
guard let eventID = itemID.eventID else {
@@ -13,6 +13,10 @@ struct PinnedEventsTimelineScreen: View {
@ObservedObject var context: PinnedEventsTimelineScreenViewModel.Context
@ObservedObject var timelineContext: TimelineViewModel.Context
private var isMessageSelectionActive: Bool {
timelineContext.viewState.messageSelection.isActive
}
private var title: String {
let pinnedEventIDs = timelineContext.viewState.pinnedEventIDs
guard !pinnedEventIDs.isEmpty else {
@@ -26,6 +30,11 @@ struct PinnedEventsTimelineScreen: View {
.navigationTitle(title)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.safeAreaInset(edge: .bottom, spacing: 0) {
if isMessageSelectionActive {
TimelineMessageSelectionActionBar(context: timelineContext)
}
}
.background(.compound.bgCanvasDefault)
.interactiveDismissDisabled()
.timelineMediaPreview(viewModel: $context.mediaPreviewViewModel)
@@ -55,9 +64,15 @@ struct PinnedEventsTimelineScreen: View {
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionClose) {
context.send(viewAction: .close)
if isMessageSelectionActive {
TimelineMessageSelectionToolbar {
timelineContext.send(viewAction: .clearMessageSelection)
}
} else {
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionClose) {
context.send(viewAction: .close)
}
}
}
}
@@ -71,28 +86,45 @@ struct PinnedEventsTimelineScreen_Previews: PreviewProvider, TestablePreview {
appSettings: .volatile(),
analyticsService: AnalyticsServiceMock(.init()))
static let emptyTimelineViewModel: TimelineViewModel = {
let timelineController = TimelineControllerMock(.init(timelineKind: .pinned, timelineItems: []))
let appSettings = AppSettings.volatile()
return TimelineViewModel(roomProxy: JoinedRoomProxyMock(.init(name: "Preview room")),
timelineController: timelineController,
userSession: UserSessionMock(.init()),
mediaPlayerProvider: MediaPlayerProviderMock(),
userIndicatorController: UserIndicatorControllerMock(),
appMediator: AppMediatorMock(.init()),
appSettings: appSettings,
analyticsService: AnalyticsServiceMock(.init()),
emojiProvider: EmojiProvider(appSettings: appSettings),
linkMetadataProvider: LinkMetadataProvider(),
timelineControllerFactory: TimelineControllerFactoryMock(.init()))
}()
static let emptyTimelineViewModel = makeTimelineViewModel(timelineItems: [])
static let selectingTimelineViewModel = makeTimelineViewModel(timelineItems: TimelineFixtures.default, isSelecting: true)
static var previews: some View {
ElementNavigationStack {
PinnedEventsTimelineScreen(context: viewModel.context, timelineContext: emptyTimelineViewModel.context)
}
.previewDisplayName("Empty")
ElementNavigationStack {
PinnedEventsTimelineScreen(context: viewModel.context, timelineContext: selectingTimelineViewModel.context)
}
.previewDisplayName("Selecting")
.snapshotPreferences(expect: selectingTimelineViewModel.context.$viewState.map(\.messageSelection.isActive))
}
static func makeTimelineViewModel(timelineItems: [RoomTimelineItemProtocol], isSelecting: Bool = false) -> TimelineViewModel {
let eventIDs = timelineItems.compactMap { ($0 as? EventBasedTimelineItemProtocol)?.id.eventID }
let timelineController = TimelineControllerMock(.init(timelineKind: .pinned, timelineItems: timelineItems))
let appSettings = AppSettings.volatile()
appSettings.messageMultiSelectEnabled = isSelecting
let timelineViewModel = TimelineViewModel(roomProxy: JoinedRoomProxyMock(.init(name: "Preview room", pinnedEventIDs: Set(eventIDs))),
timelineController: timelineController,
userSession: UserSessionMock(.init()),
mediaPlayerProvider: MediaPlayerProviderMock(),
userIndicatorController: UserIndicatorControllerMock(),
appMediator: AppMediatorMock(.init()),
appSettings: appSettings,
analyticsService: AnalyticsServiceMock(.init()),
emojiProvider: EmojiProvider(appSettings: appSettings),
linkMetadataProvider: LinkMetadataProvider(),
timelineControllerFactory: TimelineControllerFactoryMock(.init()))
if isSelecting {
timelineViewModel.state.messageSelection.selectedEventIDs = Set(eventIDs.prefix(2))
}
return timelineViewModel
}
}
@@ -43,7 +43,7 @@ enum RoomScreenCoordinatorAction {
case presentLiveLocationViewer(sender: TimelineItemSender?, initialLiveLocationShare: LiveLocationShare?)
case presentEmojiPicker(selectedEmojis: Set<String>, continuation: EmojiPickerScreenContinuation)
case presentRoomMemberDetails(userID: String)
case presentMessageForwarding(forwardingItem: MessageForwardingItem)
case presentMessageForwarding(forwardingPayload: MessageForwardingPayload)
case presentCallScreen(isVoiceCall: Bool)
case presentPinnedEventsTimeline
case presentResolveSendFailure(failure: TimelineItemSendFailure.VerifiedUser, sendHandle: SendHandleProxy)
@@ -146,8 +146,8 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
caption: composerViewModel.context.plainComposerText))
case .displaySenderDetails(userID: let userID):
actionsSubject.send(.presentRoomMemberDetails(userID: userID))
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.presentMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.presentMessageForwarding(forwardingPayload: forwardingPayload))
case .displayLocation(let location):
actionsSubject.send(.presentLocationViewer(location))
case .displayLiveLocation(let sender, let initialLiveLocationShare):
@@ -200,8 +200,8 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
actionsSubject.send(.presentKnockRequestsList)
case .displayRoom(let roomID, let via):
actionsSubject.send(.presentRoom(roomID: roomID, via: via))
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.presentMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.presentMessageForwarding(forwardingPayload: forwardingPayload))
case .displayThreadList:
actionsSubject.send(.presentThreadList)
case .displayThread(let threadRootEventID, let focussedEventID):
@@ -238,6 +238,10 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
composerViewModel.process(timelineAction: .setFocus)
}
func clearMessageSelection() {
timelineViewModel.clearMessageSelection()
}
func stop() {
composerViewModel.stop()
roomViewModel.stop()
@@ -19,7 +19,7 @@ enum RoomScreenViewModelAction: Equatable {
case removeComposerFocus
case displayKnockRequests
case displayRoom(roomID: String, via: [String])
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
case stopLiveLocationSharing
case displayLiveLocation
}
@@ -149,11 +149,11 @@ class RoomScreenViewModel: RoomScreenViewModelType, RoomScreenViewModelProtocol
switch action {
case .dismiss:
state.bindings.mediaPreviewViewModel = nil
case .displayMessageForwarding(let forwardingItem):
case .displayMessageForwarding(let forwardingPayload):
state.bindings.mediaPreviewViewModel = nil
// We need a small delay because we need to wait for the media preview to be fully dismissed.
DispatchQueue.main.asyncAfter(deadline: .now() + TimelineMediaPreviewViewModel.displayMessageForwardingDelay) {
self.actionsSubject.send(.displayMessageForwarding(forwardingItem))
self.actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
case .viewInRoomTimeline:
fatalError("\(action) should not be visible on a room preview.")
@@ -110,10 +110,14 @@ struct RoomScreen: View {
.environment(\.timelineContext, timelineContext)
// Make sure the reply header honours the hideTimelineMedia setting too.
.environment(\.shouldAutomaticallyLoadImages, !timelineContext.viewState.hideTimelineMedia)
.collapsedInPlace(isSelectionActive)
.collapsedInPlace(isMessageSelectionActive)
if isMessageSelectionActive {
TimelineMessageSelectionActionBar(context: timelineContext)
}
}
}
.navigationBarBackButtonHidden(isSelectionActive)
.navigationBarBackButtonHidden(isMessageSelectionActive)
.toolbarRole(RoomHeaderView.toolbarRole)
.navigationTitle(L10n.screenRoomTitle) // Hidden but used for back button text.
.navigationBarTitleDisplayMode(.inline)
@@ -287,23 +291,12 @@ struct RoomScreen: View {
}
}
private var isSelectionActive: Bool {
timelineContext.viewState.selection.isActive
private var isMessageSelectionActive: Bool {
timelineContext.viewState.messageSelection.isActive
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
if isSelectionActive {
TimelineSelectionToolbar(count: timelineContext.viewState.selection.count) {
timelineContext.send(viewAction: .clearSelection)
}
} else {
roomToolbar
}
}
@ToolbarContentBuilder
private var roomToolbar: some ToolbarContent {
// .principal + .primaryAction works better than .navigation leading + trailing
// as the latter disables interaction in the action button for rooms with long names
ToolbarItem(placement: .principal) {
@@ -314,8 +307,20 @@ struct RoomScreen: View {
mediaProvider: context.mediaProvider) {
context.send(viewAction: .displayRoomDetails)
}
.disabled(isMessageSelectionActive) // The room details would cover the selection.
}
if isMessageSelectionActive {
TimelineMessageSelectionToolbar {
timelineContext.send(viewAction: .clearMessageSelection)
}
} else {
roomActions
}
}
@ToolbarContentBuilder
private var roomActions: some ToolbarContent {
if !ProcessInfo.processInfo.isiOSAppOnMac || context.viewState.isNativeCallingEnabled {
if context.viewState.shouldShowCallButton {
RoomCallControlsToolbar(viewState: context.viewState) { isVoiceCall in
@@ -379,7 +384,7 @@ struct RoomScreen_Previews: PreviewProvider, TestablePreview {
composerToolbar: ComposerToolbar(context: composerViewModel.context))
}
.previewDisplayName("Selecting")
.snapshotPreferences(expect: selectingViewModels.timeline.context.$viewState.map(\.selection.isActive))
.snapshotPreferences(expect: selectingViewModels.timeline.context.$viewState.map(\.messageSelection.isActive))
}
static func makeViewModels(canSendMessage: Bool = true, hasSuccessor: Bool = false, isSelecting: Bool = false) -> ViewModels {
@@ -408,7 +413,7 @@ struct RoomScreen_Previews: PreviewProvider, TestablePreview {
if isSelecting {
let eventIDs = timelineController.timelineItems.compactMap { ($0 as? EventBasedTimelineItemProtocol)?.id.eventID }
timelineViewModel.state.selection.selectedEventIDs = Set(eventIDs.prefix(2))
timelineViewModel.state.messageSelection.selectedEventIDs = Set(eventIDs.prefix(2))
}
return .init(room: roomViewModel, timeline: timelineViewModel)
@@ -88,7 +88,7 @@ struct DeveloperOptionsScreen: View {
Toggle(isOn: $context.messageMultiSelectEnabled) {
Text("Multi-select messages")
Text("Adds a Select action to the message menu to pick several messages at once.")
Text("Forward starts a selection so several messages can be forwarded at once.")
}
}
@@ -38,7 +38,7 @@ enum ThreadTimelineScreenCoordinatorAction {
case presentPollForm(mode: PollFormMode)
case presentEmojiPicker(selectedEmojis: Set<String>, continuation: EmojiPickerScreenContinuation)
case presentRoomMemberDetails(userID: String)
case presentMessageForwarding(forwardingItem: MessageForwardingItem)
case presentMessageForwarding(forwardingPayload: MessageForwardingPayload)
case presentResolveSendFailure(failure: TimelineItemSendFailure.VerifiedUser, sendHandle: SendHandleProxy)
}
@@ -94,8 +94,8 @@ final class ThreadTimelineScreenCoordinator: CoordinatorProtocol {
.sink { [weak self] action in
guard let self else { return }
switch action {
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.presentMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.presentMessageForwarding(forwardingPayload: forwardingPayload))
}
}
.store(in: &cancellables)
@@ -135,8 +135,8 @@ final class ThreadTimelineScreenCoordinator: CoordinatorProtocol {
caption: composerViewModel.context.plainComposerText))
case .displaySenderDetails(userID: let userID):
actionsSubject.send(.presentRoomMemberDetails(userID: userID))
case .displayMessageForwarding(let forwardingItem):
actionsSubject.send(.presentMessageForwarding(forwardingItem: forwardingItem))
case .displayMessageForwarding(let forwardingPayload):
actionsSubject.send(.presentMessageForwarding(forwardingPayload: forwardingPayload))
case .displayResolveSendFailure(let failure, let sendHandle):
actionsSubject.send(.presentResolveSendFailure(failure: failure,
sendHandle: sendHandle))
@@ -179,4 +179,8 @@ final class ThreadTimelineScreenCoordinator: CoordinatorProtocol {
func focusOnEvent(eventID: String) {
Task { await timelineViewModel.focusOnEvent(eventID: eventID) }
}
func clearMessageSelection() {
timelineViewModel.clearMessageSelection()
}
}
@@ -9,7 +9,7 @@
import Foundation
enum ThreadTimelineScreenViewModelAction {
case displayMessageForwarding(MessageForwardingItem)
case displayMessageForwarding(MessageForwardingPayload)
}
struct ThreadTimelineScreenViewState: BindableState {
@@ -66,11 +66,11 @@ class ThreadTimelineScreenViewModel: ThreadTimelineScreenViewModelType, ThreadTi
switch action {
case .viewInRoomTimeline:
fatalError("\(action) should not be visible on a thread preview.")
case .displayMessageForwarding(let forwardingItem):
case .displayMessageForwarding(let forwardingPayload):
state.bindings.mediaPreviewViewModel = nil
// We need a small delay because we need to wait for the media preview to be fully dismissed.
DispatchQueue.main.asyncAfter(deadline: .now() + TimelineMediaPreviewViewModel.displayMessageForwardingDelay) {
self.actionsSubject.send(.displayMessageForwarding(forwardingItem))
self.actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
case .dismiss:
state.bindings.mediaPreviewViewModel = nil
@@ -30,7 +30,7 @@ struct ThreadTimelineScreen: View {
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.toolbarBackground(.visible, for: .navigationBar) // Fix the toolbar's background.
.navigationBarBackButtonHidden(isSelectionActive)
.navigationBarBackButtonHidden(isMessageSelectionActive)
.timelineMediaPreview(viewModel: $context.mediaPreviewViewModel)
.overlay(alignment: .top) {
FloatingDateBadge(dateText: timelineContext.floatingDate?.formattedDateSeparator()) {
@@ -44,19 +44,25 @@ struct ThreadTimelineScreen: View {
}
}
.safeAreaInset(edge: .bottom, spacing: 0) {
composer
.padding(.top, 8)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.environmentObject(timelineContext)
.environment(\.timelineContext, timelineContext)
// Make sure the reply header honours the hideTimelineMedia setting too.
.environment(\.shouldAutomaticallyLoadImages, !timelineContext.viewState.hideTimelineMedia)
.collapsedInPlace(isSelectionActive)
VStack(spacing: 0) {
composer
.padding(.top, 8)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.environmentObject(timelineContext)
.environment(\.timelineContext, timelineContext)
// Make sure the reply header honours the hideTimelineMedia setting too.
.environment(\.shouldAutomaticallyLoadImages, !timelineContext.viewState.hideTimelineMedia)
.collapsedInPlace(isMessageSelectionActive)
if isMessageSelectionActive {
TimelineMessageSelectionActionBar(context: timelineContext)
}
}
}
}
private var isSelectionActive: Bool {
timelineContext.viewState.selection.isActive
private var isMessageSelectionActive: Bool {
timelineContext.viewState.messageSelection.isActive
}
@ViewBuilder
@@ -70,22 +76,22 @@ struct ThreadTimelineScreen: View {
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
if isSelectionActive {
TimelineSelectionToolbar(count: timelineContext.viewState.selection.count) {
timelineContext.send(viewAction: .clearSelection)
// .principal + .primaryAction works better than .navigation leading + trailing
// as the latter disables interaction in the action button for rooms with long names
ToolbarItem(placement: .principal) {
RoomHeaderView(roomName: L10n.commonThread,
roomSubtitle: context.viewState.roomTitle,
roomAvatar: context.viewState.roomAvatar,
dmRecipientDetails: context.viewState.dmRecipientDetails,
roomHistorySharingState: context.viewState.roomHistorySharingState,
mediaProvider: context.mediaProvider) {
// There is no action but the iOS 26 designs have it looking like a button.
}
} else {
// .principal + .primaryAction works better than .navigation leading + trailing
// as the latter disables interaction in the action button for rooms with long names
ToolbarItem(placement: .principal) {
RoomHeaderView(roomName: L10n.commonThread,
roomSubtitle: context.viewState.roomTitle,
roomAvatar: context.viewState.roomAvatar,
dmRecipientDetails: context.viewState.dmRecipientDetails,
roomHistorySharingState: context.viewState.roomHistorySharingState,
mediaProvider: context.mediaProvider) {
// There is no action but the iOS 26 designs have it looking like a button.
}
}
if isMessageSelectionActive {
TimelineMessageSelectionToolbar {
timelineContext.send(viewAction: .clearMessageSelection)
}
}
}
@@ -224,8 +224,8 @@ class TimelineInteractionHandler {
analyticsService.trackInteraction(name: .PinnedMessageListViewTimeline)
guard let eventID = itemID.eventID else { return }
actionsSubject.send(.viewInRoomTimeline(eventID: eventID))
case .downloadMedia, .selectMessages:
break // Handled by the media preview screen and the TimelineViewModel respectively.
case .downloadMedia:
break // Handled inline in the media preview screen.
case .translate:
guard let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol else { return }
actionsSubject.send(.showTranslation(text: messageTimelineItem.body))
@@ -22,7 +22,7 @@ enum TimelineViewModelAction {
case displayEditPollForm(eventID: String, poll: Poll)
case displayMediaUploadPreviewScreen(mediaURLs: [URL])
case displaySenderDetails(userID: String)
case displayMessageForwarding(forwardingItem: MessageForwardingItem)
case displayMessageForwarding(forwardingPayload: MessageForwardingPayload)
case displayMediaPreview(TimelineMediaPreviewViewModel)
case displayLocation(StaticLocationData)
case displayLiveLocation(sender: TimelineItemSender, initialLiveLocationShare: LiveLocationShare)
@@ -69,11 +69,11 @@ enum TimelineViewAction {
/// The user has confirmed the removal of an item, optionally giving a reason.
case redactConfirmed(itemID: TimelineItemIdentifier, reason: String?)
/// Start a multi-selection with the specified item.
case startSelection(itemID: TimelineItemIdentifier)
/// Add or remove an item from the active multi-selection.
case toggleSelection(itemID: TimelineItemIdentifier)
case clearSelection
case toggleMessageSelection(itemID: TimelineItemIdentifier)
case clearMessageSelection
/// Forward the selected messages, in timeline order.
case forwardMessageSelection
case tappedOnSenderDetails(sender: TimelineItemSender)
case displayReactionSummary(itemID: TimelineItemIdentifier, key: String)
@@ -137,7 +137,7 @@ struct TimelineViewState: BindableState {
var linkPreviewsEnabled: Bool
var jumpToReadMarkerEnabled: Bool
var selection: TimelineSelectionState
var messageSelection: TimelineMessageSelectionState
let hasPredecessor: Bool
@@ -206,12 +206,10 @@ struct TimelineViewStateBindings {
}
/// The state of the multi-selection of messages, active as soon as an item is selected.
struct TimelineSelectionState: Equatable {
static let limit = 30
struct TimelineMessageSelectionState: Equatable {
static let limit = 10
/// Mirrors the `messageMultiSelectEnabled` feature flag.
var isEnabled = false
/// The event IDs of the selected items. Only remote messages can be selected.
var selectedEventIDs: Set<String> = []
var isActive: Bool {
@@ -354,12 +352,12 @@ enum ScrollDirection: Equatable {
}
extension TimelineViewState {
/// Multi-selection is only offered in the room and thread timelines.
/// Multi-selection is offered everywhere but the media timelines.
var canSelectMessages: Bool {
guard selection.isEnabled else { return false }
guard messageSelection.isEnabled else { return false }
return switch timelineKind {
case .live, .detached, .thread: true
case .pinned, .media: false
case .live, .detached, .thread, .pinned: true
case .media: false
}
}
@@ -103,7 +103,7 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
areThreadsEnabled: appSettings.threadsEnabled,
linkPreviewsEnabled: appSettings.linkPreviewsEnabled,
jumpToReadMarkerEnabled: appSettings.jumpToReadMarkerEnabled,
selection: .init(isEnabled: appSettings.messageMultiSelectEnabled),
messageSelection: .init(isEnabled: appSettings.messageMultiSelectEnabled),
hasPredecessor: roomProxy.predecessorRoom != nil,
pinnedEventIDs: roomProxy.infoPublisher.value.pinnedEventIDs,
emojiProvider: emojiProvider,
@@ -198,7 +198,7 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
}
case .displayTimelineItemMenu(let itemID):
timelineInteractionHandler.displayTimelineItemActionMenu(for: itemID)
case .handleTimelineItemMenuAction(let itemID, .selectMessages):
case .handleTimelineItemMenuAction(let itemID, .forward) where state.canSelectMessages:
startSelection(itemID: itemID)
case .handleTimelineItemMenuAction(let itemID, let action):
timelineInteractionHandler.handleTimelineItemMenuAction(action, itemID: itemID)
@@ -206,12 +206,12 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
state.bindings.redactConfirmationInfo = nil
// A blank reason is no reason at all, so don't send one.
timelineInteractionHandler.redact(itemID, reason: reason?.isBlank == false ? reason : nil)
case .startSelection(let itemID):
startSelection(itemID: itemID)
case .toggleSelection(let itemID):
case .toggleMessageSelection(let itemID):
toggleSelection(itemID: itemID)
case .clearSelection:
state.selection.selectedEventIDs.removeAll()
case .clearMessageSelection:
clearMessageSelection()
case .forwardMessageSelection:
forwardSelection()
case .tappedOnSenderDetails(let sender):
handleTappedOnSenderDetails(sender: sender)
case .displayEmojiPicker(let itemID):
@@ -313,11 +313,6 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
await userSession.liveLocationManager.stopLiveLocation(roomID: roomProxy.id)
}
func makeForwardingItem(for itemID: TimelineItemIdentifier) async -> MessageForwardingItem? {
guard let content = await timelineController.messageEventContent(for: itemID) else { return nil }
return .init(id: itemID, roomID: roomProxy.id, content: content)
}
// MARK: - Private
private func handleTappedOnSenderDetails(sender: TimelineItemSender) {
@@ -1059,13 +1054,6 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
state.bindings.readReceiptsSummaryInfo = .init(orderedReceipts: eventTimelineItem.properties.orderedReadReceipts, id: eventTimelineItem.id)
}
// MARK: - Message forwarding
private func forwardMessage(itemID: TimelineItemIdentifier) async {
guard let forwardingItem = await makeForwardingItem(for: itemID) else { return }
actionsSubject.send(.displayMessageForwarding(forwardingItem: forwardingItem))
}
// MARK: Pills
private func pillContextUpdater(_ pillContext: PillContext) {
@@ -1185,68 +1173,106 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
}
}
// MARK: - Message forwarding
extension TimelineViewModel {
func makeForwardingPayload(for itemIDs: [TimelineItemIdentifier]) async -> MessageForwardingPayload? {
var ids = [TimelineItemIdentifier]()
var contents = [RoomMessageEventContentWithoutRelation]()
for itemID in itemIDs {
guard let content = await timelineController.messageEventContent(for: itemID) else { continue }
ids.append(itemID)
contents.append(content)
}
guard !contents.isEmpty else { return nil }
return .init(ids: ids, roomID: roomProxy.id, contents: contents)
}
private func forwardMessage(itemID: TimelineItemIdentifier) async {
guard let forwardingPayload = await makeForwardingPayload(for: [itemID]) else { return }
actionsSubject.send(.displayMessageForwarding(forwardingPayload: forwardingPayload))
}
}
// MARK: - Selection
extension TimelineViewModel {
private func setupSelectionSubscriptions() {
appSettings.messageMultiSelectEnabledPublisher
.sink { [weak self] isEnabled in
self?.state.selection.isEnabled = isEnabled
self?.state.messageSelection.isEnabled = isEnabled
if !isEnabled {
self?.state.selection.selectedEventIDs.removeAll()
self?.state.messageSelection.selectedEventIDs.removeAll()
}
}
.store(in: &cancellables)
}
private func startSelection(itemID: TimelineItemIdentifier) {
guard state.canSelectMessages, let eventID = selectableEventID(for: itemID) else { return }
guard let eventID = selectableEventID(for: itemID) else { return }
// The composer is collapsed while selecting, so don't leave the microphone open behind it.
Task { await timelineInteractionHandler.stopRecordingVoiceMessageIfNeeded() }
actionsSubject.send(.composer(action: .removeFocus))
guard !state.selection.isAtLimit || state.selection.selectedEventIDs.contains(eventID) else {
guard !state.messageSelection.isAtLimit || state.messageSelection.selectedEventIDs.contains(eventID) else {
showSelectionLimitToast()
return
}
state.selection.selectedEventIDs.insert(eventID)
state.messageSelection.selectedEventIDs.insert(eventID)
}
private func toggleSelection(itemID: TimelineItemIdentifier) {
guard state.selection.isActive, let eventID = selectableEventID(for: itemID) else { return }
guard state.messageSelection.isActive, let eventID = selectableEventID(for: itemID) else { return }
if state.selection.selectedEventIDs.contains(eventID) {
state.selection.selectedEventIDs.remove(eventID)
} else if state.selection.isAtLimit {
if state.messageSelection.selectedEventIDs.contains(eventID) {
state.messageSelection.selectedEventIDs.remove(eventID)
} else if state.messageSelection.isAtLimit {
showSelectionLimitToast()
} else {
state.selection.selectedEventIDs.insert(eventID)
state.messageSelection.selectedEventIDs.insert(eventID)
}
}
/// Drops selected items that are no longer selectable (e.g. redacted), or the whole selection
/// when the timeline is swapped, so the selection always refers to items that are on screen.
private func reconcileSelection(with timelineItems: [RoomTimelineItemProtocol], isSwitchingTimelines: Bool) {
guard state.selection.isActive else { return }
guard state.messageSelection.isActive else { return }
if isSwitchingTimelines {
state.selection.selectedEventIDs.removeAll()
state.messageSelection.selectedEventIDs.removeAll()
return
}
let selectableEventIDs = timelineItems.compactMap { item -> String? in
guard let item = item as? EventBasedTimelineItemProtocol, item.isBulkSelectable else { return nil }
return item.id.eventID
}
state.selection.selectedEventIDs.formIntersection(selectableEventIDs)
let forwardableEventIDs = timelineItems.forwardableItems.compactMap(\.id.eventID)
state.messageSelection.selectedEventIDs.formIntersection(forwardableEventIDs)
}
/// The event ID of the item, when it is part of this timeline and can be bulk selected.
/// Ends the selection, either from the close button or once the selected messages have been forwarded.
func clearMessageSelection() {
state.messageSelection.selectedEventIDs.removeAll()
}
/// Forwards the selection in timeline order, which is unrelated to the order the messages were selected in.
/// The selection is kept until the forwarding completes, so cancelling the picker returns to it.
private func forwardSelection() {
let itemIDs = timelineController.timelineItems.selectedItems(state.messageSelection.selectedEventIDs).map(\.id)
Task {
guard let forwardingPayload = await makeForwardingPayload(for: itemIDs) else {
displayErrorToast(L10n.errorUnknown)
return
}
actionsSubject.send(.displayMessageForwarding(forwardingPayload: forwardingPayload))
}
}
/// The event ID of the item, when it is part of this timeline and can be forwarded.
private func selectableEventID(for itemID: TimelineItemIdentifier) -> String? {
guard let item = timelineController.timelineItems.firstUsingStableID(itemID) as? EventBasedTimelineItemProtocol,
item.isBulkSelectable else {
item.isForwardable else {
return nil
}
return item.id.eventID
@@ -19,6 +19,8 @@ protocol TimelineViewModelProtocol {
func focusOnEvent(eventID: String) async
/// Stops the current live location sharing
func stopLiveLocationSharing() async
/// Handles getting the content to forward an item given its item ID.
func makeForwardingItem(for itemID: TimelineItemIdentifier) async -> MessageForwardingItem?
/// Handles getting the contents to forward the given items, keeping the order of the given IDs.
func makeForwardingPayload(for itemIDs: [TimelineItemIdentifier]) async -> MessageForwardingPayload?
/// Ends the message selection, e.g. once the selected messages have been forwarded.
func clearMessageSelection()
}
@@ -339,7 +339,6 @@ struct TimelineItemMenu_Previews: PreviewProvider, TestablePreview {
pinnedEventIDs: [],
isViewSourceEnabled: true,
areThreadsEnabled: true,
isMultiSelectEnabled: false,
timelineKind: .live,
emojiProvider: EmojiProvider(appSettings: .volatile()))
guard let actions = provider.makeActions() else { return nil }
@@ -68,7 +68,6 @@ enum TimelineItemMenuAction: Identifiable, Hashable {
case reply(isThread: Bool)
case replyInThread
case forward(itemID: TimelineItemIdentifier)
case selectMessages
case viewSource
case report
case react
@@ -170,8 +169,6 @@ enum TimelineItemMenuAction: Identifiable, Hashable {
Label(L10n.actionReplyInThread, icon: \.threads)
case .forward:
Label(L10n.actionForward, icon: \.forward)
case .selectMessages:
Label(L10n.actionSelect, icon: \.check)
case .redact(let isMedia):
Label(isMedia ? L10n.actionDeleteFile : L10n.actionRemoveMessage, icon: \.delete)
case .viewSource:
@@ -17,7 +17,6 @@ struct TimelineItemMenuActionProvider {
let pinnedEventIDs: Set<String>
let isViewSourceEnabled: Bool
let areThreadsEnabled: Bool
let isMultiSelectEnabled: Bool
let timelineKind: TimelineKind
let emojiProvider: EmojiProviderProtocol
@@ -66,10 +65,6 @@ struct TimelineItemMenuActionProvider {
actions.append(.forward(itemID: item.id))
}
if isMultiSelectEnabled, item.isBulkSelectable {
actions.append(.selectMessages)
}
if item.isEditable, canCurrentUserSendMessage {
if item.supportsMediaCaption {
if item.hasMediaCaption {
@@ -9,7 +9,7 @@
import SwiftUI
/// How a timeline item takes part in an active multi-selection, for accessibility purposes.
enum TimelineItemAccessibilitySelection {
enum TimelineItemAccessibilityMessageSelection {
/// No selection is active, the item offers its regular message actions.
case none
/// A selection is active, the item acts as a toggle when it can be selected.
@@ -18,7 +18,7 @@ enum TimelineItemAccessibilitySelection {
private struct TimelineItemAccessibilityModifier: ViewModifier {
let timelineItem: RoomTimelineItemProtocol
let selection: TimelineItemAccessibilitySelection
let selection: TimelineItemAccessibilityMessageSelection
let action: () -> Void
private var isSelecting: Bool {
@@ -77,7 +77,7 @@ private struct TimelineItemAccessibilityModifier: ViewModifier {
}
}
case .selecting(let isSelected):
if let item = timelineItem as? EventBasedTimelineItemProtocol, item.isBulkSelectable {
if let item = timelineItem as? EventBasedTimelineItemProtocol, item.isForwardable {
view
.accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)
.accessibilityAction(.default, action)
@@ -91,7 +91,7 @@ private struct TimelineItemAccessibilityModifier: ViewModifier {
extension View {
func timelineItemAccessibility(_ timelineItem: RoomTimelineItemProtocol,
selection: TimelineItemAccessibilitySelection = .none,
selection: TimelineItemAccessibilityMessageSelection = .none,
action: @escaping () -> Void) -> some View {
modifier(TimelineItemAccessibilityModifier(timelineItem: timelineItem, selection: selection, action: action))
}
@@ -42,12 +42,12 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
return context.viewState.pinnedEventIDs.contains(eventID)
}
private var isSelectionActive: Bool {
context.viewState.selection.isActive
private var isMessageSelectionActive: Bool {
context.viewState.messageSelection.isActive
}
private var isSelected: Bool {
context.viewState.selection.contains(timelineItem.id.eventID)
context.viewState.messageSelection.contains(timelineItem.id.eventID)
}
/// The base padding applied to bubbles on either side.
@@ -61,18 +61,17 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
}
var body: some View {
HStack(spacing: 0) {
if isSelectionActive {
HStack(spacing: 10) {
if isMessageSelectionActive {
selectionIndicator
}
bubble
}
.padding(EdgeInsets(top: 1, leading: 8, bottom: 1, trailing: 8))
.background(isSelected ? Color.compound.bgAccentSelected : .clear)
.highlightedTimelineItem(isFocussed)
.overlay { selectionOverlay }
.animation(.elementDefault.disabledDuringTests(), value: isSelectionActive)
.animation(.elementDefault.disabledDuringTests(), value: isMessageSelectionActive)
.onPreferenceChange(ContentScanningFailurePreferenceKey.self) { contentScanningFailure = $0 }
}
@@ -80,7 +79,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
// The ZStack keeps the transition on the indicator's appearance rather than its checked state.
ZStack {
ListRowAccessory.multiSelection(isSelected)
.opacity(timelineItem.isBulkSelectable ? 1 : 0) // Keeps the bubbles aligned.
.opacity(timelineItem.isForwardable ? 1 : 0) // Keeps the bubbles aligned.
}
.padding(.leading, 8)
.transition(.move(edge: .leading).combined(with: .opacity))
@@ -90,7 +89,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
/// Captures every touch while selecting so the content's own gestures can't fire.
@ViewBuilder
private var selectionOverlay: some View {
if isSelectionActive {
if isMessageSelectionActive {
Color.clear
.contentShape(Rectangle())
.onTapGesture { toggleSelection() }
@@ -172,8 +171,8 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
// Figma overlaps reactions by 3
VStack(alignment: alignment, spacing: -3) {
messageBubbleWithActions
.timelineItemAccessibility(timelineItem, selection: isSelectionActive ? .selecting(isSelected: isSelected) : .none) {
if isSelectionActive {
.timelineItemAccessibility(timelineItem, selection: isMessageSelectionActive ? .selecting(isSelected: isSelected) : .none) {
if isMessageSelectionActive {
toggleSelection()
} else {
context.send(viewAction: .displayTimelineItemMenu(itemID: timelineItem.id))
@@ -189,7 +188,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
isLayoutRTL: timelineItem.isOutgoing)
// Workaround to stop the message long press stealing the touch from the reaction buttons
.onTapGesture { }
.accessibilityHidden(isSelectionActive)
.accessibilityHidden(isMessageSelectionActive)
}
if context.viewState.areThreadsEnabled,
@@ -199,7 +198,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
context.send(viewAction: .displayThread(itemID: timelineItem.id))
}
.padding(5)
.accessibilityHidden(isSelectionActive)
.accessibilityHidden(isMessageSelectionActive)
}
}
}
@@ -213,7 +212,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
// specific taps within the timeline views themselves.
}
// The UIKit recogniser would still receive touches through the selection overlay.
.longPressWithFeedback(isEnabled: !isSelectionActive) {
.longPressWithFeedback(isEnabled: !isMessageSelectionActive) {
context.send(viewAction: .displayTimelineItemMenu(itemID: timelineItem.id))
}
.swipeRightAction {
@@ -221,13 +220,13 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
.foregroundColor(.compound.iconPrimary)
.accessibilityHidden(true)
} shouldStartAction: {
!isSelectionActive && timelineItem.canBeRepliedTo
!isMessageSelectionActive && timelineItem.canBeRepliedTo
} action: {
context.send(viewAction: .handleTimelineItemMenuAction(itemID: timelineItem.id,
action: .reply(isThread: timelineItem.properties.isThreaded)))
}
.contextMenu {
if !isSelectionActive {
if !isMessageSelectionActive {
macContextMenu
}
}
@@ -245,7 +244,6 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
pinnedEventIDs: context.viewState.pinnedEventIDs,
isViewSourceEnabled: context.viewState.isViewSourceEnabled,
areThreadsEnabled: context.viewState.areThreadsEnabled,
isMultiSelectEnabled: context.viewState.canSelectMessages,
timelineKind: context.viewState.timelineKind,
emojiProvider: context.viewState.emojiProvider)
TimelineItemMacContextMenu(item: timelineItem, actionProvider: provider) { action in
@@ -298,8 +296,8 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
}
private func toggleSelection() {
guard timelineItem.isBulkSelectable else { return }
context.send(viewAction: .toggleSelection(itemID: timelineItem.id))
guard timelineItem.isForwardable else { return }
context.send(viewAction: .toggleMessageSelection(itemID: timelineItem.id))
}
private var messageBubbleTopPadding: CGFloat {
@@ -478,7 +476,7 @@ struct TimelineItemBubbledStylerView_Previews: PreviewProvider, TestablePreview
emojiProvider: EmojiProvider(appSettings: appSettings),
linkMetadataProvider: LinkMetadataProvider(),
timelineControllerFactory: TimelineControllerFactoryMock(.init()))
viewModel.state.selection.selectedEventIDs = ["selected"]
viewModel.state.messageSelection.selectedEventIDs = ["selected"]
return viewModel
}()
@@ -0,0 +1,40 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
/// Replaces the composer while messages are being selected, offering the action to take on them.
struct TimelineMessageSelectionActionBar: View {
@ObservedObject var context: TimelineViewModelType.Context
var body: some View {
Button {
context.send(viewAction: .forwardMessageSelection)
} label: {
Label(L10n.actionForwardMessages(context.viewState.messageSelection.count), icon: \.forward)
}
.buttonStyle(.compound(.primary))
.padding(16)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
}
}
// MARK: - Previews
struct TimelineMessageSelectionActionBar_Previews: PreviewProvider, TestablePreview {
static let viewModel: TimelineViewModel = {
let viewModel = TimelineViewModel.mock() // A fresh instance so the shared mock isn't left selecting.
viewModel.state.messageSelection.selectedEventIDs = ["$1", "$2", "$3"]
return viewModel
}()
static var previews: some View {
TimelineMessageSelectionActionBar(context: viewModel.context)
.previewLayout(.sizeThatFits)
}
}
@@ -0,0 +1,19 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import SwiftUI
/// The trailing navigation bar item that cancels the selection of messages in a timeline.
struct TimelineMessageSelectionToolbar: ToolbarContent {
let onCancel: () -> Void
var body: some ToolbarContent {
ToolbarItem(placement: .primaryAction) {
ToolbarButton(role: .cancel, action: onCancel)
}
}
}
@@ -1,27 +0,0 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
/// The navigation bar content shown while messages are being selected in a timeline.
struct TimelineSelectionToolbar: ToolbarContent {
let count: Int
let onCancel: () -> Void
var body: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel, role: .cancel, action: onCancel)
}
ToolbarItem(placement: .principal) {
Text(L10n.screenRoomSelectionCount(count))
.font(.compound.bodyLGSemibold)
.foregroundStyle(.compound.textPrimary)
}
}
}
@@ -41,7 +41,6 @@ struct TimelineView: View {
pinnedEventIDs: timelineContext.viewState.pinnedEventIDs,
isViewSourceEnabled: timelineContext.viewState.isViewSourceEnabled,
areThreadsEnabled: timelineContext.viewState.areThreadsEnabled,
isMultiSelectEnabled: timelineContext.viewState.canSelectMessages,
timelineKind: timelineContext.viewState.timelineKind,
emojiProvider: timelineContext.viewState.emojiProvider)
.makeActions()